Search completed in 1.39 seconds.
3098 results for "true":
Your results are loading. Please wait...
NS ENSURE TRUE
Summary Macro Returns return-value if expr evaluates to false. Syntax NS_ENSURE_TRUE( expr, return-value ); Usage nsresult mozMyClass::MozStringMucking() { char *foo = new char[123]; NS_ENSURE_TRUE(foo, NS_ERROR_OUT_OF_MEMORY); // This is equivalent to doing: if (!foo) return NS_ERROR_OUT_OF_MEMORY; // Thou shalt not return NS_ERROR_FAILURE.. ...
... Summary Macro Returns return-value if expr evaluates to false. Syntax NS_ENSURE_TRUE( expr, return-value ); Usage nsresult mozMyClass::MozStringMucking() { char *foo = new char[123]; NS_ENSURE_TRUE(foo, NS_ERROR_OUT_OF_MEMORY); // This is equivalent to doing: if (!foo) return NS_ERROR_OUT_OF_MEMORY; // Thou shalt not return NS_ERROR_FAILURE.. ...
...age nsresult mozMyClass::MozStringMucking() { char *foo = new char[123]; NS_ENSURE_TRUE(foo, NS_ERROR_OUT_OF_MEMORY); // This is equivalent to doing: if (!foo) return NS_ERROR_OUT_OF_MEMORY; // Thou shalt not return NS_ERROR_FAILURE.. ...
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). If using the Fetch API, make sure Request.credentials is "omit". ...
... If using Server-sent events, make sure EventSource.withCredentials is false (it's the default value). If using the Fetch API, make sure Request.credentials is "omit". ...
...ls' What went wrong? The CORS request requires that the server permit the use of credentials, but the server's Access-Control-Allow-Credentials header's value isn't set to true to enable their use. To fix this problem on the client side, revise the code to not request the use of credentials. If the request is being issued using XMLHttpRequest, make sure you're not setting withCredentials to true. If using Server-sent events, make sure EventSource.withCredentials is false (it's the default value). If using the Fetch API, make sure Request.credentials is "omit". To eliminate this error by changing the server's configuration, adjust the server's configuration to set the Access-Control-Allow-Credentials header's value to true. ...
JS::TrueHandleValue
This article covers features introduced in SpiderMonkey 38 The JS::Value that represents the JavaScript value true. Syntax const JS::HandleValue JS::TrueHandleValue; const JS::HandleValue JS::FalseHandleValue; Description JS::TrueHandleValue and JS::FalseHandleValue are JS::HandleValue constants that represent the JavaScript values true and false. See Also MXR ID Search for JS::TrueHandleValue MXR ID Search for JS::FalseHandleValue JS::NullHandleValue JS::UndefinedHandleValue bug 959787 ...
JS::TrueValue
This article covers features introduced in SpiderMonkey 24 Create a JS::Value that represents the JavaScript value true. Syntax JS::Value JS::TrueValue() Description JS::TrueValue creates a JS::Value that represents the JavaScript value true. See Also MXR ID Search for JS::TrueValue JS::Value JS::BooleanValue JS::FalseValue ...
JSVAL_TRUE
Obsolete since JSAPI 42This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. 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. Take care not to confuse the jsval constants JSVAL_TRUE and JSVAL_FALSE with the bool constants true and false. jsval values must not be used as C true/false values; there is no guarantee that the C bit-pattern of any particular jsval is zero or nonzero. See Also MXR ID Search for JSVAL_TRUE MXR I...
true - XPath
Web › XPath › Functions › true
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The true function returns a boolean value of true. Syntax true() Returns Boolean true. Defined XPath 1.0 4.3 Gecko support Supported. ...
Index - Web APIs
Web › API › Index
ace represents a signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. 11 AbortSignal.aborted API, AbortSignal, Experimental, Property, Reference, aborted The aborted read-only property returns a Boolean that indicates whether the DOM request(s) the signal is communicating with is/are aborted (true) or not (false). 12 AbortSignal.onabort API, AbortSignal, Event Handler, Experimental, Fetch, Property, Reference, onabort The onabort read-only property of the FetchSignal interface is an event handler Invoked when an abort event fires, i.e. when the fetch request(s) the signal is communicating with is/are aborted. 13 AbortSignal: abort event abort, events ...
...AbstractRange abstract interface is the base class upon which all DOM range types are defined. A range is an object that indicates the start and end points of a section of content within the document. 17 AbstractRange.collapsed API, AbstractRange, DOM, DOM API, Empty, Property, Range, Reference, collapsed The collapsed read-only property of the AbstractRange interface returns true if the range's start position and end position are the same. 18 AbstractRange.endContainer API, AbstractRange, DOM, DOM API, End, Node, Position, Property, Range, Read-only, Reference, container, endContainer The endContainer property of the AbstractRange interface returns the Node in which the end of the range is located. 19 AbstractRange.endOffset API, Abstra...
...rSourceNode.loopEnd API, Audio, AudioBufferSourceNode, Media, Property, Reference, Web Audio API, loopEnd, sound A floating-point number indicating the offset, in seconds, into the audio buffer at which each loop will loop return to the beginning of the loop (that is, the current play time gets reset to AudioBufferSourceNode.loopStart). This property is only used if the loop property is true. 118 AudioBufferSourceNode.loopStart API, Audio, AudioBufferSourceNode, Media, Property, Reference, Web Audio API, loopStart, sound The loopStart property of the AudioBufferSourceNode interface is a floating-point value indicating, in seconds, where in the AudioBuffer the restart of the play must happen. 119 AudioBufferSourceNode.playbackRate API, AudioBufferSo...
...And 113 more matches
Index
AN_TO_JSVAL converts a bool argument, b, to a boolean jsval. 19 DOUBLE_TO_JSVAL JSAPI Reference, Obsolete, SpiderMonkey DOUBLE_TO_JSVAL is the inverse of JS::ToNumber. 20 INT_FITS_IN_JSVAL JSAPI Reference, Obsolete, SpiderMonkey Determines if a specified C integer value, i, lies within the range allowed for integer jsvals. If so, INT_FITS_IN_JSVAL returns TRUE, and i can be cast to jsval by calling INT_TO_JSVAL(i). Otherwise, INT_FITS_IN_JSVAL returns FALSE. In this case, the application can still convert i to a jsval using JS_NewNumberValue. 21 INT_TO_JSVAL JSAPI Reference, Obsolete, SpiderMonkey INT_TO_JSVAL converts a C integer, i, to a jsval. 22 JS::Add*Root JSAPI Reference, NeedsContent, Obsolete, Reference, Ref...
...ooted JSAPI Reference, Reference, Reference(2), SpiderMonkey Here, ptr represents the private member of JS::PersistentRooted<T>, typed with T. 61 JS::PropertySpecNameEqualsId JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::PropertySpecNameEqualsId determines if the given JSPropertySpec::name or JSFunctionSpec::name value equals the given jsid, and returns true if so. 62 JS::PropertySpecNameIsSymbol JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::PropertySpecNameIsSymbol determines if the given JSPropertySpec::name or JSFunctionSpec::name value is actually a symbol code and not a string, and returns true if so. 63 JS::PropertySpecNameToPermanentId JSAPI Reference, Reference, Reference(2), SpiderMonkey ...
...79 JS::ToUint32 JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::ToInt32 converts a JavaScript value to an unsigned 32bit integer. It implements the ToInt32 operator described in ECMA 262-3 ?9.6. 80 JS::ToUint64 JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::ToInt64 converts a JavaScript value to an unsigned 64bit integer. 81 JS::TrueHandleValue JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::TrueHandleValue and JS::FalseHandleValue are JS::HandleValue constants that represent the JavaScript values true and false. 82 JS::TrueValue JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::TrueValue creates a JS::Value that represents the JavaScript value true. 83 JS::Undefin...
...And 44 more matches
jspage - Archive of obsolete content
slice.call(arguments); return b.prototype[c].apply(d.shift(),d);};}};Native.implement=function(d,c){for(var b=0,a=d.length;b<a;b++){d[b].implement(c);}};Native.typize=function(a,b){if(!a.type){a.type=function(c){return($type(c)===b); };}};(function(){var a={Array:Array,Date:Date,Function:Function,Number:Number,RegExp:RegExp,String:String};for(var h in a){new Native({name:h,initialize:a[h],protect:true}); }var d={"boolean":Boolean,"native":Native,object:Object};for(var c in d){Native.typize(d[c],c);}var f={Array:["concat","indexOf","join","lastIndexOf","pop","push","reverse","shift","slice","sort","splice","toString","unshift","valueOf"],String:["charAt","charCodeAt","concat","indexOf","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","val...
...typize(d[c],c);}var f={Array:["concat","indexOf","join","lastIndexOf","pop","push","reverse","shift","slice","sort","splice","toString","unshift","valueOf"],String:["charAt","charCodeAt","concat","indexOf","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","valueOf"]}; for(var e in f){for(var b=f[e].length;b--;){Native.genericize(a[e],f[e][b],true);}}})();var Hash=new Native({name:"Hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getClean()); }for(var b in a){this[b]=a[b];}return this;}});Hash.implement({forEach:function(b,c){for(var a in this){if(this.hasOwnProperty(a)){b.call(c,this[a],a,this); }}},getClean:function(){var b={};for(var a in this){if(this.hasOwnProperty(a)){b[a]=this[a];}}return b;},getLength:function(){var b=...
...ndow.ActiveXObject)?false:((window.XMLHttpRequest)?((document.querySelectorAll)?6:5):4);},webkit:function(){return(navigator.taintEnabled)?false:((Browser.Features.xpath)?((Browser.Features.query)?525:420):419); },gecko:function(){return(!document.getBoxObjectFor&&window.mozInnerScreenX==null)?false:((document.getElementsByClassName)?19:18);}}},Browser||{});Browser.Platform[Browser.Platform.name]=true; Browser.detect=function(){for(var b in this.Engines){var a=this.Engines[b]();if(a){this.Engine={name:b,version:a};this.Engine[b]=this.Engine[b+a]=true; break;}}return{name:b,version:a};};Browser.detect();Browser.Request=function(){return $try(function(){return new XMLHttpRequest();},function(){return new ActiveXObject("MSXML2.XMLHTTP"); },function(){return new ActiveXObject("Microsoft.XMLHTTP");...
...And 40 more matches
Equality comparisons and sameness - JavaScript
If the values have different types, the values are considered unequal. If the values have the same type, are not numbers, and have the same value, they're considered equal. Finally, if both values are numbers, they're considered equal if they're both not NaN and are the same value, or if one is +0 and one is -0. 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. For all values except numbers,...
... between +0 and -0, strict equality treats them as the same value. The second is that floating point includes the concept of a not-a-number value, NaN, to represent the solution to certain ill-defined mathematical problems: negative infinity added to positive infinity, for example. Strict equality treats NaN as unequal to every other value -- including itself. (The only case in which (x !== x) is true is when x is NaN.) Loose equality using == Loose equality compares two values for equality, after converting both values to a common type. After conversions (one or both sides may undergo conversions), the final equality comparison is performed exactly as === performs it. Loose equality is symmetric: A == B always has identical semantics to B == A for any values of A and B (except for the order...
...xactly as === performs it. Loose equality is symmetric: A == B always has identical semantics to B == A for any values of A and B (except for the order of applied conversions). ...
...And 36 more matches
Theme changes in Firefox 2 - Archive of obsolete content
e styles bookmarksProperties.xul. Note: This CSS may be moved out into a separate file that will be referenced by both files in the future. ...
...d by both files in the future. ...
...re. ...
...And 33 more matches
JXON - Archive of obsolete content
ent node. /*\ |*| |*| JXON Snippet #1 MDNDeveloper Network |*| |*| https://developer.mozilla.org/docs/JXON |*| https://developer.mozilla.org/User:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. ...
... |*| https://developer.mozilla.org/docs/JXON |*| https://developer.mozilla.org/User:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. ...
...de of it. /*\ |*| |*| JXON Snippet #2 MDNDeveloper Network |*| |*| https://developer.mozilla.org/docs/JXON |*| https://developer.mozilla.org/User:fusionchess |*| |*| This framework is released under the GNU Public License, version 3 or later. ...
...And 28 more matches
Color picker tool - CSS: Cascading Style Sheets
le */ .resize-handle { width: 10px; height: 10px; background: url('https://mdn.mozillademos.org/files/6083/resize.png') center center no-repeat; position: absolute; bottom: 0; right: 0; } [data-resize='both']:hover { cursor: nw-resize !important; } [data-resize='width']:hover { cursor: w-resize !important; } [data-resize='height']:hover { cursor: n-resize !important; } [data-hidden='true'] { display: none; } [data-collapsed='true'] { height: 0 !important; } .block { display: table; } /** * Container */ #container { width: 100%; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; display: table; } /** * Picker Zone */ #picker { padding: 10px; width: 980px; } .ui-color-picker { padding: 3px 5px; float: left; border-color:...
... 30px; overflow: hidden; position: relative; float: left; transition: all 0.2s; } #picker-samples .sample { width: 40px; height: 40px; margin: 5px; border: 1px solid #DDD; position: absolute; float: left; transition: all 0.2s; } #picker-samples .sample:hover { cursor: pointer; border-color: #BBB; transform: scale(1.15); border-radius: 3px; } #picker-samples .sample[data-active='true'] { border-color: #999; } #picker-samples .sample[data-active='true']:after { content: ""; position: absolute; background: url('https://mdn.mozillademos.org/files/6065/arrow.png') center no-repeat; width: 100%; height: 12px; top: -12px; z-index: 2; } #picker-samples #add-icon { width: 100%; height: 100%; position: relative; box-shadow: inset 0px 0px 2px 0px #DDD; } #picker-samples ...
...r: 1px solid #DDD; display: table; float: left; } #controls .icon:hover { cursor: pointer; } #controls .picker-icon { background-image: url('https://mdn.mozillademos.org/files/6081/picker.png'); } #controls #void-sample { margin-right: 10px; background-image: url('https://mdn.mozillademos.org/files/6087/void.png'); background-position: center left; } #controls #void-sample[data-active='true'] { border-color: #CCC; background-position: center right; } #controls .switch { width: 106px; padding: 1px; border: 1px solid #CCC; font-size: 14px; text-align: center; line-height: 24px; overflow: hidden; float: left; } #controls .switch:hover { cursor: pointer; } #controls .switch > * { width: 50%; padding: 2px 0; background-color: #EEE; float: left; } #controls .switch [dat...
...And 28 more matches
Expressions and operators - JavaScript
om arrays or objects using a syntax that mirrors the construction of array and object literals. var foo = ['one', 'two', 'three']; // without destructuring var one = foo[0]; var two = foo[1]; var three = foo[2]; // with destructuring var [one, two, three] = foo; Comparison operators A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conver...
... comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code: var var1 = 3; var var2 = 4; Comparison operators Operator Description Examples returning true Equal (==) Returns true if the operands are equal. 3 == var1 "3" == var1 3 == '3' Not equal (!=) Returns true if the operands are not equal. var1 != 4 var2 != "3" Strict equal (===) Returns true if the operands are equal and of the same type. See also Object.is and sameness in JS. 3 === var1 Strict not equal (!==) Returns tr...
...e if the operands are not equal. var1 != 4 var2 != "3" Strict equal (===) Returns true if the operands are equal and of the same type. See also Object.is and sameness in JS. 3 === var1 Strict not equal (!==) Returns true if the operands are of the same type but not equal, or are of different type. var1 !== "3" 3 !== '3' Greater than (>) Returns true if the left operand is greater than the right operand. var2 > var1 "12" > 2 Greater than or equal (>=) Returns true if the left operand is greater than or equal to the right operand. ...
...And 28 more matches
Proxy Auto-Configuration (PAC) file - HTTP
was used to test the following syntax examples. The PAC file is named proxy.pac Command line: pactester -p ~/pacparser-master/tests/proxy.pac -u http://www.mozilla.org (passes the host parameter www.mozilla.org and the url parameter http://www.mozilla.org) isPlainHostName() Syntax isPlainHostName(host) Parameters host The hostname from the URL (excluding port number). Description True if and only if there is no domain name in the hostname (no dots). Examples isPlainHostName("www.mozilla.org") // false isPlainHostName("www") // true dnsDomainIs() Syntax dnsDomainIs(host, domain) Parameters host Is the hostname from the URL. domain Is the domain name to test the hostname against. Description Returns true if and only if the domain of hostname matches. Examples d...
...stname (no dots). Examples isPlainHostName("www.mozilla.org") // false isPlainHostName("www") // true dnsDomainIs() Syntax dnsDomainIs(host, domain) Parameters host Is the hostname from the URL. domain Is the domain name to test the hostname against. Description Returns true if and only if the domain of hostname matches. 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. hostdom Fully qualified hostname to match against. Description Is true if the hostname matches exactly the specified hostname, or if there is no domain name part in the hostname, but the unqualified hostname matches. Examples localH...
...OrDomainIs() Syntax localHostOrDomainIs(host, hostdom) Parameters host The hostname from the URL. hostdom Fully qualified hostname to match against. Description Is true if the hostname matches exactly the specified hostname, or if there is no domain name part in the hostname, but the unqualified hostname matches. Examples localHostOrDomainIs("www.mozilla.org" , "www.mozilla.org") // true (exact match) localHostOrDomainIs("www" , "www.mozilla.org") // true (hostname match, domain not specified) localHostOrDomainIs("www.google.com" , "www.mozilla.org") // false (domain name mismatch) localHostOrDomainIs("home.mozilla.org", "www.mozilla.org") // false (hostname mismatch) isResolvable() Syntax isResolvable(host) Parameters host is the hostname from the URL. Tri...
...And 25 more matches
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
r *dbdir, CERTName *subject, const char *subjectStr, const char *certReqFileName) { PRBool validationFailed = PR_FALSE; if (!subject) { PR_fprintf(PR_STDERR, "%s -G -d %s -s: improperly formatted name: \"%s\"\n", progName, dbdir, subjectStr); validationFailed = PR_TRUE; } if (!certReqFileName) { PR_fprintf(PR_STDERR, "%s -G -d %s -s %s -r: certificate request file name not found\n", progName, dbdir, subjectStr); validationFailed = PR_TRUE; } if (validationFailed) { fprintf(stderr, "\nUsage: %s %s \n\n", progName, "-G -d <dbdirpath> -s <subject> -r <csr> \n"); exit(-1);...
...st char *certReqFileName, const char *issuerNameStr, const char *serialNumberStr, PRBool selfsign) { PRBool validationFailed = PR_FALSE; if (!nickNameStr) { PR_fprintf(PR_STDERR, "%s -A -d %s -n : nick name is missing\n", progName, dbdir); validationFailed = PR_TRUE; } if (!trustStr) { PR_fprintf(PR_STDERR, "%s -A -d %s -n %s -t: trust flag is missing\n", progName, dbdir, nickNameStr); validationFailed = PR_TRUE; } if (!certFileName) { PR_fprintf(PR_STDERR, "%s -A -d %s -n %s -t %s -c: certificate file name not found\n", progName, dbdir, nickNameStr, trustStr, serialNumber...
...STDERR, "%s -A -d %s -n %s -t: trust flag is missing\n", progName, dbdir, nickNameStr); validationFailed = PR_TRUE; } if (!certFileName) { PR_fprintf(PR_STDERR, "%s -A -d %s -n %s -t %s -c: certificate file name not found\n", progName, dbdir, nickNameStr, trustStr, serialNumberStr, certReqFileName); validationFailed = PR_TRUE; } if (PR_Access(certFileName, PR_ACCESS_EXISTS) == PR_FAILURE) { if (!certReqFileName) { PR_fprintf(PR_STDERR, "%s -A -d %s -n %s -t %s -c %s -r: certificate file or certificate request file is not found\n", progName, dbdir, nickNameStr, trustStr, certFileName); validationFailed = PR_TRUE; } if (!selfsign && !
...And 22 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
linear-gradient generator HTML Content <div id="container"> <div id="gradient-container" data-alpha="true"> </div> <div id="controls"> <div class="section"> <div class="title"> Active point </div> <div class="property"> <div class="ui-input-slider" data-topic="point-position" data-info="position" data-unit="px" data-min="-1000" data-value="0" data-max="1000" data-sensivity="5"></div> <div id="delete-point" class="button"> delete point </div> </div> <div class="ui-color-picker" data-topic="picker"></div> </div> <div class="section"> <div class="title"> Active axis </div> ...
...ding: 0 0.3em; border: 1px solid #3490D2; border-color: #208B20; background: #666; background-color: #EEF1F5; color: #000; position: absolute; top: 100%; left: 0; z-index: 100; overflow: hidden; transition: all 0.3s; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .ui-dropdown-list:hover { overflow: auto; } .ui-dropdown-list[data-hidden='true'] { height: 0 !important; opacity: 0; visibility: hidden; } .ui-dropdown[data-position='left'] .ui-dropdown-list { left: -100%; top: 0; } .ui-dropdown[data-position='right'] .ui-dropdown-list { left: 100%; top: 0; } .ui-dropdown-list > div { width: 80%; height: 1.6em; margin: 0.3em 0; padding: 0.3em 10%; line-height: 1.6em; } .ui-dropdown-list > div:hover { background: #3490D2; ...
...m 10%; line-height: 1.6em; } .ui-dropdown-list > div:hover { background: #3490D2; color:#FFF; border-radius: 2px; cursor: pointer; } /* * COLOR PICKER TOOL */ body { width: 100%; height: 100%; margin: 0 auto; font-family: "Segoe UI", Arial, Helvetica, sans-serif; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; } body[data-dragging="true"] { } /** * Resize Handle */ .resize-handle { width: 10px; height: 10px; background: url("images/resize.png") center center no-repeat; position: absolute; bottom: 0; right: 0; } [data-resize='both']:hover { cursor: nw-resize !important; } [data-resize='width']:hover { cursor: w-resize !important; } [data-resize='height']:hover { cursor: n-resize !important; } /** * Main Containe...
...And 22 more matches
Shell global objects
If the property is omitted or v is null, don't attribute the source to any DOM element. ...
...If the property is omitted or v is null, don't attribute the source to any DOM element. elementAttributeName if present and not undefined, the name of prop...
...ned, the name of property of element that holds this code. This is what Debugger.Source.prototype.elementAttributeName returns. sourceMapURL if present with value v, convert v to a string, and provide that as the code's source map URL. If omitted, attach no source map URL to the code (although the code may provide one itself, via a //#sourceMappingURL comment). ...
...And 21 more matches
Browser Feature Detection - Archive of obsolete content
DOM 1 HTML 100% 100% 100% 100% / 100% 100% / 100% DOM CSS 1 100% 100% 100% 100% / 100% 96% / 96% DOM CSS 2 100% 98% 67% 71% / 83% 38% / 42% Test Results Cross Reference DOM Core Level 1 Support for properties/methods in document name Firefox 1.5 IE 6 & 7 Opera 8.54 - 9.01 Document.doctype true true true Document.implementation true true true Document.documentElement true true true Document.createElement() true true true Document.createDocumentFragment() true true true Document.createTextNode() true true true Document.createComment() true true true Document.createCD...
... 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/me...
...reateAttribute() true true true Document.createEntityReference()Obsolete since Gecko 7 (method present but only returns null: bug 9850) false false Document.getElementsByTagName() true true true DOM Core Level 2 Support for properties/methods in document name Firefox 1.5 IE 6 & 7 Opera 8.54 - 9.01 Document.doctype true true true Document.implementation true true true Document.documentElement true true true Document.createElement() true true true Document.createDocumentFragment() true true true Document.createTextNode() true true true Document.createComment() true true true Document.createCD...
...And 20 more matches
sample2
1); } /* * Validate the options used for Generate CSR command */ static void ValidateGenerateCSRCommand(const char *progName, const char *dbdir, CERTName *subject, const char *subjectStr, const char *certReqFileName) { PRBool validationFailed = PR_FALSE; if (!subject) { PR_fprintf(PR_STDERR, "%s -G -d %s -s: improperly formatted name: \"%s\"\n", progName, dbdir, subjectStr); validationFailed = PR_TRUE; } if (!certReqFileName) { PR_fprintf(PR_STDERR, "%s -G -d %s -s %s -r: certificate request file name not found\n", progName, dbdir, subjectStr); validationFailed = PR_TRUE; } if (validationFailed) { fprintf(stderr, "\nUsage: %s %s \n\n", progName, "-G -d <dbdirpath> -s <subject> -r <csr> \n"); exit(-1); } } /* * Validate the options used for Add Cert to DB command */ static void ValidateAddCertT...
...teAddCertToDBCommand(const char *progName, const char *dbdir, const char *nickNameStr, const char *trustStr, const char *certFileName, const char *certReqFileName, const char *issuerNameStr, const char *serialNumberStr, PRBool selfsign) { PRBool validationFailed = PR_FALSE; if (!nickNameStr) { PR_fprintf(PR_STDERR, "%s -A -d %s -n : nick name is missing\n", progName, dbdir); validationFailed = PR_TRUE; } if (!trustStr) { PR_fprintf(PR_STDERR, "%s -A -d %s -n %s -t: trust flag is missing\n", progName, dbdir, nickNameStr); validationFailed = PR_TRUE; } if (!certFileName) { PR_fprintf(PR_STDERR, "%s -A -d %s -n %s -t %s -c: certificate file name not found\n", progName, dbdir, nickNameStr, trustStr, serialNumberStr, certReqFileName); validationFailed = PR_TRUE; } if (PR_Access(certFileName, PR_ACC...
...t found\n", progName, dbdir, nickNameStr, trustStr, serialNumberStr, certReqFileName); validationFailed = PR_TRUE; } if (PR_Access(certFileName, PR_ACCESS_EXISTS) == PR_FAILURE) { if (!certReqFileName) { PR_fprintf(PR_STDERR, "%s -A -d %s -n %s -t %s -c %s -r: certificate file or certificate request file is not found\n", progName, dbdir, nickNameStr, trustStr, certFileName); validationFailed = PR_TRUE; } if (!selfsign && !issuerNameStr) { PR_fprintf(PR_STDERR, "%s -A -d %s -n %s -t %s -c %s -r %s -u : issuer name is missing\n", progName, dbdir, nickNameStr, trustStr, certFileName, certReqFileName); validationFailed = PR_TRUE; } if (!serialNumberStr) { PR_fprintf(PR_STDERR, "%s -A -d %s -n %s -t %s -c %s -r %s -u %s -m : serial number is missing\n", progName, dbdir, nickNameStr, trustStr, certF...
...And 20 more matches
Box-shadow generator - CSS: Cascading Style Sheets
</div> </div> <div id="element_properties" class="category"> <div class="title"> Class element properties </div> <div class="group"> <div class="group property"> <div class="ui-slider-name"> border </div> <div class="ui-checkbox" data-topic='border-state' data-state="true"></div> </div> <div id="z-index" class="slidergroup"> <div class="ui-slider-name"> z-index </div> <div class="ui-slider-btn-set" data-topic="z-index" data-type="sub"></div> <div class="ui-slider" data-topic="z-index" data-min="-10" data-max="10" data-step="1"...
...ition: absolute; top: 2px; } #output .button { width: 90px; height: 22px; margin: 0 5px 0 0; text-align: center; line-height: 20px; font-size: 14px; color: #FFF; background-color: #999; border-top-left-radius: 3px; border-top-right-radius: 3px; bottom: -5px; float:left; } #output .button:hover { color: #FFF; background-color: #666; cursor: pointer; } #output .menu [data-active="true"] { color: #777; background-color: #FFF; border: 1px solid #CCC; border-bottom: none; } #output .menu [data-topic="before"] { left: 100px; } #output .menu [data-topic="after"] { left: 200px; } #output .output { width: 480px; margin: 10px; padding: 10px; overflow: hidden; color: #555; font-size: 14px; border: 1px dashed #CCC; border-radius: 3px; display: none; -moz-box-sizing: ...
...e('data-max') | 0; var step = node.getAttribute('data-step') | 0; var value = node.getAttribute('data-value') | 0; var snap = node.getAttribute('data-snap'); var topic = node.getAttribute('data-topic'); this.min = min; this.max = max > 0 ? max : 100; this.step = step === 0 ? 1 : step; this.value = value <= max && value >= min ? ...
...And 20 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
veSession, select, setSelectionRange, syncSessions Examples (example needed) Attributes accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. alwaysopenpopup Obsolete since Gecko 1.9.1 Type: boolean Note: Applies to: Thunderbird and SeaMonkeyIf true, the autocomplete popup will be displayed even when there are no matches. If false, the default value, the popup will be hidden. This attribute is obsolete as of Gecko 1.9.1; to control the display of the popup, use the minresultsforpopup attribute instead. autocompletesearch New in Thunderbird 2Requires SeaMonkey 1.1 Type: space-separated list of values A space-separate...
...earched. ldap New in Thunderbird 25 Requires SeaMonkey 2.22 The user's LDAP directory is searched. autocompletesearchparam New in Thunderbird 2 Requires SeaMonkey 1.1 Type: string A string which is passed to the search component. autoFill Obsolete since Gecko 1.9.1 Type: boolean Note: Applies to: Thunderbird and SeaMonkeyIf set to true, the best match will be filled into the textbox as the user types. If false, the default, the value will not be filled in until the user selects an item. As of Gecko 1.9.1, this attribute is now always specified in lower case. autoFillAfterMatch Obsolete since Gecko 1.9.1 Type: boolean If set to true, the entire text of the best match will be displayed at the end of the input. If false, ...
...t be filled in until the user selects an item. As of Gecko 1.9.1, this attribute is now always specified in lower case. autoFillAfterMatch Obsolete since Gecko 1.9.1 Type: boolean If set to true, the entire text of the best match will be displayed at the end of the input. If false, only the text that hasn't been entered yet will be filled in. The textbox.autoFill attribute must be set to true to use this feature. As of Gecko 1.9.1, this attribute is superseded by the completedefaultindex attribute. autofill New in Thunderbird 3 Requires SeaMonkey 2.0 Type: boolean If set to true, the best match will be filled into the textbox as the user types. If false, the default, the value will not be filled in until the user selects an item. completedefaultindex ...
...And 18 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 fa...
...-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 && bInve...
...You could safely remove all or some of them, * depending on your needs. If you want to remove them and are using the Daemon.safe subsystem you * should also remove the Daemon.safe global object methods that require them. **/ Daemon.construct = function (aArgs) { ...
...And 17 more matches
Making decisions in your code — conditionals - Learn web development
", and the outcome of "ate two cookies" might be "felt full, but mom scolded me for eating all the cookies".) if...else statements Let's look at by far the most common type of conditional statement you'll use in JavaScript -- the humble if...else statement. Basic if ... else syntax Basic if...else syntax looks like the following in pseudocode: if (condition) { code to run if condition is true } else { run some other code instead } Here we've got: The keyword if followed by some parentheses. A condition to test, placed inside the parentheses (typically "is this value bigger than this other value?", or "does this value exist?"). The condition makes use of the comparison operators we discussed in the last module and returns true or false. A set of curly braces, inside which we ha...
... some parentheses. A condition to test, placed inside the parentheses (typically "is this value bigger than this other value?", or "does this value exist?"). The condition makes use of the comparison operators we discussed in the last module and returns true or false. A set of curly braces, inside which we have some code -- this can be any code we like, and it only runs if the condition returns true. The keyword else. ...
...ndition makes use of the comparison operators we discussed in the last module and returns true or false. A set of curly braces, inside which we have some code -- this can be any code we like, and it only runs if the condition returns true. The keyword else. Another set of curly braces, inside which we have some more code -- this can be any code we like, and it only runs if the condition is not true -- or in other words, the condition is false. ...
...And 17 more matches
sslfnc.html
plication will have two threads, one reading and one writing, or just one thread doing reads and writes alternately. 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. An application that wishes to do sumultaneous reads and writes should set this to PR_TRUE. In NSS 2.8, the SSL_ENABLE_FDX option only affects the behavior of non-blocking SSL sockets. See the description below for more information on this option. SSL_ENABLE_SSL3 enables the application to communicate with SSL v3. Factory setting is on. If you turn this option off, an attempt to establish a connection with a peer that only...
... SSL3. It uses the SSL version number 3.1, appearing to be a "minor" revision of SSL 3.0. NSS 2.8 supports TLS in addition to SSL2 and SSL3. You can think of it as "SSL_ENABLE_SSL3.1". See the description below for more information about this option. SSL_V2_COMPATIBLE_HELLO tells the SSL library whether or not to send SSL3 client hello messages in SSL2-compatible format. If set to PR_TRUE, it will; otherwise, it will not. Factory setting is on (PR_TRUE). See the description below for more information on this option. SSL_NO_CACHE disallows use of the session cache. Factory setting is off. If you turn this option on, this socket will be unable to resume a session begun by another socket. When this socket's session is finished, no other socket will be able to resume the ...
...roperate with TLS clients ( such as certain versions of Microsoft Internet Explorer) that do not conform to the TLS specification regarding rollback attacks. Important: turning this option off means that your code will not comply with the TLS 3.1 and SSL 3.0 specifications regarding rollback attack and will therefore be vulnerable to this form of attack. on PR_TRUE turns option on; PR_FALSE turns option off. Returns The function returns one of these values: If successful, SECSuccess. If unsuccessful, SECFailure. Use PR_GetError to obtain the error code. Description This function changes the default values for all subsequently opened sockets as long as the current application program is running. This function must be called onc...
...And 17 more matches
nsIDOMWindowUtils
OT_AVAILABLE if the count can't be provided. focusedInputType string The type of the currently-focused HTML <input> element, if one is focused. imageAnimationMode unsigned short Returns the image animation mode of the window. The attribute's value must be one of the animationMode values from imgIContainer. IMEIsOpen boolean Returns the IME open state. True if it's open, otherwise false. This attribute only works when IMEStatus is IME_STATUS_ENABLED. Read only. IMEStatus unsigned long Returns the current IME status. Values correspond to the IME_STATUS_* constants defined below. Read only. isMozAfterPaintPending boolean Returns true if a MozAfterPaint event has been queued but not yet fired. Read only. layerM...
...nly. layerManagerType AString What type of layer manager the widget associated with this window is using. "Basic" is unaccelerated; other types are accelerated. Throws an error if there is no widget associated with this window. Read only. outerWindowID unsigned long long The ID of the window's outer window. Read only. paintingSuppressed boolean true if painting is currently suppressed for this window; otherwise false. Read only. This is used on mobile, for example, to prevent attempts to render content until enough of the page has been loaded to avoid content bouncing around excessively as more content is loaded. screenPixelsPerCSSPixel float Returns the number of screen pixels per CSS pixel. Read only. aud...
...all the MediaElements in this window. We have audioMuted and audioVolume to preserve the volume across mute/umute. audioVolume float Range: greater or equal to 0. The real volume level is affected by the volume of all ancestor windows. ...
...And 16 more matches
Image file type and format guide - Web media technologies
3, Opera 46, Safari 8 Maximum dimensions 2,147,483,647x2,147,483,647 pixels Supported color modes Color mode Bits per component (D) Description Greyscale 1, 2, 4, 8, and 16 Each pixel consists of a single D-bit value indicating the brightness of the greyscale pixel. True color 8 and 16 Each pixel is represented by three D-bit values indicating the level of the red, green, and blue color components. Indexed color 1, 2, 4, and 8 Each pixel is a D-bit value indicating an index into a color palette which is contained within a PLTE chunk in the APNG file; the colors in the palette all use an 8-bit depth. ...
...h pixel is a D-bit value indicating an index into a color palette which is contained within a PLTE chunk in the APNG file; the colors in the palette all use an 8-bit depth. Greyscale with alpha 8 and 16 Each pixel is represented by two D-bit values: the intensity of the greyscale pixel and an alpha sample, indicating how opaque the pixel is. True color with alpha 8 and 16 Each pixel is comprised of four D-pixel color components: red, green, blue, and the alpha sample indicating how opaque the pixel is. Compression Lossless Licensing Free and open under the Creative Commons Attribution-ShareAlike license (CC-BY-SA) version 3.0 or later. BMP (Bitmap file) The BMP (Bitmap im...
...fari Maximum dimensions Either 32,767x32,767 or 2,147,483,647x2,147,483,647 pixels, depending on the format version Supported color modes Color mode Bits per component (D) Description Greyscale 1 Each bit represents a single pixel, which can be either black or white. True color 8 and 16 Each pixel is represented by three values representing the red, green, and blue color components; each is D bits. Indexed color 2, 4, and 8 Each pixel is represented by a value which is one 2, 4, or 8 bits, serving as an index into the color table. Greyscale with alpha n/a BMP has no distinct graysc...
...And 16 more matches
Equality (==) - JavaScript
in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x == y Description The equality operators (== and !=) use the Abstract Equality Comparison Algorithm to compare two operands. ...
...thub.com/mdn/interactive-examples and send us a pull request. Syntax x == y Description The equality operators (== and !=) use the Abstract Equality Comparison Algorithm to compare two operands. This can be roughly summarised as follows: If the operands are both objects, return true only if both operands reference the same object. If one operand is null and the other is undefined, return true. If the operands are of different types, try to convert them to the same type before comparing: When comparing a number to a string, try to convert the string to a numeric value. If one of the operands is Boolean, convert the Boolean operand to 1 if it is true and +0 if it is false. If one of the operands is an object and the other is a number or a string, try to convert the object t...
...string to a numeric value. If one of the operands is Boolean, convert the Boolean operand to 1 if it is true and +0 if it is false. If one of the operands is an object and the other is a number or a string, try to convert the object to a primitive using the object's valueOf() and toString() methods. If the operands have the same type, they are compared as follows: String: return true only if both operands have the same characters in the same order. Number: return true only if both operands have the same value. +0 and -0 are treated as the same value. If either operand is NaN, return false. Boolean: return true only if operands are both true or both false. The most notable difference between this operator and the strict equality (===) operator is that the strict e...
...And 14 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
etenv("USER") != "") { // *NIX settings var env_user = getenv("USER"); var env_home = getenv("HOME"); } else { // Windows settings var env_user = getenv("USERNAME"); var env_home = getenv("HOMEPATH"); } var env_mozdebug= getenv("MOZILLA_DEBUG"); // var env_user = prompt("indiquez votre login", toto); // 2) lock general preferences //LDAP address book lockPref("ldap_2.prefs_migrated", true); lockPref("ldap_2.servers.LDAPINT.auth.savePassword", true); lockPref("ldap_2.servers.LDAPINT.description", "LDAP INT"); lockPref("ldap_2.servers.LDAPINT.filename", "abook-1.mab"); lockPref("ldap_2.servers.LDAPINT.uri", "ldap://ldap1.int-evry.Fr:389/ou=people,dc=int-evry,dc=fr??sub"); lockPref("ldap_2.servers.history.filename", "history.mab"); lockPref("ldap_2.servers.history.replication.lastCha...
...draft_folder", "imap://" + env_user + "@imap-int.int-evry.fr/Drafts"); lockPref("mail.identity.id1.drafts_folder_picker_mode", "0"); lockPref("mail.identity.id1.fcc_folder", "imap://" + env_user + "@imap-int.int-evry.fr/Sent"); lockPref("mail.identity.id1.fcc_folder_picker_mode", "0"); lockPref("mail.identity.id1.organization", "INT Evry France"); lockPref("mail.identity.id1.overrideGlobal_Pref", true); lockPref("mail.identity.id1.reply_to", ""); //IMAP lockPref("mail.server.server2.hostname", "imap-int.int-evry.fr"); lockPref("mail.server.server2.isSecure", true); lockPref("mail.server.server2.login_at_startup", true); lockPref("mail.server.server2.max_cached_connections", 5); //lockPref("mail.server.server2.name", "jehan.procaccia@int-evry.fr"); lockPref("mail.server.server2.type", "imap");...
....name", "jehan.procaccia@int-evry.fr"); lockPref("mail.server.server2.type", "imap"); lockPref("mail.server.server2.userName", env_user); //SMTP lockPref("mail.identity.id1.smtpServer", "smtp1"); lockPref("mail.identity.id1.stationery_folder", "imap://" + env_user + "@imap-int.int-evry.fr/Templates"); lockPref("mail.identity.id1.tmpl_folder_picker_mode", "0"); lockPref("mail.identity.id1.valid", true); //SMTP general lockPref("mail.smtp.defaultserver", "smtp1"); lockPref("mail.smtpserver.smtp1.auth_method", 0); lockPref("mail.smtpserver.smtp1.hostname", "smtp-int.int-evry.fr"); lockPref("mail.smtpserver.smtp1.port", 25); lockPref("mail.smtpserver.smtp1.try_ssl", 0); lockPref("mail.smtpserver.smtp1.username", ""); lockPref("mail.smtpservers", "smtp1"); lockPref("mail.startup.enabledMailCheckO...
...And 13 more matches
textbox - Archive of obsolete content
. disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...t with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. ...
...The value may still be adjusted with the keyboard. The default value is false. ...
...And 13 more matches
OS.File for the main thread
y exists: let encoder = new TextEncoder(); // This encoder can be reused for several writes let array = encoder.encode("This is some text"); // Convert the text to an array let promise = OS.File.writeAtomic("file.txt", array, // Write the array atomically to "file.txt", using as temporary {tmpPath: "file.txt.tmp", noOverwrite: true}); // buffer "file.txt.tmp". These examples require Firefox 19 or a more recent version. Example: Rename a file You have to use OS.File.move to rename a file: let promise = OS.File.move("oldname.txt", "newname.txt", {noOverwrite:true}); Here's a working example which renames test.txt to testRenamed.txt if the file is located in directory C:\Jean\ var promise = OS.File.mo...
... Example: Copy a file The following snippet copies file "oldname.txt" to "newname.txt". On most operating systems, this operation is handled directly by the operating system itself, which makes it as fast as possib...
...e - in most cases, function OS.File.writeAtomic is a better choice. let writeStream = function writeStream(data, outFile, chunkSize) { let view = new Uint8Array(data); let loop = function loop(pos) { // Define a recursive asynchronous loop. if (pos <= view.byteLength) { // Note: Should this be pos >= view.byteLength ? return Promise.resolve(true); // Loop end. } let promise = file.write(view.subarray(pos, chunkSize)); // Write a subset of |data| return promise.then(function onSuccess(bytes) { return loop(pos + bytes); // ... and loop. }); }; let promise = loop(0); // Ente...
...And 13 more matches
Encrypt Decrypt_MAC_Using Token
(PR_STDERR, "Could not read SymKey CKA_ID attribute\n"); return rv; } return rv; } /* * Generate a Symmetric Key. ...
...gin(slot)) { rv = PK11_Authenticate(slot, PR_TRUE, pwdata); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Could not authenticate to token %s.\n", PK11_GetTokenName(slot)); return NULL; } } /* Generate the symmetric key. ...
... */ SECStatus Crypt(PK11Context *ctx, unsigned char *out, unsigned int *outLen, unsigned int maxOut, unsigned char *in, unsigned int inLen) { SECStatus rv; rv = PK11_CipherOp(ctx, out, outLen, maxOut, in, inLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Crypt Failed : PK11_CipherOp retur...
...And 13 more matches
Bytecode Descriptions
Int32 Operands: (int32_t val) Stack: => val Push the int32_t immediate operand as an Int32Value. JSOp::Zero, JSOp::One, JSOp::Int8, JSOp::Uint16, and JSOp::Uint24 are all compact encodings for JSOp::Int32. Zero Stack: => 0 Push the number 0. One Stack: => 1 Push the number 1. ...
...an throw. Implements: Relational Operators: Evaluation. Format: JOF_IC Instanceof Stack: value, target => (value instanceof target) The instanceof operator. This throws a TypeError if target is not an object. It calls target[Symbol.hasInstance](value) if the method exists. On success, the result is always a boolean value. Format: JOF_IC In Stack: id, obj => (id in obj) The in operator. Push true if obj has a property with the key id. Otherwise push false. This throws a TypeError if obj is not an object. This can fire proxy hooks and can throw. On success, the result is always a boolean value. Format: JOF_IC Lsh, Rsh, Ursh Stack: lval, rval => (lval OP rval) Bitwise shift operators (<<, >>, >>>). Pop two values, convert them to integers, perform a bitwise shift, and push the result. Co...
...t actually pushes the preconstructed object script->getObject(objectIndex) right onto the stack. The object must be a singleton PlainObject or ArrayObject. The spec requires that an ObjectLiteral or ArrayLiteral creates a new object every time it's evaluated, so this instruction must not be used anywhere it might be executed more than once. There's a shell-only option, newGlobal({cloneSingletons: true}), that makes this instruction do a deep copy of the object. A few tests use it. Format: JOF_OBJECT ObjWithProto Stack: proto => obj Create and push a new ordinary object with the provided [[Prototype]]. This is used to create the .prototype object for derived classes. Defining properties InitProp Operands: (uint32_t nameIndex) Stack: obj, val => obj Define a data property on an object. o...
...And 13 more matches
BasicCardResponse - Web APIs
// Call show() to trigger the browser's payment flow. request.show().then(function(instrumentResponse) { // Do something with the response from the UI. }) .catch(function(err) { // Do something with the error from re...
... // Call show() to trigger the browser's payment flow. request.show().then(function(instrumentResponse) { // Do something with the response from the UI. }) .catch(function(err) { // Do something with the error from request.show(). }); } catch (e) { // Catch any ot...
...To change preferences in Firefox, visit about:config.IE No support NoOpera No support ...
...And 13 more matches
@font-feature-values - CSS: Cascading Style Sheets
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support 9.1WebView Android No support NoChrome Android No support NoFire...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support 9.3Samsung Internet Android No support No@annotationChrome No support NoEdge No support ...
...To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support 9.1WebView Android No support NoChrome Android No support NoFire...
...And 13 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
e'll emit a checkAll event to signal that all the todos should be checked/unchecked. When the second button is clicked, we'll emit a removeCompleted event to signal that all of the completed todos should be removed. ...
...function to the following: const checkAllTodos = (completed) => { todos.forEach(t => t.completed = completed) console.log('todos', todos) } Go back to your browser, open your DevTools console, and click Check All/Uncheck All a few times. 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. This also means that in this case, a reactive statement like $: console.log('todos', todos) won't be very useful. To find out why this is happening, we need to understand how reactivity works in Svelte when updating arrays and objects. Many web frameworks use the virtual DOM technique to update the page. Basically, the virtual DOM is an in-memory cop...
...j. In our checkAllTodos() function, when we run: todos.forEach(t => t.completed = completed) Svelte will not mark todos as changed because it does not know that when we update our t variable inside the forEach() method, we are also modifying the todos array. And that makes sense, because otherwise Svelte would be aware of the inner workings of the forEach() method; the same would therefore be true for any method attached to any object or array. Nevertheless, there are different techniques that we can apply to solve this problem, and all of them involve assigning a new value to the variable being watched. Like we already saw, we could just tell Svelte to update the variable with a self-assignment, like this: const checkAllTodos = (completed) => { todos.forEach(t => t.completed = comple...
...And 12 more matches
CustomizableUI.jsm
widgets can be placed. CustomizableUI assumes that each area it is told about is present in every browser window. CustomizableUI is aware of two types of areas: toolbars and the menu panel. Areas are registered using the registerArea method and unregistered using the unregisterArea method. When a customizable toolbar's XBL binding is constructed (generally, that is when a <toolbar customizable="true"/> node is appended to the document and isn't invisible), the binding will call into CustomizableUI and register the toolbar's node as being one of the concrete instances of its area. For each area, CustomizableUI keeps track of a list of the widgets they contain, generally refered to as 'placements'. This is analogous to the old currentset attribute. If consumers make a change to the placements...
...the actual nodes in each area instance for them. Toolbars generally function the same way they always have. However, they can now be 'overflowable', that is, if there are too many widgets to fit in the toolbar's horizontal space, the excess widgets will be placed in a panel accessible from an anchor (chevron) in the toolbar. In order to register such a toolbar, set the 'overflowable' property to true, and provide the id of the anchor in the 'anchor' property. Widgets Widget is the term that CustomizableUI uses for each of the items in a customizable area. Note that these are also abstract cross-window objects; CustomizableUI will manage the actual DOM manipulation involved with adding/moving/removing widgets in all windows for you. There are three main types of widgets: 'legacy' XUL wid...
... removed from. onWidgetBeforeDOMChange(aNode, aNextNode, aContainer, aIsRemoval) Fired before a widget's DOM node is acted upon by CustomizableUI (to add, move or remove it). aNode is the DOM node changed, aNextNode the DOM node (if any) before which a widget will be inserted, aContainer the actual DOM container (could be an overflow panel in case of an overflowable toolbar), and aWasRemoval is true iff the action about to happen is the removal of the DOM node. onWidgetAfterDOMChange(aNode, aNextNode, aContainer, aWasRemoval) Like onWidgetBeforeDOMChange, but fired after the change to the DOM node of the widget. onWidgetReset(aNode, aContainer) Fired after a reset to default placements moves a widget's node to a different location. aNode is the widget's node, aContainer is the area it wa...
...And 12 more matches
WebIDL bindings
gument list. This comes after all IDL arguments, but before the ErrorResult&, if any, for the method. Note that this allows callees to declare their methods as taking an nsAString& or nsString& if desired. Strings in sequences, dictionaries, owning unions, and variadic arguments become nsString. Nullable strings are represented by the same types as non-nullable ones, but the string will return true for DOMStringIsNull(). Returning null as a string value can be done using SetDOMStringToNull on the out param if it's an nsAString or calling SetNull() on a DOMString. For example, this WebIDL: interface Test { DOMString myAttr; [Throws] DOMString myMethod(sequence<DOMString> arg1, DOMString? arg2, optional DOMString arg3); }; will correspond to these C++ function declarations: void Ge...
... Arguments become const nsACString&. Return values become an nsACString& out param appended to the argument list. This comes after all IDL arguments, but before the ErrorResult&, if any, for the method. In sequences, dictionaries owning unions, and variadic arguments it becomes nsCString. Nullable UTF8Strings are represented by the same types as non-nullable ones, but the string will return true for IsVoid(). Returning null as a string value can be done using SetIsVoid() on the out param. ByteString ByteString is reflected in three different ways, depending on use: ByteString arguments become const nsACString&. ByteString return values become an nsCString& out param appended to the argument list. This comes after all IDL arguments, but before the ErrorResult&, if any, for the metho...
...e const nsACString&. ByteString return values become an nsCString& out param appended to the argument list. This comes after all IDL arguments, but before the ErrorResult&, if any, for the method. ByteString in sequences, dictionaries, owning unions, and variadic arguments becomes nsCString. Nullable ByteString are represented by the same types as non-nullable ones, but the string will return true for IsVoid(). Returning null as a string value can be done using SetIsVoid() on the out param. object object is represented in three different ways, depending on use: object arguments become JS::Handle<JSObject*>. They will be in the compartment of the passed-in JSContext. object return values become a JS::MutableHandle<JSObject*> out param appended to the argument list. This comes after a...
...And 12 more matches
Border-image generator - CSS: Cascading Style Sheets
dding: 0 0.3em; border: 3px solid #3490D2; border-color: #208B20; background: #666; background-color: #EEF1F5; color: #000; position: absolute; top: 2em; left: 0; z-index: 100; overflow: hidden; transition: all 0.3s; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .ui-dropdown-list:hover { overflow: auto; } .ui-dropdown-list[data-hidden='true'] { height: 0 !important; opacity: 0; visibility: hidden; } .ui-dropdown[data-position='left'] .ui-dropdown-list { left: -100%; top: 0; } .ui-dropdown[data-position='right'] .ui-dropdown-list { left: 100%; top: 0; } .ui-dropdown-list > div { width: 100%; height: 1.6em; margin: 0.3em 0; padding: 0.3em; line-height: 1em; -moz-box-sizing: border-box; -webkit-box-sizing: border-box;...
...kit-box-sizing: border-box; box-sizing: border-box; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; } body[data-move='X'] { cursor: w-resize !important; } body[data-move='Y'] { cursor: s-resize !important; } #container { width: 100%; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } [data-draggable='true']:hover { cursor: move; } [data-draggable='true']:hover > * { cursor: default; } /******************************************************************************/ /******************************************************************************/ /* * Border Image Picker */ #gallery { box-shadow: 0 0 3px 0 #BABABA; } #image-gallery { width: 600px; height: 100px; margin: 0 auto; transi...
...*********************************************/ /* * Border Image Picker */ #gallery { box-shadow: 0 0 3px 0 #BABABA; } #image-gallery { width: 600px; height: 100px; margin: 0 auto; transition: margin 0.4s; } #image-gallery .image { height: 80px; float: left; margin: 10px; opacity: 0.5; background-color: #FFF; box-shadow: 0px 0px 3px 1px #BABABA; } #image-gallery .image[selected="true"] { box-shadow: 0px 0px 3px 1px #3BBA52; opacity: 1; } #image-gallery .image:hover { cursor: pointer; box-shadow: 0px 0px 3px 1px #30ACE5; opacity: 1; } #image-gallery[data-collapsed='true'] { margin-top: -100px; } /* Load Menu */ #load-actions { margin: 10px 0; } #toggle-gallery { width: 30px; height: 25px; margin: 10px; color: #FFF; background-image: url('https://mdn.mozillade...
...And 12 more matches
lang/type - Archive of obsolete content
Functions for working with type detection. 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. Returns boolean : Boolean indicating if value is undefined. isNull(value) Returns true if value is null, false otherwise. let { isNull } = require('sdk/lang/type'); isNull(null); // true isNull(false); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is null. isString(value) Returns true if value is a String, false otherwise. Uses typeof operator to check type, and will only properly detect string primitives: for example, a string ...
...s value : mixed The variable to check. Returns boolean : Boolean indicating if value is null. isString(value) Returns true if value is a String, false otherwise. Uses typeof operator to check type, and will only properly detect string primitives: for example, a string created with new String() will always return false. let { isString } = require('sdk/lang/type'); isString('my string'); // true isString(100); // false isString('100'); // true Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is a String. isNumber(value) Returns true if value is a Number, false otherwise. Uses typeof operator to check type, and will only properly detect number primitives: for example, a number created with new Number() will always return false. let { is...
...rs value : mixed The variable to check. Returns boolean : Boolean indicating if value is a String. isNumber(value) Returns true if value is a Number, false otherwise. Uses typeof operator to check type, and will only properly detect number primitives: for example, a number created with new Number() will always return false. let { isNumber } = require('sdk/lang/type'); isNumber(3.1415); // true isNumber(100); // true isNumber('100'); // false Parameters value : mixed The variable to check. Returns boolean : Boolean indicating if value is a Number. isRegExp(value) Returns true if value is a RegExp, false otherwise. ...
...And 11 more matches
source-editor.jsm
You can then use this value to detect when the contents of the text are different from your most recent save. In addition, when this value changes, the "DirtyChanged" event is sent. editorElement Element The element containing the editor. When using the default Orion editor, this is a XUL <xul:iframe> element. Read only. lastFind Object ...
... most recent find operation; this is the index into the text at which str was found, or -1 if the string wasn't found. lastFound Number The index of the previous location at which str was found, for multiple find operations (such as find() followed by findNext()). This can be -1 if the string was never found. ignoreCase Boolean true if the search was case sensitive; otherwise false. readOnly Boolean Set this value to true to make the editor read only, thereby preventing the user from making changes. Set it to false to allow editing. Constants Preference name constants These constants define the names of preferences used by the source editor. Constant Value Descrip...
...The default Mozilla syntax highlighter theme. Configuration defaults constants These constants represent the default values for each of the available configuration options. See The editor configuration object for details on configuring the editor. ...
...And 11 more matches
Enc Dec MAC Output Public Key as CSR
int)); if (!data->data) { PR_fprintf(PR_STDERR, "Error while allocating memory\n"); rv = SECFailure; goto cleanup; } rv = PK11_PubWrapSymKey(CKM_RSA_PKCS, pubKey, key, data); if (rv != SECSuccess) { rv = SECFailure; } else { *wrappedKey = data; return SECSuccess; } cleanup: if (data) { SECITEM_FreeItem(data, PR_TRUE); } return rv; } /* * Generate a Symmetric Key */ PK11SymKey * GenerateSYMKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE mechanism, int keySize, SECItem *keyID, secuPWData *pwdata) { SECStatus rv; PK11SymKey *key; /* Generate the symmetric key */ key = PK11_TokenKeyGen(slot, mechanism, NULL, keySize, keyID, PR_FALSE, pwdata); if (!ke...
...(type, &ivItem); if (secParam == NULL) { PR_fprintf(PR_STDERR, "Crypt Failed : secParam NULL\n"); return NULL; } ctx = PK11_CreateContextBySymKey(type, operation, key, secParam); if (ctx == NULL) { PR_fprintf(PR_STDERR, "Crypt Failed : can't create a context\n"); goto cleanup; } cleanup: if (secParam) { SECITEM_FreeItem(secParam, PR_TRUE); } return ctx; } /* * Common encryption and decryption code */ SECStatus Crypt(PK11Context *ctx, unsigned char *out, unsigned int *outLen, unsigned int maxOut, unsigned char *in, unsigned int inLen) { SECStatus rv; rv = PK11_CipherOp(ctx, out, outLen, maxOut, in, inLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Crypt Failed : PK11_CipherOp return...
... algtag = SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION; params = &rsaparams; break; default: goto cleanup; } fprintf(stderr, "\n\n"); fprintf(stderr, "Generating key. ...
...And 11 more matches
nsIPromptService
alog with OK and cancel buttons. boolean confirm( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText ); Parameters aParent The parent window for the dialog. If set to null the parent window will be nsIWindowWatcher.activeWindow. aDialogTitle Text to appear in the title of the dialog. aText Text to appear in the body of the dialog. Return value true for OK, false for Cancel See also the confirm_example. confirmCheck() Shows a dialog with OK and Cancel buttons and a labeled checkbox. See also the confirm_example. boolean confirmCheck( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText, in wstring aCheckMsg, inout boolean aCheckState ); Parameters aParent The parent window for the dialog. If set to null the...
...he body of the dialog. aCheckMsg Text to appear with the checkbox. aCheckState Contains the initial checked state of the checkbox when this method is called and the final checked state after this method returns. If you call this method from JavaScript you need to wrap this argument in an object with its 'value' property set to a boolean (or use an empty object). Return value true for OK, false for Cancel confirmEx() Puts up a dialog with up to 3 buttons and an optional, labeled checkbox. The Buttons are numbered 0 - 2. The implementation can decide what order the buttons appear in, and it may not be simply right-to-left (2, 1, 0) or left-to-right (0, 1, 2). See bug 624043 for more on this. Button 0 is the default button unless one of the Button Default Flags is specified...
... Text to appear with the checkbox. If null, checkbox will not be shown. aCheckState Contains the initial checked state of the checkbox when this method is called and the final checked state after this method returns. If you call this method from JavaScript you need to wrap this argument in an object with its 'value' property set to a boolean (or use an empty object). Return value true for OK, false for Cancel promptUsernameAndPassword() Shows a dialog with an edit field, a password field, and an optional, labeled checkbox. See also the promptUsernameAndPassword_example. boolean promptUsernameAndPassword( in nsIDOMWindow aParent, in wstring aDialogTitle, in wstring aText, inout wstring aUsername, inout wstring aPassword, in wstring aCheckMsg, inout boolean aCheck...
...And 11 more matches
Object.defineProperty() - JavaScript
t has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both. Both data and accessor descriptors are objects. They share the following optional keys (note: the default value is in the case of defining properties using Object.defineProperty()): configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false. A data descriptor also has the following optional keys: value The value associated with the proper...
... Defaults to false. An accessor descriptor also has the following optional keys: get A function which serves as a getter for the property, or undefined if there is no getter. ...
...When the property specified doesn't exist in the object, Object.defineProperty() creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are inputted. var o = {}; // Creates a new object // Example of an object property added // with defineProperty with a data property descriptor Object.defineProperty(o, 'a', { value: 37, writable: true, enumerable: true, configurable: true }); // 'a' property exists in the o object and its value is 37 // Example of an object property added // with defineProperty with an accessor property descriptor var bValue = 38; Object.defineProperty(o, 'b', { // Using shorthand method names (ES2015 feature). // This is equivalent to: // get: function() { return bValue; }, // set: function(newVa...
...And 11 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
0 The user's address book is searched. ldap New in Thunderbird 25 Requires SeaMonkey 2.22 The user's LDAP directory is searched. autocompletesearchparam New in Thunderbird 2 Requires SeaMonkey 1.1 Type: string A string which is passed to the search component. completedefaultindex New in Thunderbird 3 Requires SeaMonkey 2.0 Type: boolean If true, the best match value will be filled into the textbox as the user types. If set to false or omitted, the value must be selected from the list. completeselectedindex Type: boolean If true, the text in the text field will be autocompleted as the user selects from the popup list. crop Type: boolean This attribute is not used and is only provided for compatibility with the menulis...
...You might use a script to change this attribute. If false, the default, autocomplete is enabled. disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. ...
... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...And 10 more matches
Tree View Details - Archive of obsolete content
nd so on. The tree will query the view for each row by calling its getLevel method to find out the level of that row. The view will need to return 0 for the outermost rows and higher values for inner rows. The tree will use this information to determine the hierarchical structure of the rows. In addition to the getLevel method, there is a hasNextSibling function which, given a row, should return true if there is another row afterwards at the same level. This function is used, specifically, to draw the nesting lines along the side of the tree. The getParentIndex method is expected to return the parent row of a given row, that is, the row before it with a lower nesting value. All of these methods must be implemented by the view for children to be handled properly. Containers There are also t...
...entIndex method is expected to return the parent row of a given row, that is, the row before it with a lower nesting value. All of these methods must be implemented by the view for children to be handled properly. Containers There are also three functions, isContainer, isContainerEmpty and isContainerOpen that are used to handle a parent item in the tree. The isContainer method should return true if a row is a container and might contain children. The isContainerEmpty method should return true if a row is an empty container, for instance, a directory with no files in it. The isContainerOpen method is used to determine which items are opened and closed. The view is required to keep track of this. The tree will call this method to determine which containers are open and which are closed. ...
...a container. When the user clicks the twisty to open a row, the tree will call the view's toggleOpenState method. The view should then perform any necessary operations to retrieve the child rows and then update the tree with the new rows. Note: As of this writing (Gecko 2.0), custom nsITreeView implementations must be prepared to handle a call to toggleOpenState for any row index which returns true for a call to isContainer, regardless of whether the container is empty. Review of the Methods Here is a review of the methods needed to implement hierarchical views: getLevel(row) hasNextSibling(row, afterIndex) getParentIndex(row) isContainer(row) isContainerEmpty(row) isContainerOpen(row) toggleOpenState(row) The afterIndex argument to hasNextSibling function is used as optimization to o...
...And 10 more matches
Debugger.Object - Firefox Developer Tools
Debugger.Object instance inherits the following accessor properties from its prototype: proto The referent's prototype (as a new Debugger.Object instance), or null if it has no prototype. This accessor may throw if the referent is a scripted proxy or some other sort of exotic object (an opaque wrapper, for example). class A string naming the ECMAScript [[Class]] of the referent. callable true if the referent is a callable object (such as a function or a function proxy); false otherwise. name The name of the referent, if it is a named function. If the referent is an anonymous function, or not a function at all, this is undefined. This accessor returns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instanti...
...tring which is the name of the template; undefined otherwise. errorLineNumber If the referent is an Error object, this is the line number at which the referent was created; undefined otherwise. errorColumnNumber If the referent is an Error object, this is the column number at which the referent was created; undefined otherwise. isBoundFunction If the referent is a debuggee function, returns true if the referent is a bound function; false otherwise. If the referent is not a debuggee function, or not a function at all, returns undefined instead. isArrowFunction If the referent is a debuggee function, returns true if the referent is an arrow function; false otherwise. If the referent is not a debuggee function, or not a function at all, returns undefined instead. isGeneratorFunction If ...
...therwise. If the referent is not a debuggee function, or not a function at all, returns undefined instead. isArrowFunction If the referent is a debuggee function, returns true if the referent is an arrow function; false otherwise. If the referent is not a debuggee function, or not a function at all, returns undefined instead. isGeneratorFunction If the referent is a debuggee function, returns true if the referent was created with a function* expression or statement, or false if it is some other sort of function. If the referent is not a debuggee function, or not a function at all, this is undefined. ...
...And 10 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
he following example simulates typewriter by first clearing and then slowly typing content into the NodeList that matches a specified group of selectors. ...
...<meta charset="UTF-8" /> <title>JavaScript Typewriter - MDN Example</title> <script> function Typewriter (sSelector, nRate) { function clean () { clearInterval(nIntervId); bTyping = false; bStart = true; oCurrent = null; aSheets.length = nIdx = 0; } function scroll (oSheet, nPos, bEraseAndStop) { if (!oSheet.hasOwnProperty('parts') || aMap.length < nPos) { return true; } var oRel, bExit = false; if (aMap.length === nPos) { aMap.push(0); } while (aMap[nPos] < oSheet.parts.length) { oRel = oSheet.parts[aMap[nPos]]; scroll(oRel, nPos + 1, bEraseAndStop) ? aMap[nPos]++ : bExit = true; if (bEraseAndStop && (oRel.ref.nodeType - 1 | 1) === 3 && oRel.ref.nodeValue) { bExit = true; oCurrent = oRel.ref; sPart = ...
... scroll(oRel, nPos + 1, bEraseAndStop) ? ...
...And 10 more matches
Iteration protocols - JavaScript
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. (This is equivalent to not specifying the done property altogether.) Has the value true if the iterator has completed its sequence. In this case, value optionally specifies the return value of the iterator. value Any JavaScript value returned by the iterator. Can be omitted when done is true. The next() method must always return an object with appropriate properties including done and value. If a non-object value gets returned (such as false or undefined), a Typ...
...String[Symbol.iterator]); // "function" String's default iterator returns the string's code points one by one: let iterator = someString[Symbol.iterator](); console.log(iterator + ''); // "[object String Iterator]" console.log(iterator.next()); // { value: "h", done: false } console.log(iterator.next()); // { value: "i", done: false } console.log(iterator.next()); // { value: undefined, done: true } Some built-in constructs--such as the spread syntax--use the same iteration protocol under the hood: console.log([...someString]); // ["h", "i"] You can redefine the iteration behavior by supplying our own @@iterator: // need to construct a String object explicitly to avoid auto-boxing let someString = new String('hi'); someString[Symbol.iterator] = function () { return { // this is ...
...our own @@iterator: // need to construct a String object explicitly to avoid auto-boxing let someString = new String('hi'); someString[Symbol.iterator] = function () { return { // this is the iterator object, returning a single element (the string "bye") next: function () { return this._first ? ...
...And 10 more matches
tree - Archive of obsolete content
Archive › Mozilla › XUL › tree
eeitem> <treerow> <treecell label="mel@whereever.com"/> <treecell label="Let's do lunch"/> </treerow> </treeitem> </treechildren> </tree> A tree with several columns and nested items <tree id="myTree" flex="1" hidecolumnpicker="false" seltype="single" class="tree" rows="5"> <treecols id="myTree2-treeCols"> <treecol id="myTree2-treeCol0" primary="true" flex="2" label="Column A" persist="width" ordinal="1"/> <splitter class="tree-splitter" ordinal="2"/> <treecol id="myTree2-treeCol1" flex="1" label="Column B" persist="width" ordinal="3"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="1"/> <treecell label="a"/> </treerow> </treeitem> <!-- Make sure t...
..."Column A" persist="width" ordinal="1"/> <splitter class="tree-splitter" ordinal="2"/> <treecol id="myTree2-treeCol1" flex="1" label="Column B" persist="width" ordinal="3"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="1"/> <treecell label="a"/> </treerow> </treeitem> <!-- Make sure to set container="true" --> <treeitem container="true" open="true"> <treerow> <treecell label="2"/> <treecell label="b"/> </treerow> <treechildren> <treeitem> <treerow> <treecell label="2a"/> <treecell label="ba"/> </treerow> </treeitem> </treechildren> </treeitem> </treechildren> </tree> Attributes dis...
...s disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...And 9 more matches
Client-side form validation - Learn web development
whether the data needs to be a number, an email address, or some other specific preset type. pattern: Specifies a regular expression that defines a pattern the entered data needs to follow. If the data entered in a form field follows all of the rules specified by the above attributes, it is considered valid. If not, it is considered invalid. ...
... If the user tries to send the data, the browser will block the form and display an error message. ...
... is false) or the element's value satisfies its constraints (is valid), this will return an empty string. validity: Returns a ValidityState object that contains several properties describing the validity state of the element. ...
...And 9 more matches
ByteLengthQueuingStrategy - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 46Safari ? WebView Android Full support 59Chrome Android ...
... 59Edge Full support 16Firefox Full support 57Disabled Full support 57Disabled Disabled From version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true). To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 46Safari ? WebView Android Full support 59Chrome Android Full support 59Firefox Android ...
...To change preferences in Firefox, visit about:config.Opera Android Full support 43Safari iOS ? Samsung Internet Android Full support 7.0ByteLengthQueuingStrategy() constructor ExperimentalChrome ...
...And 9 more matches
CountQueuingStrategy - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 46Safari ? WebView Android Full support 59Chrome Android ...
... 59Edge Full support 16Firefox Full support 57Disabled Full support 57Disabled Disabled From version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true). To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 46Safari ? WebView Android Full support 59Chrome Android Full support 59Firefox Android ...
...To change preferences in Firefox, visit about:config.Opera Android Full support 43Safari iOS ? Samsung Internet Android Full support 7.0CountQueuingStrategy() constructor ExperimentalChrome ...
...And 9 more matches
ARIA Test Cases - Accessibility
under construction. Only the bold/italic buttons should be toggle buttons, and they aren't currently toggleable. Expected AT Behavior: Same as basic button above, plus if the state is pressed, AT should indicate that when focus lands on the button and when toggling. 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. Fail in V PC mode. No indication is given that a button is pressed, or that it is pressed after activating it. - - - VoiceOver (Leopard) n/a n/a -...
...d 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). When pressing Space, new state should be announced automatically. ...
... pass ZoomText Pass - Fail Fail Orca Pass n/a - - Tristate Checkbox Testcases: Both remove or unset for unchecked case Expected AT Behavior: Screen reader should announce accessible name, role and state. When toggling, new state should be announced (not checked, partially checked, checked). 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. The state of tristate checkboxes is not announced when initially focusing. It is announced when toggling. Fail - changes not spoken Fail Fail VoiceOver (Leopard) n/a n/a - fail Window-Eyes Pass ...
...And 9 more matches
Logical OR (||) - JavaScript
The logical OR (||) operator (logical disjunction) for a set of operands is true if and only if one or more of its operands is true. It is typically used with Boolean (logical) values. When it is, it returns a Boolean value. However, the || operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...ified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax expr1 || expr2 Description If expr1 can be converted to true, returns expr1; else, returns expr2. If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy. Examples of expressions that can be converted to false are: null; NaN; 0; empty string ("" or '' or ``); undefined. Even though the || operator can be used with operands that are not Boolean values, it can still be ...
...it means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. ...
...And 9 more matches
this - JavaScript
f an execution context (global, function or eval) that, in non-strict mode, is always a reference to an object and in strict mode can be any value. Description Global context In the global execution context (outside of any function), this refers to the global object whether in strict mode or not. // In web browsers, the window object is also the global object: console.log(this === window); // true a = 37; console.log(window.a); // 37 this.b = "MDN"; console.log(window.b) // "MDN" console.log(b) // "MDN" Note: You can always easily get the global object using the global globalThis property, regardless of the current context in which your code is running. Function context Inside a function, the value of this depends on how the function is called. Since the following code is...
...less of the current context in which your code is running. Function context Inside a function, the value of this depends on how the function is called. Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser. ...
...code is running. Function context Inside a function, the value of this depends on how the function is called. Since the following code is not in strict mode, and because the value of this is not set by the call, this will default to the global object, which is window in a browser. function f1() { return this; } // In a browser: f1() === window; // true // In Node: f1() === globalThis; // true In strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined, as shown in the following example: function f2() { 'use strict'; // see strict mode return this; } f2() === undefined; // true In the second example, this should be undefined, because f2 was called directly and not as a method or property of an object (e.g. window.f2()). ...
...And 9 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
l overlay, write code which listens for a custom DOM event. Here we call the event MyExtensionEvent. 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. The data from the web page (unprivileged code) will be the values of attribute1 and attribute2. To trigger the alert() in the listener and pass the data from the web page, write code such as this in the web page: var element = document.createElement("MyExtensionDataElement"); element.
...Values are set for two arbitrary attributes on the element. These can also be named anything you like, but we've chosen attribute1 and attribute2. Finally, the code creates and dispatches a custom event named MyExtensionEvent -- similar to the stand...
... document.addEventListener("message", function(e...
...And 8 more matches
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
utton Also, as shown in Listing 7, you can embed CSS inline into elements via the style attribute, which allows you to set sizes using units other than pixels. <button label="Button" style="min-width: 10em;"/> Listing 7: Setting the size of a button using CSS markup hidden and collapsed The hidden and collapsed attributes act as switches to turn off the display of elements. Setting hidden="true" disables display of that element. This has the same effect as setting display: none in CSS. You would use this to set a hidden or absent state, for example items that aren't displayed in contextual menus. Setting collapsed="true" sets an element's height and width to 0, but the element is treated as being present. This is equivalent to setting visibility: collapse in CSS. Use this to "roll up" ...
...nt's height and width to 0, but the element is treated as being present. This is equivalent to setting visibility: collapse in CSS. Use this to "roll up" sidebars that aren't currently in use. disabled While not appropriate for all elements, you can use the disabled attribute to temporarily disable input to an element that is normally operable by the user. Typically, elements with the disabled="true" attribute will appear as either transparent or pale gray. Note: With attributes like hidden, collapsed, and disabled, which take Boolean values, setting disabled="false" in XUL can have unintended consequences. This is because there may be cases where a script or CSS rule will be written in such a way that they treat the value as true unconditionally if any value has been set. So when changing ...
...item elements can operate like checkboxes and radio buttons by setting their type attributes. checkbox Adding type="checkbox" to a menuitem element will check that when it is selected, and uncheck it if it is selected again. For an example of menu items with checkboxes, see the View menu in Firefox, with items to show or hide the toolbar and sidebar. ...
...And 8 more matches
Mozilla DOM Hacking Guide
ument. So XPConnect will then try to find a method named GetElementById() on the nsIDOMDocument interface. And indeed it will find it, and thus call it. This is the schema used most of the time when using W3C DOM objects and methods. It is however different for some DOM Level 0 objects and methods. I'll take two very different examples. The first one is the window.location object (the same holds true for document.location, actually). We can change the URL of the current window by assigning window.location. In IDL, location is declared to be a readonly attribute. This is because, if we had a SetLocation() method, it would take an nsIDOMLocation parameter, and not a URL string. Instead, in the helper class for the window object (nsWindowSH, see the next Section), we define the GetProperty() mem...
...sult aResult);: help me! static nsresult InitDOMJSClass(JSContext *cx, JSObject *obj);: help me! static JSClass sDOMJSClass;: help me! Protected section: const nsDOMClassInfoData* mData;: help me! static nsresult Init(): Called only once, it is used to initialize the remaining members of the nsDOMClassInfoData structure, as mentioned above. Once called, Init() sets sIsInitialized to true, to remember that the initialization has been performed. The implementation is described in Section 1.5. static nsresult RegisterClassName(PRInt32 aDOMClassInfoID): help me! static nsresult RegisterClassProtos(PRInt32 aDOMClassInfoID): help me! static nsresult RegisterExternalClasses();: help me! nsresult ResolveConstructor(JSContext *cx, JSObject *obj, JSObject **objp);: help me! static PRI...
...Else, *aIsNumber is false and -1 is returned. static inline PRBool IsReadonlyReplaceable(jsval id) { ... }: help me! static inline PRBool IsWritableReplaceable(jsval id) { ... }: help me! nsresult doCheckPropertyAccess(...): help me! (bug 90757) static JSClass sDOMConstructorProtoClass: XPConnect fu to expose the DOM objects constructors to JavaScript. static JS...
...And 8 more matches
Encrypt Decrypt MAC Keys As Session Objects
f(PR_STDERR, "Could not read SymKey CKA_ID attribute\n"); return rv; } return rv; } /* * Generate a Symmetric Key */ PK11SymKey * GenerateSYMKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE mechanism, int keySize, SECItem *keyID, secuPWData *pwdata) { SECStatus rv; PK11SymKey *key; if (PK11_NeedLogin(slot)) { rv = PK11_Authenticate(slot, PR_TRUE, pwdata); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Could not authenticate to token %s.\n", PK11_GetTokenName(slot)); return NULL; } } /* Generate the symmetric key */ key = PK11_TokenKeyGen(slot, mechanism, NULL, keySize, keyID, PR_TRUE, pwdata); if (!key) { PR_fprintf(PR_STDE...
...&ivItem); if (secParam == NULL) { PR_fprintf(PR_STDERR, "Crypt Failed : secParam NULL\n"); return NULL; } ctx = PK11_CreateContextBySymKey(CKM_AES_CBC, operation, key, secParam); if (ctx == NULL) { PR_fprintf(PR_STDERR, "Crypt Failed : can't create a context\n"); goto cleanup; } cleanup: if (secParam) { SECITEM_FreeItem(secParam, PR_TRUE); } return ctx; } /* * Common encryption and decryption code */ SECStatus Crypt(PK11Context *ctx, unsigned char *out, unsigned int *outLen, unsigned int maxOut, unsigned char *in, unsigned int inLen) { SECStatus rv; rv = PK11_CipherOp(ctx, out, outLen, maxOut, in, inLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Crypt Failed : PK11_CipherOp return...
...0] = paddingLength; padItem.type = siBuffer; padItem.data = (unsigned char *)pad; padItem.len = sizeof(pad[0]); WriteToHeaderFile(padItem.data, padItem.len, PAD, headerFile); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Write PAD Failure\n"); goto cleanup; } rv = SECSuccess; cleanup: if (ctxmac != NULL) { PK11_DestroyContext(ctxmac, PR_TRUE); } if (ctxenc != NULL) { PK11_DestroyContext(ctxenc, PR_TRUE); } return rv; } /* * Find the Key for the given mechanism */ PK11SymKey* FindKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE mechanism, SECItem *keyBuf, secuPWData *pwdata) { SECStatus rv; PK11SymKey *key; if (PK11_NeedLogin(slot)) { rv = PK11_Authenticate(slot, PR_TRU...
...And 8 more matches
Encrypt and decrypt MAC using token
f(PR_STDERR, "Could not read SymKey CKA_ID attribute\n"); return rv; } return rv; } /* * Generate a Symmetric Key */ PK11SymKey * GenerateSYMKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE mechanism, int keySize, SECItem *keyID, secuPWData *pwdata) { SECStatus rv; PK11SymKey *key; if (PK11_NeedLogin(slot)) { rv = PK11_Authenticate(slot, PR_TRUE, pwdata); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Could not authenticate to token %s.\n", PK11_GetTokenName(slot)); return NULL; } } /* Generate the symmetric key */ key = PK11_TokenKeyGen(slot, mechanism, NULL, keySize, keyID, PR_TRUE, pwdata); if (!key) { PR_fprintf(PR_STDE...
...&ivItem); if (secParam == NULL) { PR_fprintf(PR_STDERR, "Crypt Failed : secParam NULL\n"); return NULL; } ctx = PK11_CreateContextBySymKey(CKM_AES_CBC, operation, key, secParam); if (ctx == NULL) { PR_fprintf(PR_STDERR, "Crypt Failed : can't create a context\n"); goto cleanup; } cleanup: if (secParam) { SECITEM_FreeItem(secParam, PR_TRUE); } return ctx; } /* * Common encryption and decryption code */ SECStatus Crypt(PK11Context *ctx, unsigned char *out, unsigned int *outLen, unsigned int maxOut, unsigned char *in, unsigned int inLen) { SECStatus rv; rv = PK11_CipherOp(ctx, out, outLen, maxOut, in, inLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Crypt Failed : PK11_CipherOp return...
...0] = paddingLength; padItem.type = siBuffer; padItem.data = (unsigned char *)pad; padItem.len = sizeof(pad[0]); WriteToHeaderFile(padItem.data, padItem.len, PAD, headerFile); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Write PAD Failure\n"); goto cleanup; } rv = SECSuccess; cleanup: if (ctxmac != NULL) { PK11_DestroyContext(ctxmac, PR_TRUE); } if (ctxenc != NULL) { PK11_DestroyContext(ctxenc, PR_TRUE); } return rv; } /* * Find the Key for the given mechanism */ PK11SymKey* FindKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE mechanism, SECItem *keyBuf, secuPWData *pwdata) { SECStatus rv; PK11SymKey *key; if (PK11_NeedLogin(slot)) { rv = PK11_Authenticate(slot, PR_TRU...
...And 8 more matches
NSS Sample Code Sample_3_Basic Encryption and MACing
f(PR_STDERR, "Could not read SymKey CKA_ID attribute\n"); return rv; } return rv; } /* * Generate a Symmetric Key */ PK11SymKey * GenerateSYMKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE mechanism, int keySize, SECItem *keyID, secuPWData *pwdata) { SECStatus rv; PK11SymKey *key; if (PK11_NeedLogin(slot)) { rv = PK11_Authenticate(slot, PR_TRUE, pwdata); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Could not authenticate to token %s.\n", PK11_GetTokenName(slot)); return NULL; } } /* Generate the symmetric key */ key = PK11_TokenKeyGen(slot, mechanism, NULL, keySize, keyID, PR_TRUE, pwdata); if (!key) { PR_fprintf(PR_STDE...
...&ivItem); if (secParam == NULL) { PR_fprintf(PR_STDERR, "Crypt Failed : secParam NULL\n"); return NULL; } ctx = PK11_CreateContextBySymKey(CKM_AES_CBC, operation, key, secParam); if (ctx == NULL) { PR_fprintf(PR_STDERR, "Crypt Failed : can't create a context\n"); goto cleanup; } cleanup: if (secParam) { SECITEM_FreeItem(secParam, PR_TRUE); } return ctx; } /* * Common encryption and decryption code */ SECStatus Crypt(PK11Context *ctx, unsigned char *out, unsigned int *outLen, unsigned int maxOut, unsigned char *in, unsigned int inLen) { SECStatus rv; rv = PK11_CipherOp(ctx, out, outLen, maxOut, in, inLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Crypt Failed : PK11_CipherOp return...
...0] = paddingLength; padItem.type = siBuffer; padItem.data = (unsigned char *)pad; padItem.len = sizeof(pad[0]); WriteToHeaderFile(padItem.data, padItem.len, PAD, headerFile); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Write PAD Failure\n"); goto cleanup; } rv = SECSuccess; cleanup: if (ctxmac != NULL) { PK11_DestroyContext(ctxmac, PR_TRUE); } if (ctxenc != NULL) { PK11_DestroyContext(ctxenc, PR_TRUE); } return rv; } /* * Find the Key for the given mechanism */ PK11SymKey* FindKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE mechanism, SECItem *keyBuf, secuPWData *pwdata) { SECStatus rv; PK11SymKey *key; if (PK11_NeedLogin(slot)) { rv = PK11_Authenticate(slot, PR_TRU...
...And 8 more matches
nss tech note5
The Rijndael algorithm permits 3 blocksizes (16, 24, 32 bytes), but the AES standard requires the blocksize to be 16 b...
...p2_outlen, sizeof outbuf - tmp1_outlen); result_len = tmp1_outlen + tmp2_outlen; <big>Destroy the Context PK11_DestroyContext(EncContext, PR_TRUE);</big> <big>Repeat Step 6 any number of times. When all done with encrypt/decrypt ops, clean up</big> <big>PK11_FreeSymKey(SymKey); SECITEM_FreeItem(SecParam, PR_TRUE); PK11_FreeSlot(slot);</big> Note: AES encryption, a fixed blocksize of 16 bytes is used. The Rijndael algorithm permits 3 blocksizes (16, 24, 32 bytes), but the AES standard requires the blocksize to be 16 bytes. The keysize can vary and these keysizes are permitted: 16, 24, 32 bytes. You can also look at a sample program illustrating encryption Hash / Digest Include headers ...
...You can find a list of digest mechanisms in security/nss/lib/softoken/pkcs...
...And 8 more matches
Starting WebLock
ponent will be created and then released after the notification, which may cause the component to be deleted. ...
...ion, which may cause the component to be deleted. ...
... PR_TRUE, // replace existing &previous); if (previous) nsMemory::Free(previous); // free the memory the replaced value might have used The unregistration, which should occur in the unregistration callback, looks like this: rv = catman->DeleteCategoryEntry("xpcom-startup", "WebLock", PR_TRUE); // persist A complete code listing for registering WebLock as a startup observer follows: #define MOZILLA_STRICT_API #include "nsIGenericFactory.h" #include "nsCOMPtr.h" #include "nsXPCOM.h" #include "nsIServiceManager.h" #include "nsICategoryManager.h" #include "nsMemory.h" #include "nsIObserver.h" #include "nsEmbedString.h" #define WebLock_CID \ { 0x777f7150, 0x4a2b, 0x4301, \ { 0xa...
...And 8 more matches
nsITreeView
see isContainer(). boolean canDrop( in long index, in long orientation, in nsIDOMDataTransfer dataTransfer ); Parameters index The index of the row. orientation The position around the given row. Defined in constants. dataTransfer This parameter, added in Gecko 1.9.2, provides the data being dragged, so that it can be examined to determine if a drop is possible. Return value true if a drop is allowed at the current location; otherwise false. canDropBeforeAfter() Obsolete since Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method used by the drag feedback code to determine if a drag is allowable at the current location. To get the behavior where drops are only allowed on items, such as the mailNews folder pane, always return false fr...
...rbird 1.5 / SeaMonkey 1.0) Method used by the drag feedback code to determine if a drag is allowable at the current location. To get the behavior where drops are only allowed on items, such as the mailNews folder pane, always return false from canDropBeforeAfter(). boolean canDropBeforeAfter( in long index, in boolean before ); Parameters index The index of the item. before true to test drop before. false to test drop after. Return value true if a drop event can occur. Otherwise false. canDropOn() Obsolete since Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method used by the drag feedback code to determine if a drag is allowable at the current location. To get the behavior where drops are only allowed on items, such as the mail...
...8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Method used by the drag feedback code to determine if a drag is allowable at the current location. To get the behavior where drops are only allowed on items, such as the mailNews folder pane, always return false from canDropBeforeAfter(). boolean canDropOn( in long index ); Parameters index The index of the item. Return value true if a drop event can occur. Otherwise false. cycleCell() Called on the view when a cell in a non-selectable cycling column (for example, unread/flag/and so on.) is clicked. void cycleCell( in long row, in nsITreeColumn col ); Parameters row The row of the cell. col The column of the cell. cycleHeader() Called on the view when a header is clicked. void cycleHeader( in nsITreeCo...
...And 8 more matches
Fullscreen API - Web APIs
ed when the fullscreenchange event is sent to the element, indicating that the element has been placed into, or removed from, full-screen mode. Element.onfullscreenerror An event handler for the fullscreenerror event when sent to an element which has encountered an error while transitioning into or out of full-screen mode. 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. Note: Use the fullscreenElement property on the Document or ShadowRoot instead; if it's not null, then it's an Element currently being displayed in full-screen mode. Events The Fullscreen API defines two events which can be used to detect when full-screen mode is turned on and off, a...
...To change preferences in Firefox, visit about:config. No support 9 -- 65Alternate Name Alternate Name Uses the non-standard name: mozFullScreenIE No support NoOpera Full support 58 Full support 58 Full support ...
...To change preferences in Firefox, visit about:config. No support 9 -- 65Alternate Name Alternate Name Uses the non-standard name: mozFullScreenOpera Android Full support 50 Full support 50 Full support 14Alternate Name Alternate Name Us...
...And 8 more matches
ValidityState - Web APIs
The ValidityState interface represents the validity states that an element can be in, with respect to constraint validation. Together, they help explain why an element's value fails to validate, if it's not valid. Properties For each of these Boolean properties, a value of true indicates that the specified reason validation may have failed is true, with the exception of the valid property, which is true if the element's value obeys all constraints. ...
...t to constraint validation. Together, they help explain why an element's value fails to validate, if it's not valid. Properties For each of these Boolean properties, a value of true indicates that the specified reason validation may have failed is true, with the exception of the valid property, which is true if the element's value obeys all constraints. badInput Read only A Boolean that is true if the user has provided input that the browser is unable to convert. ...
...h is true if the element's value obeys all constraints. badInput Read only A Boolean that is true if the user has provided input that the browser is unable to convert. customError Read only A Boolean indicating whether the element's custom validity message has been set to a non-empty string by calling the element's setCustomValidity() method. patternMismatch Read only A Boolean that is true if the value does not match the specified pattern, and false if it does match. If true, the element matches the :invalid CSS pseudo-class. 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. If true, the element matches the :invalid and :out-of-range and CSS pseudo-classes. ...
...And 8 more matches
Animating textures in WebGL - Web APIs
a <canvas>) as the source for your textures. This example uses the glMatrix library to perform its matrix and vertex math. You'll need to include it if you create your own project based on this code. Our sample loads a copy from a CDN in our HTML's <head>. ...
...le loads a copy from a CDN in our HTML's <head>. ...
... CDN in our HTML's <head>. ...
...And 8 more matches
url - Archive of obsolete content
The URL, as a string, to be converted. Returns string : The converted native file path as a string. fromFilename(path) Converts the given native file path to a file: URL. Parameters path : string The native file path, as a string, to be converted. Returns string : The converted URL as a string. isValidURI(uri) Checks the validity of a URI. isValidURI("http://mozilla.org") would return true, whereas isValidURI("mozilla.org") would return false. Parameters uri : string The URI, as a string, to be tested. Returns boolean : A boolean indicating whether or not the URI is valid. getTLD(url) Returns the top-level domain for the given URL: that is, the highest-level domain under which individual domains may be registered. Uses getPublicSuffix() internally. var urls = require("sdk/u...
...ethods toString() Returns a string representation of the URL. Returns string : The URL as a string. toJSON() Returns a string representation of the URL. Returns string : The URL as a string. Properties scheme The name of the protocol in the URL, without the trailing ':'. Compare with protocol. ...
...ling ':'. Compare with protocol. For example: var url = require("sdk/url").URL("https://developer.mozilla.org/Add-ons?example=true&visible=yes#top"); console.log(url.scheme); // https userPass The username:password part of the URL, null if not present. host The host of the URL, null if not present. For example: var url = require("sdk/url").URL("https://developer.mozilla.org/Add-ons?example=true&visible=yes#top"); console.log(url.host); // developer.mozilla.org port The port number of the URL, null if none was specified. path The path component of the URL. Contains everything after the host of the URL. Compare with pathname. ...
...And 7 more matches
WAI-ARIA basics - Learn web development
tructural elements e.g. role="navigation" (<nav>) or role="complementary" (<aside>), but there are also others that describe different pages structures, such as role="banner", role="search", role="tabgroup", role="tab", etc., which are commonly found in UIs. Properties -- These define properties of elements, which can be used to give them extra meaning or semantics. As an example, aria-required="true" specifies that a form input needs to be filled in to be valid, whereas aria-labelledby="label" allows you to put an ID on an element, then reference it as being the label for anything else on the page, including multiple elements, which is not possible using <label for="input">. As an example, you could use aria-labelledby to specify that a key description contained in a <div> is the label for m...
...ion contained in a <div> is the label for multiple table cells, or you could use it as an alternative to image alt text -- specify existing information on the page as an image's alt text, rather than having to repeat it inside the alt attribute. You can see an example of this at Text alternatives. States -- Special properties that define the current conditions of elements, such as aria-disabled="true", which specifies to a screenreader that a form input is currently disabled. States differ from properties in that properties don't change throughout the lifecycle of an app, whereas states can change, generally programmatically via JavaScript. An important point about WAI-ARIA attributes is that they don't affect anything about the web page, except for the information exposed by the browser's ...
... local web server like Python's SimpleHTTPServer. There is an additional consideration here -- only the bit of text that updates is read out. It might be nice if we always read out the heading too, so the user can remember what is being read out. To do this, we can add the aria-atomic property to the section. Update your <section> tag again, like so: <section aria-live="assertive" aria-atomic="true"> The aria-atomic="true" attribute tells screenreaders to read out the entire element contents as one atomic unit, not just the bits that were updated. Note: You can see the finished example at aria-live.html (see it running live). Note: The aria-relevant property is also quite useful for controlling what gets read out when a live region is updated. You can for example only get content addi...
...And 7 more matches
Accessibility API cross-reference
CHECKBUTTON CHECK_BOX CHECK_BOX checkbox or switch <input type=checkbox> Pretty obvious what this is for CLOCK n/a n/a timer <time> Column of cells in a table - how would the user specifically point to this, as oppo...
...ou think - this is for the damn paperclip CHARACTER n/a n/a n/a For graphics representing data CHART n/a figure ? 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. CHECKBUTTON CHECK_BOX CHECK_BOX checkbox or switch <input type=checkbox> Pretty obvious what this is for CLOCK n/a n/a timer <time> Column of cells in a table - how would the user specifically point to this, as opposed to the column header or cells? COLUMN n/a n/a n/a The headi...
... A type of live region where non-essential information changes frequently. 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. menuitemcheckbox A checkable menuitem in a set of elements with the same role, only one of which can be checked at a time. menuitemradio Any menu other than the menu bar Java: MENU is for pull-downs, POPUP_MENU for all others MENUPOPUP POPUP_MENU, MENU POPUP_MENU, MENU menu ...
...And 7 more matches
Displaying Places information using views
The following example uses the built-in tree view to display bookmarks whose titles or URLs contain "mozilla". Remember that, because XUL is XML, any ampersands in query URIs must be written as entity reference &amp; and not simply &. ...
...l id="title" label="My Bookmarks" flex="1" primary="true" /> </treecols> <treechildren /> </tree> The next example does the same as the last but uses JavaScript to set the tree's place attribute: var histServ = Cc["@mozilla.org/browser/nav-history-service;1"]. getService(Ci.nsINavHistoryService); var query = histServ.getNewQuery(); query.searchTerms = "mozilla"; query.onlyBookmarked = true; var opts = histServ.getNewQueryOptions(); opts.queryType = opts.QUERY_TYPE_BOOKMARKS; var uri = histServ.queriesToQueryString([query], 1, opts); var tree = document.getElementById("mytree"); tree.place = uri; These two examples use the built-in tree view, but the point is to demonstrate the use of the place attribute and property. In this regard the built-in menu and toolbar views are no diff...
...otified, the view is responsible for updating itself. Note: Starting in Gecko 2.0, nsINavHistoryResultViewer has been replaced by the more powerful nsINavHistoryResultObserver. Tree view Create a built-in tree view by setting the type attribute to "places" on a tree element. The treechildren element should be empty: <tree type="places"> <treecols> <treecol id="title" flex="1" primary="true" /> <treecol id="url" flex="1" /> </treecols> <treechildren /> </tree> The tree view is implemented in browser/components/places/content/tree.xml. See the tree reference and Trees tutorial for general information about trees. If you would like your tree view to be styled in the same manner that Firefox styles its uses of the view, you should include the following stylesheet. Note that ...
...And 7 more matches
Frame script loading and lifetime
Loading frame scripts To load a frame script use the loadFrameScript() function. This line of code loads a frame script into the currently selected tab. The script just writes "foo" to the command line: // chrome script var mm = gBrowser.selectedBrowser.messageManager; mm.loadFrameScript('data:,dump("foo\\n")', true); loadFrameScript() takes two mandatory parameters: A URL that points to the frame script you want to load A boolean flag, allowDelayedLoad Note: if the message manager is a global frame message manager or a window message manager, loadFrameScript() may load the script multiple times, once in each applicable frame. chrome: URLs Extension developers usually use a chrome:// URL to refer to the frame scripts. To define the mapping between a chrome:// URL and a fra...
... frame. chrome: URLs Extension developers usually use a chrome:// URL to refer to the frame scripts. ...
...URL and a frame script packaged with an extension, use a "chrome.manifest" file to register a chrome URL: // chrome.manifest content my-e10s-extension chrome/content/ // chrome script mm.loadFrameScript("chrome://my-e10s-extension/content/content.js", true); allowDelayedLoad If the message manager is a global frame message manager or a window message manager then: If allowDelayedLoad is true, the frame script will be loaded into any new frame, which has opened after the loadFrameScript() call. For example: var mm = window.messageManager; mm.loadFrameScript("chrome://my-e10s-extension/content/frame-script.js", true); The script will be loaded into all tabs currently open in this window, and all new tabs opened afterwards. If allowDelayedLoad is false, the script will only be ...
...And 7 more matches
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
forward buttons are disabled when you cannot move backwards/forwards, and enabled when you can. ...
...ackward."); } else { back.disabled = true; console.log("It's not possible to navigate the history backward."); } } } function canMoveFwd() { var request = browser.getCanGoForward(); request.onsuccess = function() { if (request.result) { fwd.disabled = false; console.log("It's possible to navigate the history forward."); } else { fwd.disabled = true; console.log("It's not possible to navigate the history forward."); } } } So here we have functions to detect whether we can navigate forwards/backwards in the history at any point. ...
... Note that Promise versions of Browser API DOM request methods also exist, so you can use async promise style syntax if you so wish. ...
...And 7 more matches
NSS Sample Code Sample1
// If there is o...
... // If there is one, no further action is required. rv = getPrivateKey(&prvKey);...
..., no further action is required. rv = getPrivateKey(&prvKey); if (rv == 0 && prvKey) goto done; rv = 0; // These could be parameters to the Init function rsaParams.keySizeInBits = 1024; rsaParams.pe = 65537; slot = PK11_GetInternalKeySlot(); if (!slot) { rv = 1; goto done; } prvKey = PK11_GenerateKeyPair(slot, CKM_RSA_PKCS_KEY_PAIR_GEN, &rsaParams, &pubKey, PR_TRUE, PR_TRUE, 0); if (!prvKey) { rv = 1; goto done; } // Set the nickname on the private key so that it // can be found later. s = PK11_SetPrivateKeyNickname(prvKey, mServerName); if (s != SECSuccess) { rv = 1; goto done; } done: if (slot) PK11_FreeSlot(slot); if (pubKey) SECKEY_DestroyPublicKey(pubKey); if (prvKey) SECKEY_DestroyPrivateKey(prvKey); return rv; } int Server::Gene...
...And 7 more matches
JSAPI Cookbook
gc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); JSObject *global = JS_GetGlobalForObject(cx, &args.callee()); ... } Defining a function // JavaScript function justForFun() { return null; } /* JSAPI */ bool justForFun(JSContext *cx, unsigned argc, JS::Value *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); args.rval().setNull(); return true; } ... /* * Add this to your JSContext setup code. * This makes your C function visible as a global function in JavaScript. */ if (!JS_DefineFunction(cx, global, "justForFun", &justForFun, 0, 0)) return false; To define many JSAPI functions at once, use JS_DefineFunctions. Creating an Array // JavaScript var x = []; // or "x = Array()", or "x = new Array" /* JSAPI */ JS::RootedObj...
...// empty argument list JS::RootedValue r(cx); if (!JS_CallFunctionValue(cx, NULL, f, args, &r) return false; Returning an integer // JavaScript return 23; /* JSAPI * * Warning: This only works for integers that fit in 32 bits. * Otherwise, convert the number to floating point (see the next example). */ JS::CallArgs args = JS::CallArgsFromVp(argc, vp); args.rval().setInt32(23); return true; Returning a floating-point number // JavaScript return 3.14159; /* JSAPI */ JS::CallArgs args = JS::CallArgsFromVp(argc, vp); args.rval().setDouble(3.14159); Exception handling throw The most common idiom is to create a new Error object and throw that. JS_ReportError does this. Note that JavaScript exceptions are not the same thing as C++ exceptions. The JSAPI code also has to return fa...
...r example: foo(); bar(); } catch (exc) { // do error-handling stuff here } /* JSAPI */ /* try some stuff here; for example: */ if (!JS_CallFunctionName(cx, global, "foo", 0, NULL, &r)) goto catch_block; /* instead of returning false */ if (!JS_CallFunctionName(cx, global, "bar", 0, NULL, &r)) goto catch_block; /* instead of returning false */ return true; catch_block: js::RootedValue exc(cx); if (!JS_GetPendingException(cx, &exc)) return false; JS_ClearPendingException(cx); /* do error-handling stuff here */ return true; finally // JavaScript try { foo(); bar(); } finally { cleanup(); } If your C/C++ cleanup code doesn't call back into the JSAPI, this is straightforward: /* JSAPI */ bool success = f...
...And 7 more matches
Places Developer Guide
-service;1"] .getService(Ci.nsINavHistoryService); var query = history.getNewQuery(); query.setFolders([myFolderId], 1); var result = history.executeQuery(query, history.getNewQueryOptions()); // The root property of a query result is an object representing the folder you specified above. var folderNode = result.root; // Open the folder, and iterate over its contents. folderNode.containerOpen = true; for (var i=0; i < folderNode.childCount; ++i) { var childNode = folderNode.getChild(i); // Some item properties. var title = childNode.title; var id = childNode.itemId; var type = childNode.type; // Some type-specific actions. if (type == Ci.nsINavHistoryResultNode.RESULT_TYPE_URI) { var uri = childNode.uri; } else if (type == Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER) { child...
...(i); // Some item properties. var title = childNode.title; var id = childNode.itemId; var type = childNode.type; // Some type-specific actions. if (type == Ci.nsINavHistoryResultNode.RESULT_TYPE_URI) { var uri = childNode.uri; } else if (type == Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER) { childNode.QueryInterface(Ci.nsINavHistoryContainerResultNode); childNode.containerOpen = true; // now you can iterate over a subfolder's children } } ther available node types are documented in the IDL. Searching Bookmarks Queries are executed through the history service. The example below shows how to search through all bookmarks, and to iterate over the results. var bookmarks = Cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getService(Ci.nsINavBookmarksService);...
...ry.searchTerms = "firefox"; var options = history.getNewQueryOptions(); options.queryType = options.QUERY_TYPE_BOOKMARKS; var result = history.executeQuery(query, options); // The root property of a query result is an object representing the folder you specified above. var resultContainerNode = result.root; // Open the folder, and iterate over its contents. resultContainerNode.containerOpen = true; for (var i=0; i < resultContainerNode.childCount; ++i) { var childNode = resultContainerNode.getChild(i); // Accessing properties of matching bookmarks var title = childNode.title; var uri = childNode.uri; } Updating Bookmark Items For all items: setItemTitle(aItemId, aTitle) - Changes an item's title. setItemIndex(aItemId, aIndex) - Changes an item's position. NOTE: This does not...
...And 7 more matches
Places utilities for JavaScript
on. Return type Returns a string from the default places stringbundle. getString() string getString(string key) Parameters key The name of the string to get. Return type Returns a string from the default places stringbundle. nodeIs() There are a ton of nodeIs(something) functions in here to check properties of a bookmark node. 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. boolean nodeIsBookmark(aNode) Determines whether or not a ResultNode represents a bookmarked URI. boolean nodeIsSeparator(aNode) Determines whether or not a ResultNode is a Bookmark separator. boolean nodeIsVisit(aNode) Determines whet...
...s a remote container registered by the livemark service. boolean nodeIsLivemarkItem(aNode) Determines whether a result node is a live-bookmark item Parameters aNode The node to check. Return type Returns a boolean. isReadonlyFolder() Determines whether or not a node is a readonly folder. boolean isReadonlyFolder(aNode) Parameters aNode The node to check. Return type Return true if the node is a folder, false otherwise. getIndexOfNode() Gets the index of a node within its parent container int getIndexOfNode(aNode) Parameters aNode The node to look up Return type Returns the index of the node within its parent container, or -1 if the node was not found or the node specified has no parent. wrapNode() String-wraps a result node according to the rules of the s...
... action was copy, so don't move folders or links. Return type Returns an object implementing nsITransaction that can perform the move/insert. getFolderContents() getFolderContents(aFolderId, aExcludeItems, aExpandQueries) Generates a nsINavHistoryResult for the contents of a folder. Parameters folderId The folder to open [optional] excludeItems True to hide all items (individual bookmarks). This is used on the left places pane so you just get a folder hierarchy. [optional] expandQueries True to make query items expand as new containers. For managing,you want this to be false, for menus and such, you want this to be true. Return type Returns a nsINavHistoryResult containing the contents of the folder. The result.root is guaranteed to be ...
...And 7 more matches
nsIDocShell
boolean forward, out boolean tookFocus); Attributes Attribute Type Description allowAuth boolean Certain dochshells (like the message pane) should not throw up auth dialogs because it can act as a password trojan. allowDNSPrefetch boolean Attribute that determines whether DNS prefetch is allowed for this subtree of the docshell tree. Defaults to true. Setting this will make it take effect starting with the next document loaded in the docshell. allowImages boolean Attribute stating whether or not images should be loaded. allowJavascript boolean Whether to allow Javascript execution. allowMedia boolean Attribute stating whether or not media (audio/video) should be loaded. allowMetaRedirect...
...bute stating if refresh based redirects can be allowed. allowPlugins boolean Whether to allow plugin execution. allowSubframes boolean Attribute stating if it should allow subframes (framesets/iframes) or not. allowWindowControl boolean Specifies whether or not content is allowed to control the window (that is, to resize or move the window). Default is true, which lets content control the window. appType unsigned long The type of application that created this window. Types are defined in Constants. busyFlags unsigned long Current busy state for DocShell. Valid states are defined in Constants. Read only. canExecuteScripts boolean Whether this docshell can execute scripts based on its hierarchy. The rule o...
... Obsolete since Gecko 1.9.2 historyID unsigned long long The ID of the docshell in the session history. Read only. isActive boolean Indicates whether or not the DocShell is currently active. An active DocShell is one that is currently visible, which means it's not a good candidate for optimizations such as image frame discarding. DocShells are active if this is true, which is the default state. Note: Starting in Gecko 8.0, isActive is false for documents in minimized windows. isAppTab boolean Sets whether a docshell is an app tab. An app tab docshell may behave differently than a non-app tab docshell in some cases, such as when handling link clicks. Docshells are not app tabs unless told otherwise. isExecutingOnLo...
...And 7 more matches
nsITextInputProcessor
void setPendingCompositionString(in DOMString aString); void shareModifierStateOf(in nsITextInputProcessor aOther); boolean startComposition([optional] in nsIDOMKeyEvent aDOMKeyEvent, [optional] in unsigned long aKeyFlags); Attributes Attribute Type Description hasComposition boolean Whether the instance has composition or not. true if it has composition. Read only. Constants Constant Value Description ATTR_RAW_CLAUSE 0x02 A clause attribute. This means that the clause is not converted, i.e., raw text of user input. ATTR_RAW_SELECTED_CLAUSE 0x03 A clause attribute but this is typically not used. This means that the clause is not converted but selected to convert or mod...
...fy. ATTR_CONVERTED_CLAUSE 0x04 A clause attribute. This means that the clause is already converted. ATTR_SELECTED_CLAUSE 0x05 A clause attribute. This means that the clause is already converted and is selected to convert. KEY_DEFAULT_PREVENTED 0x00000001 One of aKeyFlags. When this is specified, defaultPrevented attribute of dispatching keyboard events true. This is not useful in usual cases. This may be useful for automated tests. KEY_NON_PRINTABLE_KEY 0x00000002 One of aKeyFlags. When you attempt to dispatch a non-printable key's events, it's recommented this be specified. If the key attribute value is not a registered key name, this flag causes throwing an exception. Therefore, this can prevent non-printable key events to cause dis...
...rs the callback to the instance. boolean beginInputTransaction(in nsIDOMWindow aWindow, in nsITextInputProcessorCallback aCallback); Parameters aWindow The DOM window which has focused editor. This must not be null. aCallback The callback object. This must not be null. See the document of nsITextInputProcessorCallback for the details. Return value Returns true if the instance could create composition. Otherwise, false. beginInputTransactionForTests() This must be called before starting composition for automated tests every time. This tries to get the rights to create composition on the window. If no other instance is composing on the window, this associates the instance with the window and registers the callback to the instance if it's specified. bo...
...And 7 more matches
EventTarget.addEventListener() - Web APIs
self. options Optional An options object specifies characteristics about the event listener. The available options are: capture A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. once A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked. passive A Boolean that, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. See Improving scrolling performance with passive listeners to learn more. mozSystemGroup A Bo...
...in the target phase, rather than the capturing and bubbling phases. Events in the target phase will trigger all listeners on an element in the order they were registered, regardless of the useCapture parameter. Note: useCapture has not always been optional. Ideally, you should include it for the widest possible browser compatibility. wantsUntrusted A Firefox (Gecko)-specific parameter. If true, the listener receives synthetic events dispatched by web content (the default is false for browser chrome and true for regular web pages). This parameter is useful for code found in add-ons, as well as the browser itself. Return value undefined Usage notes The event listener callback The event listener can be specified as either a callback function or an object that implements EventListene...
...ndle this scenario intelligently. You can do this by using feature detection for each of the options you're interested in. For example, if you want to check for the passive option: let passiveSupported = false; try { const options = { get passive() { // This function will be called when the browser // attempts to access the passive property. passiveSupported = true; return false; } }; window.addEventListener("test", null, options); window.removeEventListener("test", null, options); } catch(err) { passiveSupported = false; } This creates an options object with a getter function for the passive property; the getter sets a flag, passiveSupported, to true if it gets called. That means that if the browser checks the value of the passive prop...
...And 7 more matches
Control flow and error handling - JavaScript
tement within the block is in the same scope as the var x statement before the block. (In C or Java, the equivalent code would have outputted 1.) Since ECMAScript2015, the let and const variable declarations are block-scoped. See the let and const reference pages for more information. Conditional statements A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: if...else and switch. if...else statement Use the if statement to execute a statement if a logical condition is true. 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 ...
...Otherwise, statement_2 is executed. ...
...Otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements. ...
...And 7 more matches
Strict equality (===) - JavaScript
pository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x === y Description The strict equality operators (=== and !==) use the Strict Equality Comparison Algorithm to compare two operands. If the operands are of different types, return false. If both operands are objects, return true only if they refer to the same object. If both operands are null or both operands are undefined, return true. If either operand is NaN, return false. Otherwise, compare the two operand's values: Numbers must have the same numeric values. +0 and -0 are considered to be the same value. Strings must have the same characters in the same order. Booleans must be both true or both false. ...
...trings must have the same characters in the same order. Booleans must be both true or both false. The most notable difference between this operator and the equality (==) operator is that if the operands are of different types, the == operator attempts to convert them to the same type before comparing. ...
...oth false. The most notable difference between this operator and the equality (==) operator is that if the operands are of different types, the == operator attempts to convert them to the same type before comparing. ...
...And 7 more matches
delete operator - JavaScript
e interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax delete expression Where expression should evaluate to a property reference, e.g.: delete object.property delete object['property'] Parameters object The name of an object, or an expression evaluating to an object. property The property to delete. 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. Exceptions Throws TypeError in strict mode if the property is an own non-configurable property. Description Unlike what common belief suggests (perhaps due to other programming languages like delete in C++), the delete operator has nothing to do with directly freein...
...erty. Description Unlike what common belief suggests (perhaps due to other programming languages like delete in C++), the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references. See the memory management page for more details. The delete operator removes a given property from an object. On successful deletion, it will return true, else false will be returned. However, it is important to consider the following scenarios: If the property which you are trying to delete does not exist, delete will not have any effect and will return true. If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has...
...ey were defined. Non-configurable properties cannot be removed. This includes properties of built-in objects like Math, Array, Object and properties that are created as non-configurable with methods like Object.defineProperty(). The following snippet gives a simple example: var Employee = { age: 28, name: 'abc', designation: 'developer' } console.log(delete Employee.name); // 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. In strict mode this will raise a TypeError. var Employee = {}; Object.definePropert...
...And 7 more matches
instanceof - JavaScript
please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax object instanceof constructor Parameters object The object to test. constructor Function to test against Description The instanceof operator tests the presence of constructor.prototype in object's prototype chain. ...
...unction to test against Description The instanceof operator tests the presence of constructor.prototype in object's prototype chain. ...
...nceof operator tests the presence of constructor.prototype in object's prototype chain. ...
...And 7 more matches
window/utils - Archive of obsolete content
ndow The window whose outer window we are interested in. Returns ID: the outer window's ID. ...
...ceof Ci.nsIXULWindow // => true Parameters window : nsIDOMWindow Returns nsIXULWindow getBaseWindow(window) Returns the nsIBaseWindow for the given nsIDOMWindow: var { Ci } = require('chrome'); var utils = require('sdk/window/utils'); var active = utils.getMostRecentBrowserWindow(); active instanceof Ci.nsIBaseWindow // => false utils.getBaseWindow(active) instanceof Ci.nsIBaseWindow // => true Parameters window : nsIDOMWindow Returns nsIBaseWindow getToplevelWindow(window) Returns the toplevel nsIDOMWindow for the given child nsIDOMWindow: var { Ci } = require('chrome'); var utils = require('sdk/window/utils'); var browserWindow = utils.getMostRecentBrowserWindow(); var window = browserWindow.content; // `window` object for the current webpage utils.getToplevelWindow(window) == ...
... Parameters window : nsIDOMWindow Returns nsIDocShell getWindowLoadingContext(window) Returns the nsILoadContext. Parameters window : nsIDOMWindow Returns nsILoadContext open(uri, options) This function is used to open top level (application) windows...
...And 6 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
opment, but I recommend it as a way to work more efficiently. Preference Description Value nglayout.debug.disable_xul_cache (not present in Firefox 3.5+) Ordinarily, Firefox will cache XUL documents after they have been read in once, to speed subsequent displays. Disabling this cache forces XUL documents to be reloaded any every time they are displayed. ...
... Ordinarily, Firefox will cache XUL documents after they have been read in once, to speed subsequent displays. Disabling this cache forces XUL documents to be reloaded any every time they are displayed. True browser.dom.window.dump.enabled (not present in Firefox 3.5+) Enables use of the dump method for debugging. Refer to the "JavaScript debugging methods" sidebar. True javascript.options.showInConsole (present in Firefox 3.5+) Outputs JavaScript errors to the error console. ...
...forces XUL documents to be reloaded any every time they are displayed. True browser.dom.window.dump.enabled (not present in Firefox 3.5+) Enables use of the dump method for debugging. Refer to the "JavaScript debugging methods" sidebar. True javascript.options.showInConsole (present in Firefox 3.5+) Outputs JavaScript errors to the error console. ...
...And 6 more matches
preference - Archive of obsolete content
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
.... Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. instantApply Type: boolean If true, the preference will be changed as soon as the user interface is modified. inverted Type: boolean For boolean preferences, if this attribute is set to true, it indicates that the value of the preference is the reverse of the user interface element attached to it. For instance, checking the checkbox disables the preference instead of enabling it. name Type: string The name of the...
...However, the value may still be modified by a script. tabindex Type: integer The tab order of the element. The tab order is the order in which the focus is moved when the user presses the "tab" key. Elements with a higher tabindex are later in the tab sequence. type Type: one of the values below The preference type which sho...
...And 6 more matches
treecol - Archive of obsolete content
y. More information is available in the XUL tutorial. Attributes crop, cycler, dragging, editable, fixed, hidden, hideheader, ignoreincolumnpicker, label, primary, sort, sortActive, sortDirection, src, type, width Properties accessibleType Style classes treecol-image Examples This example shows a checkbox in the first column, requires the style below. ...
... cycler, dragging, editable, fixed, hidden, hideheader, ignoreincolumnpicker, label, primary, sort, sortActive, sortDirection, src, type, width Properties accessibleType Style classes treecol-image Examples This example shows a checkbox in the first column, requires the style below. ...
...pe, width Properties accessibleType Style classes treecol-image Examples This example shows a checkbox in the first column, requires the style below. <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). On Firefox 2.x and 3.x, all operating systems ...
...And 6 more matches
LiveConnect Overview - Archive of obsolete content
of jsCode. If myFunction is not defined as a JavaScript function, the JavaScript interpreter cannot evaluate jsCode. The interpreter generates an error message, the Java handler catches the message, and the doit method returns an instance of netscape.javascript.JSException. However, suppose myFunction is defined in JavaScript as follows: function myFunction() { try { if (theCondition == true) { return "Everything's ok"; } else { throw "JavaScript error occurred"; } } catch (e) { if (canHandle == true) { handleIt(); } else { throw e; } } } If theCondition is false, the function throws an exception. The exception is caught in the JavaScript code, and if canHandle is true, JavaScript handles it. If canHandle is fal...
...gative-infinity mode. Values which are too large or small to be represented result in a run-time error. NaN can not be converted and results in a run-time error. java.lang.String Values are converted to strings. For example: 237 becomes "237" boolean 0 and NaN values are converted to false. Other values are converted to true. When a JavaScript number is passed as a parameter to a Java method which expects an instance of java.lang.String, the number is converted to a string. Use the equals() method to compare the result of this conversion with other string values. Boolean Values When you pass JavaScript Boolean types as parameters to Java methods, Java converts the values according to the rules describe...
... Java parameter type Conversion rules boolean All values are converted directly to the Java equivalents. java.lang.Boolean java.lang.Object A new instance of java.lang.Boolean is created. Each parameter creates a new instance, not one instance with the same primitive value. java.lang.String Values are converted to strings. For example: true becomes "true" false becomes "false" byte char double float int long short true becomes 1 false becomes 0 When a JavaScript Boolean is passed as a parameter to a Java method which expects an instance of java.lang.String, the Boolean is converted to a string. Use the == operator to compare the result of this conve...
...And 6 more matches
EncDecMAC using token object - sample 3
_STDERR, "PK11_ReadRawAttribute returned (%d)\n", rv); PR_fprintf(PR_STDERR, "Could not read SymKey CKA_ID attribute\n"); return rv; } return rv; } /* * Generate a Symmetric Key */ PK11SymKey * GenerateSYMKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE mechanism, int keySize, SECItem *keyID, secuPWData *pwdata) { SECStatus rv; PK11SymKey *key; if (PK11_NeedLogin(slot)) { rv = PK11_Authenticate(slot, PR_TRUE, pwdata); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Could not authenticate to token %s.\n", PK11_GetTokenName(slot)); return NULL; } } /* Generate the symmetric key */ key = PK11_TokenKeyGen(slot, mechanism, NULL, keySize, keyID, PR_TRUE, pwdata); if (!key) { PR_fprintf(PR_STDERR, "Symmetric Key Generation Failed \n"); } return key; } /* * MacInit */ SECStatus MacInit(PK11Context *ctx) { SEC...
...t *ctx = NULL; SECItem *secParam = PK11_ParamFromIV(CKM_AES_CBC, &ivItem); if (secParam == NULL) { PR_fprintf(PR_STDERR, "Crypt Failed : secParam NULL\n"); return NULL; } ctx = PK11_CreateContextBySymKey(CKM_AES_CBC, operation, key, secParam); if (ctx == NULL) { PR_fprintf(PR_STDERR, "Crypt Failed : can't create a context\n"); goto cleanup; } cleanup: if (secParam) { SECITEM_FreeItem(secParam, PR_TRUE); } return ctx; } /* * Common encryption and decryption code */ SECStatus Crypt(PK11Context *ctx, unsigned char *out, unsigned int *outLen, unsigned int maxOut, unsigned char *in, unsigned int inLen) { SECStatus rv; rv = PK11_CipherOp(ctx, out, outLen, maxOut, in, inLen); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Crypt Failed : PK11_CipherOp returned %d\n", rv); goto cleanup; } cleanup: if (...
...intf(PR_STDERR, "Write MAC Failure\n"); goto cleanup; } pad[0] = paddingLength; padItem.type = siBuffer; padItem.data = (unsigned char *)pad; padItem.len = sizeof(pad[0]); WriteToHeaderFile(padItem.data, padItem.len, PAD, headerFile); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Write PAD Failure\n"); goto cleanup; } rv = SECSuccess; cleanup: if (ctxmac != NULL) { PK11_DestroyContext(ctxmac, PR_TRUE); } if (ctxenc != NULL) { PK11_DestroyContext(ctxenc, PR_TRUE); } return rv; } /* * Find the Key for the given mechanism */ PK11SymKey* FindKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE mechanism, SECItem *keyBuf, secuPWData *pwdata) { SECStatus rv; PK11SymKey *key; if (PK11_NeedLogin(slot)) { rv = PK11_Authenticate(slot, PR_TRUE, pwdata); if (rv != SECSuccess) { PR_fprintf(PR_STDERR, "Could not auth...
...And 6 more matches
nsIFile
ile or directory as this nsIFile. contains() This method tests whether or not the path represented by the specified nsIFile instance is a descendant of the path represented by this nsIFile. This nsIFile should point to a directory, while the specified argument can point to a file or directory. boolean contains( in nsIFile inFile ); Parameters inFile The nsIFile to test. Return value true if inFile is a descendant of this nsIFile. inFile does not need to be a direct child of this nsIFile to be considered a descendant. copyTo() This method copies a source file to a new location if it does not already exist. This method will NOT resolve aliases/shortcuts during the copy. void copyTo( in nsIFile newParentDir, in AString newName ); Parameters newParentDir This parameter ...
...a known type. NS_ERROR_FILE_TOO_BIG Indicates that the search for nonexistent files was unsuccessful because all of the attempted leaf name variants already exist. equals() This method tests whether or not two nsIFile instances correspond to the same file or directory. boolean equals( in nsIFile inFile ); Parameters inFile The nsIFile to compare this nsIFile against. ...
... equals() This method tests whether or not two nsIFile instances correspond to the same file or directory. boolean equals( in nsIFile inFile ); Parameters inFile The nsIFile to compare this nsIFile against. Return value true if "inFile" is equivalent to this nsIFile. exists() This method tests whether or not this nsIFile exists. boolean exists() Parameters None. Return value true if the file or directory exists. Otherwise it returns false. isDirectory() This method tests whether or not this nsIFile corresponds to a directory. boolean isDirectory(); Parameters None. Return value true if this nsIFile corresponds to a directory. Otherwise it returns false. isExecutable() This method tests whether or not this nsIFile corresponds to a file that may be executed. Not...
...And 6 more matches
nsIHTMLEditor
returnInParagraphCreatesNewParagraph boolean A boolean indicating if a return key pressed in a paragraph creates another paragraph or just inserts a <br> at the caret. Constants Constant Value Description eLeft 0 eCenter 1 ...
...AnonymousButtons() Checks if the anonymous nodes created by the HTML editor have to be refreshed or hidden depending on a possible new state of the selection. void checkSelectionStateForAnonymousButtons( in nsISelection aSelection ); Parameters aSelection A selection. createAnonymousElement() Returns an anonymous nsDOMElement of type aTag, child of aParentNode. If aIsCreatedHidden is true, the class "hidden" is added to the created element. If aAnonClass is not the empty string, it becomes the value of the attribute "_moz_anonclass" nsIDOMElement createAnonymousElement( in AString aTag, in nsIDOMNode aParentNode, in AString aAnonClass, in boolean aIsCreatedHidden ); Parameters aTag A string representing the desired type of the element to create. aParentNode The pa...
...stead of inserting new <FONT> tag. void decreaseFontSize(); Parameters None. doDrag() Transfers the relevant data (as appropriate) to a transferable so it can later be dropped. void doDrag( in nsIDOMEvent aEvent ); Parameters aEvent getAlignment() Returns what alignment is in the selection. void getAlignment( out boolean aMixed, out short aAlign ); Parameters aMixed true if there is more than one type of list item, or if there is some list and non-list. aAlign Enum value for first encountered alignment (left/center/right) getBackgroundColorState() getFontColorState() returns what font face is in the selection. AString getBackgroundColorState( out boolean aMixed ); Parameters aMixed true if there is more than one font color. Return value Color str...
...And 6 more matches
Debugger.Object - Firefox Developer Tools
collection has no visible effect on Debugger.Object instances. Accessor Properties of the Debugger.Object prototype A Debugger.Object instance inherits the following accessor properties from its prototype: proto The referent's prototype (as a new Debugger.Object instance), or null if it has no prototype. class A string naming the ECMAScript [[Class]] of the referent. callable true if the referent is a callable object (such as a function or a function proxy); false otherwise. name The name of the referent, if it is a named function. If the referent is an anonymous function, or not a function at all, this is undefined. This accessor returns whatever name appeared after the function keyword in the source code, regardless of whether the function is the result of instan...
... implicit, and in a different compartment from the function and descriptor.) defineProperties(properties) Add the properties given byproperties to the referent. (This function behaves like Object.defineProperties, except that the target object is implicit, and in a different compartment from theproperties argument.) deleteProperty(name) Remove the referent's property namedname. Return true if the property was successfully removed, or if the referent has no such property. Return false if the property is non-configurable. seal() Prevent properties from being added to or deleted from the referent. Return this Debugger.Object instance. (This function behaves like the standard Object.seal function, except that the object to be sealed is implicit and in a different compartment from...
...d Object.freeze function, except that the object to be sealed is implicit and in a different compartment from the caller.) preventExtensions() Prevent properties from being added to the referent. ...
...And 6 more matches
Web Console remoting - Firefox Developer Tools
e Firefox/B2G instances. startListeners(listeners, onResponse) The new startListeners packet: { "to": "conn0.console9", "type": "startListeners", "listeners": [ "PageError", "ConsoleAPI", "NetworkActivity", "FileActivity" ] } The reply is: { "startedListeners": [ "PageError", "ConsoleAPI", "NetworkActivity", "FileActivity" ], "nativeConsoleAPI": true, "from": "conn0.console9" } The reply tells which listeners were started and it includes a flag nativeConsoleAPI which tells if the window.console object was overridden by the scripts in the page or not. Tab navigation To listen to the tab navigation events you also need to attach to the tab actor for the given tab. The tabNavigated notification comes from tab actors. Prior to Firefox 20 ...
...ed a LocationChange listener, with an associated locationChanged notification. This is no longer the case: we have made changes to allow the Web Console client to reuse the tabNavigated notification (bug 792062). ...
...t to reuse the tabNavigated notification (bug 792062). When page navigation starts the following packet is sent from the tab actor: { "from": tabActor, "type": "tabNavigated", "state": "start", "url": newURL, "nativeConsoleAPI": true } The nativeConsoleAPI property tells if the window.console object is native or not for the top level window object for the given tab - this is always true when navigation starts. ...
...And 6 more matches
Using IndexedDB - Web APIs
ustomers", { keyPath: "ssn" }); // Create an index to search customers by name. We may have duplicates // so we can't use a unique index. objectStore.createIndex("name", "name", { unique: false }); // Create an index to search customers by email. We want to ensure that // no two customers have the same email, so use a unique index. objectStore.createIndex("email", "email", { unique: true }); // Use transaction oncomplete to make sure the objectStore creation is // finished before adding data into it. objectStore.transaction.oncomplete = function(event) { // Store values in the newly created objectStore. var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers"); customerData.forEach(function(customer) { customerObjectStore...
... or even clearing all records from an object store never affects the object store's key generator. We can create another object store with the key generator as below: // Open the indexedDB. var request = indexedDB.open(dbName, 3); request.onupgradeneeded = function (event) { var db = event.target.result; // Create another object store called "names" with the autoIncrement flag set as true. var objStore = db.createObjectStore("names", { autoIncrement : true }); // Because the "names" object store has the key generator, the key for the name value is generated automatically. // The added records would be like: // key : 1 => value : "Bill" // key : 2 => value : "Donna" customerData.forEach(function(customer) { objStore.add(customer.name); }); }...
...given value(s)) or "open" (i.e., the key range does not include the given value(s)). ...
...And 6 more matches
MediaDevices.getUserMedia() - Web APIs
meter is a MediaStreamConstraints object with two members: video and audio, describing the media types requested. Either or both must be specified. If the browser cannot find all media tracks with the specified types that meet the constraints given, then the returned promise is rejected with NotFoundError. The following requests both audio and video without any specific requirements: { audio: true, video: true } If true is specified for a media type, the resulting stream is required to have that type of track in it. If one cannot be included for any reason, the call to getUserMedia() will result in an error. While information about a user's cameras and microphones are inaccessible for privacy reasons, an application can request the camera and microphone capabilities it needs and wants,...
...ack in it. If one cannot be included for any reason, the call to getUserMedia() will result in an error. While information about a user's cameras and microphones are inaccessible for privacy reasons, an application can request the camera and microphone capabilities it needs and wants, using additional constraints. ...
...xpresses a preference for 1280x720 camera resolution: { audio: true, video: { width: 1280, height: 720 } } The browser will try to honour this, but may return other resolutions if an exact match is not available, or the user overrides it. To require a capability, use the keywords min, max, or exact (a.k.a. min == max). The following demands a minimum resolution of 1280x720: { audio: true, video: { width: { min: 1280 }, height: { min: 720 } } } If no camera exists with this resolution or higher, then the returned promise will be rejected with OverconstrainedError, and the user will not be prompted. The reason for the difference in behaviour is that the keywords min, max, and exact are inherently mandatory. Whereas plain values and a keyword called ideal are not. He...
...And 6 more matches
SubtleCrypto.wrapKey() - Web APIs
key. This means that it exports the key in an external, portable format, then encrypts the exported key. Wrapping a key helps protect it in untrusted environments, such as inside an otherwise unprotected data store or in transmission over an unprotected network. As with SubtleCrypto.exportKey(), you specify an export format for the key. To export a key, it must have CryptoKey.extractable set to true. But because wrapKey() also encrypts the key to be imported, you also need to pass in the key that must be used to encrypt it. This is sometimes called the "wrapping key". The inverse of wrapKey() is SubtleCrypto.unwrapKey(): while wrapKey is composed of export + encrypt, unwrapKey is composed of import + decrypt. Syntax const result = crypto.subtle.wrapKey( format, key, wrappingK...
...name: "PBKDF2"}, false, ["deriveBits", "deriveKey"] ); } /* Given some key material and some random salt derive an AES-KW key using PBKDF2. */ function getKey(keyMaterial, salt) { return window.crypto.subtle.deriveKey( { "name": "PBKDF2", salt: salt, "iterations": 100000, "hash": "SHA-256" }, keyMaterial, { "name": "AES-KW", "length": 256}, true, [ "wrapKey", "unwrapKey" ] ); } /* Wrap the given key. */ async function wrapCryptoKey(keyToWrap) { // get the key encryption key const keyMaterial = await getKeyMaterial(); salt = window.crypto.getRandomValues(new Uint8Array(16)); const wrappingKey = await getKey(keyMaterial, salt); return window.crypto.subtle.wrapKey( "raw", keyToWrap, wrappingKey, "AES-KW" ...
...eyMaterial = await getKeyMaterial(); salt = window.crypto.getRandomValues(new Uint8Array(16)); const wrappingKey = await getKey(keyMaterial, salt); return window.crypto.subtle.wrapKey( "raw", keyToWrap, wrappingKey, "AES-KW" ); } /* Generate an encrypt/decrypt secret key, then wrap it. */ window.crypto.subtle.generateKey( { name: "AES-GCM", length: 256, }, true, ["encrypt", "decrypt"] ) .then((secretKey) => { return wrapCryptoKey(secretKey); }) .then((wrappedKey) => { console.log(wrappedKey); }); PKCS #8 wrap This example wraps an RSA private signing key. It uses "pkcs8" as the export format and AES-GCM, with a password-derived key, to encrypt it. See the complete code on GitHub. let salt; let iv; /* Get some key material to use as input to ...
...And 6 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
nique you like. Note that this code is identical for both peers involved in the connection. Create the signaling and peer connections First, the signaling channel needs to be opened and the RTCPeerConnection needs to be created. The STUN server listed here is obviously not a real one; you'll need to replace stun.myserver.tld with the address of a real STUN server. ...
...e. Note that this code is identical for both peers involved in the connection. Create the signaling and peer connections First, the signaling channel needs to be opened and the RTCPeerConnection needs to be created. The STUN server listed here is obviously not a real one; you'll need to replace stun.myserver.tld with the address of a real STUN server. ...
... become unmuted once it starts receiving packets. We put the remainder of our reception code in there. If we already have video coming in from the remote peer (which we can see if the remote view's <video> element's srcObject property already has a value), we do nothing. Otherwise, we set srcObject to the stream at index 0 in the streams array. ...
...And 6 more matches
ARIA: switch role - Accessibility
The ARIA switch role is functionally identical to the checkbox role, except that instead of representing "checked" and "unchecked" states, which are fairly generic in meaning, the switch role represents the states "on" and "off." This example creates a widget and assigns the ARIA switch role to it. <button type="button" role="switch" aria-checked="true" id="speakerPower" class="switch"> <span>off</span> <span>on</span> </button> <label for="speakerPower" class="switch">Speaker power</label> Description The ARIA switch role is identical to the checkbox role, except instead of being "checked" or "unchecked", it is either "on" and "off." Like the checkbox role, the aria-checked attribute is required. The two possible values are true and false. Unlike a <checkbox> or role="checkb...
...ggling the value of a switch is the Space key. The developer is required to change the value of the aria-checked attribute dynamically when the switch is toggled. Associated ARIA roles, states, and properties aria-checked attribute The aria-checked attribute is required when using the switch role, as it represents the current state of the widget that the switch role is applied to. 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. The default value is false. aria-readonly attribute The aria-readonly attribute is supported by the switch role. It indicates whether the widget's state is editable by the user. A value of false means that the user can change the widget's state; a value of ...
... 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. The default value is false. aria-readonly attribute The aria-readonly attribute is supported by the switch role. It indicates whether the widget's state is editable by the user. A value of false means that the user can change the widget's state; a value of true means that the user cannot change the widget's state. The default value is false. Required JavaScript features Handler for click events When the user clicks on the switch widget, a click event is fired, which must be handled in order to change the state of the widget. Changing the aria-checked attribute When a click event is fired on the switch widget, the handler must change the value of...
...And 6 more matches
BigInt - JavaScript
-- it cannot be used with methods in the built-in Math object and cannot be mixed with instances of Number in operations; they must be coerced to the same type. Be careful coercing values back and forth, however, as the precision of a BigInt may be lost when it is coerced to a Number. Type information When tested against typeof, a BigInt will give "bigint": typeof 1n === 'bigint' // true typeof BigInt('1') === 'bigint' // true When wrapped in an Object, a BigInt will be considered as a normal "object" type: typeof Object(1n) === 'object' // true Operators The following operators may be used with BigInts (or object-wrapped BigInts): +, *, -, **, %. Bitwise operators are supported as well, except >>> (zero-fill right shift) as all BigInts are signed. Also unsupported is t...
...nts and not BigDecimals, this operation will round towards 0 (which is to say, it will not return any fractional digits). An operation with a fractional result will be truncated when used with a BigInt. ...
... is to say, it will not return any fractional digits). An operation with a fractional result will be truncated when used with a BigInt. ...
...And 6 more matches
Number.isInteger() - JavaScript
epository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Number.isInteger(value) Parameters value The value to be tested for being an integer. Return value A Boolean indicating whether or not the given value is an integer. ...
...om/mdn/interactive-examples and send us a pull request. Syntax Number.isInteger(value) Parameters value The value to be tested for being an integer. Return value A Boolean indicating whether or not the given value is an integer. Description If the target value is an integer, return true, otherwise return false. If the value is NaN or Infinity, return false. The method will also return true for floating point numbers that can be represented as integer. ...
...true, otherwise return false. If the value is NaN or Infinity, return false. The method will also return true for floating point numbers that can be represented as integer. ...
...And 6 more matches
Classes and Inheritance - Archive of obsolete content
tire article. Constructors Before the ECMASCript 6 standard, a JavaScript class was defined by creating a constructor function for that class. To illustrate this, let's define a simple constructor for a class Shape: function Shape(x, y) { this.x = x; this.y = y; } We can now use this constructor to create instances of Shape: let shape = new Shape(2, 3); shape instanceof Shape; // => true shape.x; // => 2 shape.y; // => 3 The keyword new tells JavaScript that we are performing a constructor call. Constructor calls differ from ordinary function calls in that JavaScript automatically creates a new object and binds it to the keyword this for the duration of the call. Moreover, if the constructor does not return a value, the result of the call defaults to the value of this. Construc...
... is found on the prototype, the lookup succeeds, and JavaScript pretends that it found the property on the original object. Every function has an explicit property, known as prototype. When a function is used in a constructor call, JavaScript makes the value of this property the prototype of the newly created object: let shape = Shape(2, 3); Object.getPrototypeOf(shape) == Shape.prototype; // => true All instances of a class have the same prototype. This makes the prototype the perfect place to define properties that are shared between instances of the class. To illustrate this, let's add a member function to the class Shape: Shape.prototype.draw = function () { throw Error("not yet implemented"); } let shape = Shape(2, 3); Shape.draw(); // => Error: not yet implemented Inheritance a...
...or for Shape is called as an ordinary function, and reuses the object created for the constructor call to Circle. Had we used a constructor call instead, the constructor for Shape would have been applied to a different object than the constructor for Circle. We can now use the above constructor to create instances of the class Circle: let circle = Circle(2, 3, 5); circle instanceof Circle; // => true circle.x; // => 2 circle.y; // => 3 circle.radius; // => 5 Inheritance and Prototypes There is a problem with the definition of Circle in the previous section that we have glossed over thus far. Consider the following: let circle = Circle(2, 3, 5); circle.draw(); // => TypeError: circle.draw is not a function This is not quite right. The method draw is defined on instances of Shape, so we d...
...And 5 more matches
core/heritage - Archive of obsolete content
exemplar constructs in a form of constructor functions with a proper prototype chain setup. Constructors created using Class function don't require new keyword (even though it can be used) for instantiation. Also, idiomatic SDK code does not uses optional new keywords, but you're free to use it in your add-on code: var fluffy = Dog('Fluffy'); // instatiation fluffy instanceof Dog // => true fluffy instanceof Class // => true As you could notice from example above classes created via Class function by default inherits from a Class itself. Also you could specify which class you want to inherit from by passing special extends property: var Pet = Class({ extends: Dog, // should inherit from Dog initialize: function initialize(breed, name) { // To call ancest...
...As a matter of fact since result is just a plain constructor function with proper prototype chain setup you could sub-class it as any other constructor...
...As a matter of fact since result is just a plain constructor function with proper prototype chain setup you could sub-class it as any other constructor: function Labrador() { // ... } Labrador.protot...
...And 5 more matches
Install Manifests - Archive of obsolete content
erface. This description should fit on one short line of text. Examples <em:description>Advanced foo tools.</em:description> developer The name(s) of co-developers. You may specify more than one of this value to specify multiple developers. Examples <em:developer>Jane Doe</em:developer> <em:developer>Koos van der Merwe</em:developer> hasEmbeddedWebExtension If present and given the value "true", this indicates that this add-on contains an embedded WebExtension. <em:hasEmbeddedWebExtension>true</em:hasEmbeddedWebExtension> homepageURL A link to the add-on's home page - intended for display in the user interface. Examples <em:homepageURL>https://www.example.com/</em:homepageURL> iconURL A chrome:// URL to an icon to display in the add-ons list. The icon will be displayed at 32x32 ...
...g box. This is only useful to extensions. If this property is specified, when the extension is selected in the Extensions list, the Options button is enabled and will show this. <em:optionsURL>chrome://myext/content/options.xul</em:optionsURL> Gecko 7 note In Firefox 7 you can also simply include your options XUL as a file named options.xul, in the base directory of the add-on. 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 compatibili...
... 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. <em:strictCompatibility>true</em:strictCompatibility> Usually, there is no need to restrict the compatibility: not all new releases will break your extension and, if it is hosted on AMO, you'll get notice several weeks in advance if a potential risk has been detected. Moreover, an extension being disabled, even for a short period, leads to a bad experience for the user. About the only time you should need to set this if you...
...And 5 more matches
Download Manager preferences - Archive of obsolete content
download.antivirus.dontclean Note: in Gecko 1.9.1. A boolean value that indicates whether the anti virus software should try to clean a downloaded file when a virus is detected. Default value is false. browser.download.manager.addToRecentDocs A boolean value that indicates whether or not new downloads should be added to the recent documents list. Default value is true. browser.download.manager.alertOnEXEOpen A boolean value that indicates whether the UI Should alert the user about the dangers of opening (executing) an EXE. The user may check a "don't ask" box on the UI to toggle this. Default value is true. browser.download.manager.closeWhenDone A boolean value indicating whether or not the Downloads window should close automaticall...
... In Other Applications the default value is false. ...
...user interface element should be "flashed" to get the user's attention when a download completes. Default value is 2. browser.download.manager.focusWhenStarting A boolean value that indicates whether or not to focus the Download Manager window when a download begins. In Firefox,Thunderbird and SeaMonkey the default value is false. In Other Applications the default value is true. browser.download.manager.quitBehavior Indicates what should happen to in-progress downloads if the application is quit while they're ongoing. 0 indicates that the downloads should be paused and resumed automatically the next time Firefox is run; 1 indicates that the downloads should be paused but will not automatically resume when the application is restarted; and 2 indicates that th...
...And 5 more matches
Elements - Archive of obsolete content
A XBL binding can add anonymous content, fields, properties, methods, and event handlers to HTML/XML elements. A single XBL binding can be attached to an element by using style sheets or by scripting. (See bug 83830 for <table> specifics). CSS: div { -moz-binding: url(myBinding.xml#default); } DOM: elementReference.
...may also use a number of HTML, MathML and SVG tags. The 'display' attribute does not work unless the extends attribute is set, see bug bug 119389. In that case, put the value of the display attribute into the extends attribute. inheritstyle - The inheritstyle attribute indicates whether style rules from the document will affect anonymous content generated by the XBL binding. If this attribute is true, styles from the document will also be applied to the XBL generated anonymous content. content <!ELEMENT content ANY> <!ATTLIST content id ID #IMPLIED > A binding can specify new content that is placed inside the bound element. Although you can see this content on screen as if it was directly in the file, this content is anonymous and is hidden from the normal DO...
...D #IMPLIED > The body element represents the implementation of its corresponding method. Its contents are the script that is executed when the method is invoked. id - The id attribute is a document-unique identifier. 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. It is useful as a simple holder for a value. The field element must have content which is code that determines the initial value of the field. The field tag must be inside the implementation tag. id - The id attribute is a document-unique identifier. name - The name of the field. Th...
...And 5 more matches
tab - Archive of obsolete content
Archive › Mozilla › XUL › tab
ey, accessibleType, command, control, crop, disabled, image, label, linkedPanel, selected, tabIndex, value Examples (example needed) Attributes accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. afterselected Type: boolean This is set to true if the tab is immediately after the currently selected tab. This is automatically set when needed and you shouldn't adjust it manually. This is primarily useful for themes so that they can adjust the appearance of the area around the selected tab. beforeselected Type: boolean This is set to true if the tab is immediately before the currently selected tab. This is set automatically set wh...
... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...th an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. fadein Type: boolean This attribute is set to true if the tab is fading in or out. This typically means that the tab is in the process of appearing or disappearing. first-tab Type: boolean This attribute will be set to true for the first tab. This attribute should not be set manually, but is useful in a theme if the first tab should be styled differently. image Type: URI The URI of the image to appear on the element. If this ...
...And 5 more matches
wizard - Archive of obsolete content
"checkCode();"/> </wizardpage> <wizardpage> <label value="That is the correct secret code."/> </wizardpage> </wizard> Attributes activetitlebarcolor Type: color string Specify background color of the window's titlebar when it is active (foreground). Moreover this hides separator between titlebar and window contents. This only affects Mac OS X. firstpage Type: boolean true if the wizard is on the first page. inactivetitlebarcolor Type: color string Specify background color of the window's titlebar when it is inactive (background). Moreover this hides separator between titlebar and window contents. This affects only on Mac OS X. lastpage Type: boolean True if the wizard is on the last page. Use the canCancel property to indicate to the user (by...
...ute to group windows of the same type together. Values for window type as found on MXR: http://mxr.mozilla.org/mozilla-release/search?string=windowtype navigator:browser - Looks like if window has gBrowser it has this window type devtools:scratchpad - Scratchpad windows navigator:view-source - The view source windows Properties canAdvance Type: boolean This property is set to true if the user can press the Next button to go to the next page. If this property is false, the user cannot navigate to the next page. Set this property to true to indicate that the user can go to the next page. Set to false to disallow moving to the next page. This has the effect of enabling or disabling the Next button, or, on the last page of the wizard, the Finish button. canRewind Type: ...
...Set to false to disallow moving to the previous page. ...
...And 5 more matches
MathML Torture Test
> </td></tr> <tr> <td>6</td> <td><img src="https://udn.realityripple.com/samples/76/5ce9da68c6.png" width="220" height="138" alt="TeXbook, 17.5-17.6" /></td> <td> <math display="block"> <mrow> <msub> <mi>a</mi> <mn>0</mn> </msub> <mo>+</mo> <mfrac> <mn>1</mn> <mstyle displaystyle="true" scriptlevel="0"> <msub> <mi>a</mi> <mn>1</mn> </msub> <mo>+</mo> <mfrac> <mn>1</mn> <mstyle displaystyle="true" scriptlevel="0"> <msub> <mi>a</mi> <mn>2</mn> </msub> <mo>+</mo> ...
...> </msub> <mo>+</mo> <mfrac> <mn>1</mn> <mstyle displaystyle="true" scriptlevel="0"> <msub> <mi>a</mi> <mn>2</mn> </msub> <mo>+</mo> <mfrac> <mn>1</mn> <mstyle displaystyle="true" scriptlevel="0"> <msub> <mi>a</mi> <mn>3</mn> </msub> <mo>+</mo> <mfrac> <mn>1</mn> <mstyle displaystyle="true" scriptlevel="0"> <msub> <mi>a</mi> ...
... <mo>/</mo> <mn>?</mn> </mrow> </mfrac> </mrow> </math> </td></tr> <tr> <td>6</td> <td> <math dir="rtl" display="block"> <mrow> <msub> <mi>&#x1EE00;</mi> <mn>?</mn> </msub> <mo>+</mo> <mfrac> <mn>?</mn> <mstyle displaystyle="true" scriptlevel="0"> <msub> <mi>&#x1EE00;</mi> <mn>?</mn> </msub> <mo>+</mo> <mfrac> <mn>?</mn> <mstyle displaystyle="true" scriptlevel="0"> <msub> <mi>&#x1EE00;</mi> <mn>?</mn> </msub> <m...
...And 5 more matches
JS::Value
etails or upon the size of JS::Value. ...
...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(double) string val.isString()...
... JS::SymbolValue(JS::Symbol*) val.toSymbol() val.setSymbol(JS::Symbol &) Numbers are stored in a JS::Value either as a double or as an int32_t. The different representations are visible using the separate int32/double methods but do not affect observable semantics (ignoring performance). The number mutators attempt to use int32_t representation for compatible input values, returning true when int32 could be used and false when double representation was required. Any double value may be stored in a JS::Value, in one of these two representations. The only exception is that only a single NaN value can be represented. (Note that both -0 and +0 are allowed, and the latter may sometimes be stored using the int32_t representation.) JS::Value further provides these methods combining var...
...And 5 more matches
nsIHttpChannel
utes Attribute Type Description allowPipelining boolean This attribute is a hint to the channel to indicate whether or not the underlying HTTP transaction should be allowed to be pipelined with other transactions. This should be set to false, for example, if the application knows that the corresponding document is likely to be very large. This attribute is true by default, though other factors may prevent pipelining. This attribute may only be set before the channel is opened. Exceptions thrown NS_ERROR_FAILURE If set after the channel has been opened. redirectionLimit unsigned long This attribute specifies the number of redirects this channel is allowed to make. If zero, the channel will fail to red...
...ta for a "POST" or "PUT" request can be configured via nsIUploadChannel. However, after setting the upload data, it may be necessary to set the request method explicitly. The documentation for nsIUploadChannel has further details. Exceptions thrown NS_ERROR_IN_PROGRESS If set after the channel has been opened. requestSucceeded boolean Returns true if the HTTP response code indicates success. The value of nsIRequest.status() will be NS_OK even when processing a 404 File Not Found response because such a response may include a message body that (in some cases) should be shown to the user. Use this attribute to distinguish server error pages from normal pages, instead of comparing the response status manually against the set of valid response...
... getResponseHeader( in ACString header ); Parameters header The case-insensitive name of the response header to query (For example "Set-Cookie"). Return value The value of the response header. Exceptions thrown NS_ERROR_NOT_AVAILABLE If called before the response has been received (before onStartRequest()) or if the header is not set in the response. ...
...And 5 more matches
Debugger - Firefox Developer Tools
essor Properties of the Debugger Prototype Object A Debugger instance inherits the following accessor properties from its prototype: enabled A boolean value indicating whether this Debugger instance's handlers, breakpoints, and the like are currently enabled. It is an accessor property with a getter and setter: assigning to it enables or disables this Debugger instance; reading it produces true if the instance is enabled, or false otherwise. This property is initially true in a freshly created Debugger instance. This property gives debugger code a single point of control for disentangling itself from the debuggee, regardless of what sort of events or handlers or "points" we add to the interface. allowUnobservedAsmJS A boolean value indicating whether asm.js code running inside t...
...indicating whether asm.js code running inside this Debugger instance's debuggee globals is invisible to Debugger API handlers and breakpoints. Setting this to false inhibits the ahead-of-time asm.js compiler and forces asm.js code to run as normal JavaScript. This is an accessor property with a getter and setter. It is initially false in a freshly created Debugger instance. Setting this flag to true is intended for uses of subsystems of the Debugger API (e.g, Debugger.Source) for purposes other than step debugging a target JavaScript program. allowWasmBinarySource A boolean value indicating whether WebAssembly sources will be available in binary form. The WebAssembly text generation will be disabled. collectCoverageInfo A boolean value indicating whether code coverage should be enabl...
...xt generation will be disabled. collectCoverageInfo A boolean value indicating whether code coverage should be enabled inside each debuggee of this Debugger instance. Changing this flag value will recompile all JIT code to add or remove code coverage instrumentation. Changing this flag when any frame of the debuggee is currently active on the stack will produce an exception. Setting this to true enables code coverage instrumentation, which can be accessed via the Debugger.Script getOffsetsCoverage function. In some cases, the code coverage might expose information which pre-date the modification of this flag. Code coverage reports are monotone, thus one can take a snapshot when the Debugger is enabled, and output the difference. Setting this to false prevents this Debugger instance fro...
...And 5 more matches
DevTools API - Firefox Developer Tools
. Return value: A Promise that is fulfilled once the operation has finished. switchHost(hostType) Switches the location of the toolbox Parameters: hostType {Toolbox.HostType} - The type of the new host. Return value: A Promise that is fulfilled once the new host is ready. reloadTarget(force) Reloads the current target of the toolbox. Parameters: force {Boolean} - If true the target is shift-reloaded i.e. the cache is bypassed during the reload. zoomIn() Increases the zoom level of the Toolbox document. zoomOut() Decreases the zoom level of the Toolbox document. zoomReset() Resets the zoom level of the Toolbox document. setZoom(value) Set the zoom level to an arbitrary value. Parameters: value {Number} - The zoom level such as 1.2. d...
...rence name that controls the visiblity of the tool. Default: devtools.{id}.enabled icon String, optional. An URL for the icon to show in the toolbox tab. If undefined the label should be defined. highlightedicon String, optional. An URL for an icon that is to be used when the tool is highlighted (see e.g. paused, inactive debugger). Default: {icon} iconOnly Boolean, optional. If true, the label won't be shown in the tool's tab. Default: false invertIconForLightTheme Boolean, optional. If true the colors of the icon will be inverted for the light theme. Default: false key String, optional. The key used for keyboard shortcut. Either key or keycode value. modifiers String, optional. Modifiers for the keyboard shortcut. preventClosingOnKey Boolean, optiona...
...Default: false menuLabel String, optional. A label for the Developer Menu item. ...
...And 5 more matches
MediaTrackSupportedConstraints - Web APIs
ignoring a constraint and a constraint being accepted. An actual constraint set is described using an object based on the MediaTrackConstraints dictionary. To learn more about how constraints work, see Capabilities, constraints, and settings. Properties Some combination--but not necessarily all--of the following properties will exist on the object. ...
...the MediaTrackConstraints dictionary. To learn more about how constraints work, see Capabilities, constraints, and settings. Properties Some combination--but not necessarily all--of the following properties will exist on the object. autoGainControl A Boolean whose value is true if the autoGainControl constraint is supported in the current environment. width A Boolean value whose value is true if the width constraint is supported in the current environment. ...
..., and settings. Properties Some combination--but not necessarily all--of the following properties will exist on the object. autoGainControl A Boolean whose value is true if the autoGainControl constraint is supported in the current environment. width A Boolean value whose value is true if the width constraint is supported in the current environment. height A Boolean value whose value is true if the height constraint is supported in the current environment. aspectRatio A Boolean value whose value is true if the aspectRatio constraint is supported in the current environment. ...
...And 5 more matches
Slottable - Web APIs
Web › API › Slottable
To change preferences in Firefox, visit about:config.IE No supp...
...-- 63Disabled Disabled From version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config. No support ? -- 59Disabled Disabled Until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to true) and the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 40Safari Full support 10.1WebView Android Full support ...
...To change preferences in Firefox, visit about:config.Opera Android ...
...And 5 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
specification that occur during these still somewhat experimental days of the WebXR specification. Options This example has a number of options you can configure by adjusting the values of constants before you load it in the browser. 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. yRotationDegreesPerSecond The number of degrees to rotate around the Y axis each second. zRo...
...RotationDegreesPerSecond The number of degrees of rotation to apply around the X axis per second. yRotationDegreesPerSecond The number of degrees to rotate around the Y axis each second. zRotationDegreesPerSecond The number of degrees per second to rotate around the Z axis. enableRotation A Boolean indicating whether or not to enable the rotation of the cube at all. ...
... per second. yRotationDegreesPerSecond The number of degrees to rotate around the Y axis each second. zRotationDegreesPerSecond The number of degrees per second to rotate around the Z axis. enableRotation A Boolean indicating whether or not to enable the rotation of the cube at all. allowMouseRotation If true, you can use the mouse to pitch and yaw the view angle. allowKeyboardMotion If true, the W, A, S, and D keys move the viewer forward, left, backward, and to the right, while the up and down arrow keys move up and down. If false, only XR device changes to the view are permitted. enableForcePolyfill If this Boolean is true, the example will attempt to use the WebXR polyfill even if the browser actually has support for WebXR. If false, the polyfill is only used if the browser doe...
...And 5 more matches
Background audio processing using AudioWorklet - Web APIs
e modules from over the network or even the user's local disk. Basic code framework The barest framework of an audio processor class looks like this: class MyAudioProcessor extends AudioWorkletProcessor { constructor() { super(); } process(inputList, outputList, parameters) { /* using the inputs (or not, as needed), write the output into each of the outputs */ return true; } }; registerProcessor("my-audio-processor", MyAudioProcessor); After the implementation of the processor comes a call to the global function registerProcessor(), which is only available within the scope of the audio context's AudioWorklet, which is the invoker of the processor script as a result of your call to audioWorklet.addModule(). This call to registerProcessor() registers your class...
...The same check is performed when determining how many channels to process in the current input; we only process as many as there are room for in the destination output. This avoids ...
...Each sample is added to the corresponding sample in the output buffer, with a simple code fragment in place to prevent the samples from exceeding the legal range of -1.0 to 1.0 by capping the values; there are other ways to avoid clipping that are perhaps less prone to distortion, ...
...And 5 more matches
ARIA: button role - Accessibility
n to inform users a button will launch a dialog is to append "..." (ellipsis) to the button's label, e.g., "Save as...". In addition to the ordinary button widget, role="button" should be included when creating a toggle button or menu button using a non button element. A toggle button is a two-state button that can be either off (not pressed) or on (pressed). The aria-pressed attribute values of true or false identify a button as a toggle button. A menu button is a button that controls a menu and has an aria-haspopup property attribute set to either menu or true. Associated ARIA roles, states, and properties aria-pressed Defines the button as a toggle button. The value of aria-pressed describes the state of the button. The values include aria-pressed="false" when a button is not currentl...
...If the attribute is omitted or set to its default value of aria-pressed="undefined", the element does not support being pressed. ...
... omitted or set to its default value of aria-pressed="undefined", the element does not support being pressed. aria-expanded If the button controls a grouping of other elements, the aria-expanded state indicates whether the controlled grouping is currently expanded or collapsed. If the button has aria-expanded="false" set, the grouping is not currently expanded; If the button has aria-expanded="true" set, it is currently expanded; if the button has aria-expanded="undefined" set or the attribute is ommitted, it is not expandable. Basic buttons Buttons should always have an accessible name. For most buttons, this name will be the same as the text inside the button. In some cases, for example buttons represented by icons, the accessible name may be provided from the aria-label or aria-labell...
...And 5 more matches
@supports - CSS: Cascading Style Sheets
Web › CSS › @supports
ition consists of one or more name-value pairs combined by conjunctions (and), disjunctions (or), and/or negations (not). Precedence of operators can be defined with parentheses. Declaration syntax The most basic supports condition is a simple declaration (a property name followed by a value, separated by a colon). The declaration must be surrounded by parentheses. The following example returns true if the browser's transform-origin property considers 5% 5% valid: @supports (transform-origin: 5% 5%) {} Function syntax The second basic supports condition is a supports function, the syntax for these is supported by all browsers, but the functions themselves are still being standardized. selector() Tests if the browser supports the tested selector syntax. The following example returns tr...
...ctions themselves are still being standardized. selector() Tests if the browser supports the tested selector syntax. The following example returns true if the browser supports the child combinator: @supports selector(A > B) {} The not operator The not operator can precede any expression to create a new expression, resulting in the negation of the original one. The following example returns true if the browser's transform-origin property doesn't consider 10em 10em 10em valid: @supports not (transform-origin: 10em 10em 10em) {} As with any operator, the not operator can be applied to a declaration of any complexity. The following examples are both valid: @supports not (not (transform-origin: 2px)) {} @supports (display: grid) and (not (display: inline-grid)) {} Note: There is no need...
... not (not (transform-origin: 2px)) {} @supports (display: grid) and (not (display: inline-grid)) {} Note: There is no need to enclose the not operator between two parentheses at the top level. To combine it with other operators, like and and or, the parentheses are required. The and operator The and operator creates a new expression from the conjunction of two shorter expressions. It returns true only if both of the shorter expressions are also true. The following example returns true if and only if the two shorter expressions are simultaneously true: @supports (display: table-cell) and (display: list-item) {} Multiple conjunctions can be juxtaposed without the need of more parentheses. The following are both equivalent: @supports (display: table-cell) and (display: list-item) and (dis...
...And 5 more matches
Enumerability and ownership of properties - JavaScript
Enumerable properties show up in for...in loops unless the property's key is a Symbol. Ownership of properties is determined by whether the property belongs to the object directly and not to its prototype chain. Properties of an object can also be retrieved in total. There are a number of built-in means of detecting, iterating/enumerating, and retrieving object properties, with the chart showing below which are available. ...
... all cases, but useful for a quick demonstration. ...
...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); }, getPrototypeN...
...And 5 more matches
Array.prototype.some() - JavaScript
ndex[, array]])[, thisArg]) Parameters callback A function to test for each element, taking three arguments: element The current element being processed in the array. indexOptional The index of the current element being processed in the array. arrayOptional The array some() was called upon. thisArgOptional A value to use as this when executing callback. Return value true if the callback function returns a truthy value for at least one element in the array. Otherwise, false. Description The some() method executes the callback function once for each element present in the array until it finds the one where callback returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true. Otherwis...
...type.some = function(fun, thisArg) { 'use strict'; if (this == null) { throw new TypeError('Array.prototype.some called on null or undefined'); } if (typeof fun !== 'function') { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisArg, t[i], i, t)) { return true; } } return false; }; } Examples Testing value of array elements The following example tests whether any element in the array is bigger than 10. function isBiggerThan10(element, index, array) { return element > 10; } [2, 5, 8, 1, 4].some(isBiggerThan10); // false [12, 5, 8, 1, 4].some(isBiggerThan10); // true Testing array elements using arrow functions Arrow functions...
...ment in the array is bigger than 10. function isBiggerThan10(element, index, array) { return element > 10; } [2, 5, 8, 1, 4].some(isBiggerThan10); // false [12, 5, 8, 1, 4].some(isBiggerThan10); // true Testing array elements using arrow functions Arrow functions provide a shorter syntax for the same test. ...
...And 5 more matches
Object.getOwnPropertyDescriptor() - JavaScript
ription of a property. A property in JavaScript consists of either a string-valued name or a Symbol and a property descriptor. Further information about property descriptor types and their attributes can be found in Object.defineProperty(). A property descriptor is a record with some of the following attributes: value The value associated with the property (data descriptors only). ...
...y (data descriptors only). writable true if and only if the value associated with the property may be changed (data descriptors only). get A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). set A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Examples Using Object.getOwnPropertyDescriptor var o, d; o = { get foo() { return 17; } }; d = Object.getOwnPropertyDescriptor(o, 'foo'); /...
...this property descriptor may be changed and if the property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. ...
...And 5 more matches
Object.is() - JavaScript
re the same value. Syntax Object.is(value1, value2); Parameters value1 The first value to compare. value2 The second value to compare. Return value A Boolean indicating whether or not the two arguments are the same value. Description Object.is() determines whether two values are the same value. 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 sid...
... (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. This is also not the same as being equal according to the === operator. The === operator (and the == operator as well) treats the number values -0 and +0 as equal and treats Number.NaN as not equal to NaN. Polyfill if (!Object.is) { Object.is = function(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e...
...as equal and treats Number.NaN as not equal to NaN. ...
...And 5 more matches
isNaN() - JavaScript
The isNaN() function determines whether a value is NaN or not. Note, coercion inside the isNaN function has interesting rules; you may alternatively want to use Number.isNaN(), as defined in ECMAScript 2015. Syntax isNaN(value) Parameters value The value to be tested. 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. Hence, the necessity of an isNaN function. Origin of NaN values NaN values are generated when arithmetic operations result in undefined or unrepresentable values. Such values do not necessar...
...sNaN, the expression (x != x) is a more reliable way to test whether variable x is NaN or not, as the result is not subject to the false positives that make isNaN unreliable. ...
... x) is a more reliable way to test whether variable x is NaN or not, as the result is not subject to the false positives that make isNaN unreliable. ...
...And 5 more matches
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. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x <= y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
... to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x <= y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
...mples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x <= y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
...And 5 more matches
Logical AND (&&) - JavaScript
The logical AND (&&) operator (logical conjunction) for a set of operands is true if and only if all of its operands are true. It is typically used with Boolean (logical) values. When it is, it returns a Boolean value. However, the && operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax expr1 && expr2 Description If expr1 can be converted to true, returns expr2; else, returns expr1. If a value can be converted to true, the value is so-called truthy. If ...
...it means that the expr part above is not evaluated, hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. ...
...('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). true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply Examples Using AND The following code shows examples of the && (logical AND) operator. ...
...And 5 more matches
Autoplay guide for media and Web Audio APIs - Web media technologies
API From the user's perspective, a web page or app that spontaneously starts making noise without warning can be jarring, inconvenient, or off-putting. Because of that, browsers generally only allow autoplay to occur successfully under specific circumstances. ...
... from being allowed, we'll look at how your web site or app can automatically play media upon page load, how to detect when autoplay fails to occur, and tips for coping when autoplay is denied by the browser. The autoplay attribute The simplest way to automatically play content is to add the autoplay attribute to your <audio> or <video> element. ...
...look at how your web site or app can automatically play media upon page load, how to detect when autoplay fails to occur, and tips for coping when autoplay is denied by the browser. The autoplay attribute The simplest way to automatically play content is to add the autoplay attribute to your <audio> or <video> element. ...
...And 5 more matches
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
This article is aimed at presenting alternatives to common eval uses in add-ons and other Javascript code. Add-on authors are strongly encouraged to update their code to eliminate all instances of eval, no matter if the add-on is to be hosted in the Mozilla Add-ons Gallery or not. ...
...andbox (which is complicated!), but if you have a choice, just avoid JSONP altogether! Passing around functions/code as strings Often you'll want to pass functions or code to other functions, most notoriously setTimeout and addEventListener. Often this is done passing around strings. ...
... thumb, just don't pass code around as strings and execute it by calling eval, setTimeout and friends. Alternative: Use (anonymous) functions You can always create a small anonymous function to pass around instead. Closures will ensure the code is still valid, even if your outer function already returned from execution. ...
...And 4 more matches
Tabbed browser - Archive of obsolete content
See tabbrowser for getBrowserForTab(). Note that the code above does not work inside of the Electrolysis (e10s) enabled tabs. Opening a URL in the correct window/tab There are methods available in chrome://browser/content/utilityOverlay.js that make it easy to open URL in tabs such as openUILinkIn and openUILink. openU...
...nd which hotkeys (ex: Ctrl) are being held. The code given is for a menuitem, but will work equally well for other XUL elements. This will only work in an overlay of browser.xul. 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.addTa...
...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. ...
...And 4 more matches
MenuItems - Archive of obsolete content
If the checkbox is on, the toolbar is shown, whereas if the checkbox is off, the toolbar is not shown. The user can select the menu item to switch the toolbar visibility. This type of menuitem can be created by using the type attribute and setting it to the value "checkbox". <menu label="View" accesskey="V"> <menupopup> <menuitem label="Show Toolbar" accesskey="T" type="checkbox" checked="true"/> <menuitem label="Show Status Bar" accesskey="S" type="checkbox"/> </menupopup> </menu> Both menuitems are of the checkbox type. The first menuitem is checked by default, as indicated by the checked attribute set to the value true. The second menuitem is not checked by default. When the user activates the menuitem, the command event gets fired. From within a command listener, you can ...
...t need to update the checked attribute as the menuitem will update this automatically before the command event is fired. Note that the checked state is updated before the command event fires, so if you use the menuitem's checked attribute within the command listener, it will already be in the new state. <script> function changeToolbarState(event) { if (event.target.getAttribute("checked") == "true") showToolbar(); else hideToolbar(); } </script> ... <menuitem label="Show Toolbar" accesskey="T" type="checkbox" oncommand="changeToolbarState();"/> In this example, we show the toolbar when the menuitem is checked and hide the toolbar otherwise. There may be times when you do not want the checkbox state to be updated automatically when the menuitem is activated. This can ...
...is to simply reverse the checkbox state again. As this can be more complicated, it is also possible to use the autocheck attribute to disable this behavior. 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. <script> function changeToolbarState(event) { if (event.target.getAttribute("checked") == "true") hideToolbar(); event.target.removeAttribute("checked"); } else { if (!showToolbar()) return; event.target.setAttribute("checked", "true"); } } </script> ... <menuitem label="Show Toolbar" accesskey="T" type="checkbox" autocheck="false" oncommand="changeToolbarState();"/> This version of the changeToolbarState function changes the checked attribute itself.
...And 4 more matches
More Tree Features - Archive of obsolete content
element can contain either single rows which are declared with the treerow element or a set of rows which are declared with the treechildren element. There are two other things you need to do to make sure the hierarchy works properly. First, you need to mark the treeitem element that has children as a container. You do this by adding the container attribute to it as follows: <treeitem container="true" /> This allows the user to click on the row that corresponds to the treeitem to expand and collapse the inner rows. You can have the child rows initially displayed by adding the open attribute. When the user expands and collapses the parent, the view's toggleOpenState function will be called to toggle the item between open and closed. For a content tree view, this will set the open attribute to...
...ppear before the cells in that column to indicate the cells that can be expanded. In addition, child rows are indented. Note also that the user cannot hide the primary column using the drop down to the right of the columns. ...
... the user cannot hide the primary column using the drop down to the right of the columns. ...
...And 4 more matches
panel - Archive of obsolete content
Archive › Mozilla › XUL › panel
ew Message"/> </hbox> </vbox> </hbox> </panel> <description value="6 New Messages" popup="thepanel"/> Attributes backdrag Type: boolean Setting the backdrag attribute on a XUL panel lets the user move the panel by clicking and dragging anywhere on its background area. ...
...If set to false, the rollup event is not consumed. This attribute should be used instead of setConsumeRollupEvent. fadeType: one of the values belowThe fade attribute, which may only be used with arrow panels, lets you set up a panel that will automatically fade away after a short time. The default is none. ...
...r window), so the panel extends past the left of the anchor, and the arrow slides towards the middle of the panel such that it is still aligned with the anchor. Without flip="slide", the panel would have had its width truncated and the panel would not extend to the left of the anchor. ignorekeys Type: boolean If false, the default value, the Escape key may be used to close the panel. If true, the Escape key cannot be used to close the panel. label Type: string For panels with titlebars, the label on the titlebar. left Type: integer Overrides the horizontal position of the popup specified by the showPopup method. level Type: one of the values below Specifies whether the panel appears on top of all windows, or just on top of the window the panel is in. If ...
...And 4 more matches
window - Archive of obsolete content
activetitlebarcolor Type: color string Specify background color of the window's titlebar when it is active (foreground). Moreover this hides separator between titlebar and window contents. This only affects Mac OS X. chromemargin Type: margin string Controls the amount of chrome that should be visible on each side of the wind...
...ay be -1 to use the default margin for that side on the current platform, 0 to have no system border (that is, to extend the client area to the edge of the window), or a value greater than zero to indicate how much less than the default default width you wish the margin on that side to be. If this value turns out to be less than 0, 0 is used. ...
...e: boolean Set this attribute to true to disable chrome in the window. This is used to hide chrome when showing in-browser UI such as the about:addons page, and causes the toolbars to be hidden, with only the tab strip (and, if currently displayed, the add-on bar) left showing. Note: This has no effect if the tabs on top preference is turned off. disablefastfindType: booleanPut disablefastfind="true" on the root element of a XUL document, which is intended to be loaded in a tab, to disable the find bar for the tab with this document. This is used to prevent the find bar from being displayed when it's not supported by the content (such as in the Add-ons manager tab). ...
...And 4 more matches
Old Proxy API - Archive of obsolete content
ng the value") receiver.name = val (if receiver inherits from a proxy and does not override name) set: function(receiver, name, val) -> boolean function(receiver, name, val) { var desc = this.getOwnPropertyDescriptor(name); if (desc) { if ('writable' in desc) { if (desc.writable) { desc.value = val; this.defineProperty(name, desc); return true; } else { return false; } } else { // accessor if (desc.set) { desc.set.call(receiver, val); return true; } else { return false; } } } desc = this.getPropertyDescriptor(name); if (desc) { if ('writable' in desc) { if (desc.writable) { // fall through } else { return false; } } els...
... { 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. for(prop in proxy){...} enumerate: function() -> String Array function() { return this.getPropertyNames().fil...
...ins the object identity of the proxy, upholding the illusion that the proxy "becomes" the object). Object.getPrototypeOf(proxy) returns the prototype with which proxy was initialized for an object proxy, and returns Function.prototype for a function proxy. typeof typeof anObjectProxy === "object" typeof aFunctionProxy === "function" instanceof anObjectProxy instanceof C === true if and only if the prototype with which anObjectProxy was initialized equals or inherits from C.prototype aFunctionProxy instanceof Function === true Common mistakes and misunderstanding When starting using proxies, there are often a few beginners' mistakes and misunderstandings: Not implementing all traps. Proxies are, by default, "semanticless" objects. If a trap isn't implemented...
...And 4 more matches
Using the Right Markup to Invoke Plugins - Archive of obsolete content
This is, in fact, the Unique Identifier of Macromedia's Flash plugin, and developers are expected to know such Unique Identifiers in order to invoke the compo...
...ers support the use of the object element along with a MIME type. Here is an example of this usage, once again for the Macromedia Flash plugin: <object type="application/x-shockwave-flash" data="javascript-to-flash.swf" width="366" height="142" id="myFlash"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> <p>You need Flash -- get the latest version from <a href= "http://www.macromedia.com/downloads/">here.</a></p> </object> In the above example, application/x-shockwave-flash is the Flash MIME type, and will invoke the Netscape-specific Flash architecture in Mozilla-based browsers. The data attribute points to the SWF file to play, and the configuration parameters (the param elements)...
... MIME type for Flash: <!-- Usage Will Not Work As Intended --> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="366" height="142" id="myFlash"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> <object type="application/x-shockwave-flash" data="javascript-to-flash.swf" width="366" height="142" id="myFlashNSCP"> <param name="movie" value="javascript-to-flash.swf" /> <param name="quality" value="high" /> <param name="swliveconnect" value="true" /> <p>You need Flash -- get the latest version from <a href="http://www.macromedia.com/downloads/"> here.</a></p> </...
...And 4 more matches
Desktop gamepad controls - Game development
tons) { for(var b=0; b<controller.buttons.length; b++) { if(controller.buttons[b].pressed) { buttonsPressed.push(b); } } } } We first reset the buttonsPressed array to get it ready to store the latest info we'll write to it from the current frame. ...
...e buttons are available we loop through them; if the pressed property is set to true, then we add them to the buttonsPressed array for later processing. Next, we'll consider the gamepadButtonPressedHandler() function: function gamepadButtonPressedHandler(button) { var press = false; for(var i=0; i<buttonsPressed.length; i++) { if(buttonsPressed[i] == button) { press = true; } } return press; } The function takes a button as a parameter; in the loop it checks if the given button's number is among the currently pressed buttons available in the buttonsPressed array. If it is, then the function returns true; false otherwise. Next, in the draw() function we do two things -- execute the gamepadUpdateHandler() function to get the current state of pressed...
...information about it in our object, and the axes property stores the array containing the values signifying the amount an axis is pressed in the x and y directions, represented by a float in the (-1, 1) range. ...
...And 4 more matches
2D maze game with device orientation - Game development
We're loading two images first that will be used later in the Preload state to show the prog...
...We're loading two images first that will be used later in the Preload state to show the progress of loading all the other assets. The create fun...
... Left absolute position on Canvas in pixels. Name of the image asset the button is using. Function that will be executed when someone clicks the button. The execution c...
...And 4 more matches
Looping code - Learn web development
n programming speak. Let's consider the case of a farmer that is making sure he has enough food to feed his family for the week. He might use the following loop to achieve this: A loop usually has one or more of the following features: A counter, which is initialized with a certain value -- this is the starting point of the loop ("Start: I have no food", above). 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. This is illustrated by "Have I got enough food?", above. Let's say he needs 10 portions of food to feed his family. An iterator, which generally increments the counter by a small amount on each successive loop, until the condition is no longer true. We haven't explicitly illus...
...amount on each successive loop, until the condition is no longer true. We haven't explicitly illustrated this above, but we could think about the farmer being able to collect say 2 portions of food per hour. After each hour, the amount of food he has collected is incremented by two, and he checks whether he has enough food. If he has reached 10 portions (the point where the condition is no longer true, so the loop exits), he can stop collecting and go home. In pseudocode, this would look something like the following: loop(food = 0; foodNeeded = 10) { if (food >= foodNeeded) { exit loop; // We have enough food; let's go home } else { food += 2; // Spend an hour collecting 2 more food // loop will then run again } } So the amount of food needed is set at 10, and the amo...
...oop should stop looping. This is generally an expression featuring a comparison operator, a test to see if the exit condition has been met. A final-expression -- this is always evaluated (or run) each time the loop has gone through a full iteration. It usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the point where the condition is no longer true. Some curly braces that contain a block of code -- this code will be run each time the loop iterates. Let's look at a real example so we can visualize what these do more clearly. const cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin']; let info = 'My cats are called '; const para = document.querySelector('p'); for (let i = 0; i < cats.length; i++) { info += cats[i] + ', '; } para.
...And 4 more matches
A first splash into JavaScript - Learn web development
'red'; if(userGuess < randomNumber) { lowOrHi.textContent = 'Last guess was too low!' ; } else if(userGuess > randomNumber) { lowOrHi.textContent = 'Last guess was too high!'; } } guessCount++; guessField.value = ''; } guessSubmit.addEventListener('click', checkGuess); function setGameOver() { guessField.disabled = true; guessSubmit.disabled = true; resetButton = document.createElement('button'); resetButton.textContent = 'Start new game'; document.body.append(resetButton); resetButton.addEventListener('click', resetGame); } function resetGame() { guessCount = 1; const resetParas = document.querySelectorAll('.resultParas p'); for(let i = 0 ; i < resetParas...
... = 'Bingo'; name; let hello = ' says hello!'; hello; let greeting = name + hello; greeting; There are also some shortcut operators available, called augmented assignment operators. ...
...esult, 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. ...
...And 4 more matches
JS::CompileOptions
e(const char *t) CompileOptions &setIntroductionInfo(const char *introducerFn, const char *intro, unsigned line, JSScript *script, uint32_t offset) CompileOptions &maybeMakeStrictMode(bool strict) Properties Properties of JS::ReadOnlyCompileOptions Name Type Description version JSVersion Version of the script. ...
...oductionInfo(const char *introducerFn, const char *intro, unsigned line, JSScript *script, uint32_t offset) CompileOptions &maybeMakeStrictMode(bool strict) Properties Properties of JS::ReadOnlyCompileOptions Name Type Description version JSVersion Version of the script. versionSet bool true if version is set. utf8 bool true if the character set of the source code is UTF-8. lineno unsigned Line number of the first line of the source code (1-origin). column unsigned Column number of the first line of the source code (0-origin). compileAndGo bool true if the code is going to be evaluated soon after the compile (e.g., false for Function constructor and event handler). ...
... of the source code is UTF-8. lineno unsigned Line number of the first line of the source code (1-origin). column unsigned Column number of the first line of the source code (0-origin). compileAndGo bool true if the code is going to be evaluated soon after the compile (e.g., false for Function constructor and event handler). forEval bool true if the code is for eval(). noScriptRval bool false means that the caller needs the return value of the script. ...
...And 4 more matches
Index
Mozilla › Tech › XPCOM › Index
by their names. 23 Components.interfacesByID XPCOM:Language Bindings, XPConnect Components.interfacesByID is a read-only array of classes indexed by IID. 24 Components.isSuccessCode XPCOM, XPCOM:Language Bindings, XPConnect Determines whether a given XPCOM return code (that is, an nsresult value) indicates the success or failure of an operation, returning true or false respectively. 25 Components.lastResult XPCOM:Language Bindings, XPConnect No summary! 26 Components.manager XPCOM:Language Bindings, XPConnect Components.manager is a convenience reflection of the global native component manager service. The scriptable methods on the nsIComponentManager interface can be called directly on this object. 27 ...
...rbird The folder classes all implement the nsIMsgFolder interface. There are currently three folder classes - nsLocalMailFolder, nsImapMailFolder, and nsNewsFolder. They all inherit from nsMsgDBFolder, which implements a lot of the core functionality. RSS feeds are implemented by nsLocalMailFolder. ...
...ogether. Last version set on this context. Scripts typically select this with the "language" attribute. See the VERSION_* consts on jsdIDebuggerService. Unique tag among all valid jsdIContext objects, useful as a hash key. Private data for this context, if it is an nsISupports, |null| otherwise. Retrieve the underlying context wrapped by this jsdIContext. Top of the scope chain for this context. |true| if this context should be allowed to run scripts, |false| otherwise. This attribute is only valid for contexts which implement nsIScriptContext. Setting or getting this attribute on any other context will throw a NS_ERROR_NO_INTERFACE exception. Stack frame objects. These are only valid inside the jsdIExecutionHook which gave it to you. After you return from that handler the bottom frame, and an...
...And 4 more matches
nsISelectionController
Read only. Constants Selection constants Constant Gecko version Description 1.7 - 1.9 1.9.1 - 1.9.2 2.0 SELECTION_NONE 0 SELECTION_NORMAL 1...
...Read only. ...
...isibility() Checks if textnode and offsets are actually rendered in the current precontext. boolean checkVisibility( in nsIDOMNode node, in short startOffset, in short endOffset ); Parameters node nsIDOMNode to test. startOffset Offset in DOM to first char of textnode to test. endOffset Offset in DOM to last char of textnode to test. Return value true if visible, false if not. completeMove() Will move page view to the top or bottom of the document this will also have the effect of collapsing the selection if the extend = PR_FALSE the "point" of selection that is extended is considered the "focus" point, or the last point adjusted by the selection. void completeMove( in boolean forward, in boolean extend ); Parameters forward ...
...And 4 more matches
nsIZipWriter
aZipEntry, in boolean aQueue); Attributes Attribute Type Description comment ACString Gets or sets the comment associated with the currently open Zip file. Exceptions thrown NS_ERROR_NOT_INITIALIZED If no zip file has been opened. file nsIFile The Zip file being written to. Read only. inQueue boolean true if operations are being performed in the background queue, or false if background operations are not in progress. Read only. Constants Constant Value Description COMPRESSION_NONE 0 Do not compress the file. COMPRESSION_FASTEST 1 Use the fastest compression method when adding the file to the archive. COMPRESSION_DEFAULT 6 Use the ...
... aZipEntry The path of the file entry to add to the Zip file. This is the path it will be located at within the Zip file. Note: You must use forward slashes ('/') in the path. aModTime The modification time of the entry in microseconds. aCompression One of the compression constants, indicating the compression method to use. aChannel The channel from which to get the data. aQueue If true, the operation is queued for later execution. If false, the operation is performed immediately. Will be performed when processQueue() is called. Exceptions thrown NS_ERROR_NOT_INITIALIZED No Zip file is open. NS_ERROR_FILE_ALREADY_EXISTS The specified path already exists in the Zip file. NS_ERROR_IN_PROGRESS The Zip writer is already performing another operation. addEntryDirectory() ...
...throw any errors but if this was an xpi file, firefox would not be able to read it properly. zw.addEntryFile(saveInZipAs, Ci.nsIZipWriter.COMPRESSION_NONE, fileToAddToZip, false); This example creates a folder in the zip called "sub folder" and then adds "C:\add this file.txt" to it, but it will be called "blah.txt". aModTime The modification time of the entry in microseconds. aQueue If true, the operation is queued for later execution. If false, the operation is performed immediately. Will be performed when processQueue() is called. Exceptions thrown NS_ERROR_NOT_INITIALIZED No Zip file is open. NS_ERROR_FILE_ALREADY_EXISTS The specified path already exists in the Zip file. NS_ERROR_IN_PROGRESS The Zip writer is already performing another operation. addEntryFile() Adds ...
...And 4 more matches
Advanced animations - Web APIs
e need a drawing context first. To draw the ball, we will create a ball object which contains properties and a draw() method to paint it on the canvas. var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var ball = { x: 100, y: 100, radius: 25, color: 'blue', draw: function() { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); } }; ball.draw(); Nothing special here, the ball is actually a simple circle and gets drawn with the help of the arc() method. Adding velocity Now that we have a ball, we are ready to add a basic animation like we have learned in the last chapter of this tutorial. Again, window.requestAnimationFrame() helps us to control...
... adding a velocity vector to the position. For each frame, we also clear the canvas to remove old circles from prior frames. ...
...e into the canvas to start the animation. ...
...And 4 more matches
FileSystemFlags - Web APIs
The FileSystemFlags dictionary defines a set of values which are used when specifying option flags when calling certain methods in the File and Directory Entries API. ...
...ues which are used when specifying option flags when calling certain methods in the File and Directory Entries API. Methods which accept an options parameter of this type may specify zero or more of these flags as fields in an object, like this: dataDirectoryEntry.getDirectory("Workspace", { create: true }, function(entry) { }); Here, we see that the create property is provided, with a value of true, indicating that the directory should be created if it's not already there. ...
...Instead, it must be possible for it to be created newly at call time. ...
...And 4 more matches
URLSearchParams - Web APIs
g suitable for use in a URL. URLSearchParams.values() Returns an iterator allowing iteration through all values of the key/value pairs contained in this object. Examples var paramsString = "q=URLUtils.searchParams&topic=api"; var searchParams = new URLSearchParams(paramsString); //Iterate the search parameters. ...
...e for use in a URL. URLSearchParams.values() Returns an iterator allowing iteration through all values of the key/value pairs contained in this object. Examples var paramsString = "q=URLUtils.searchParams&topic=api"; var searchParams = new URLSearchParams(paramsString); //Iterate the search parameters. ...
... Returns an iterator allowing iteration through all values of the key/value pairs contained in this object. Examples var paramsString = "q=URLUtils.searchParams&topic=api"; var searchParams = new URLSearchParams(paramsString); //Iterate the search parameters. ...
...And 4 more matches
WebGLRenderingContext.vertexAttribPointer() - Web APIs
gl.FLOAT: 32-bit IEEE floating point number When using a WebGL 2 context, the following values are available additionally: gl.HALF_FLOAT: 16-bit IEEE floating point number normalized A GLboolean specifying whether integer data values should be normalized into a certain range when being cast to a float. For types gl.BYTE and gl.SHORT, normalizes the values to [-1, 1] if true. For types gl.UNSIGNED_BYTE and gl.UNSIGNED_SHORT, normalizes the values to [0, 1] if true. For types gl.FLOAT and gl.HALF_FLOAT, this parameter has no effect. stride A GLsizei specifying the offset in bytes between the beginning of consecutive vertex attributes. Cannot be larger than 255. If stride is 0, the attribute is assumed to be tightly packed, that is, the attributes are not int...
... For example, the following vertex: { "position": [1.0, 2.0, 1.5], "normal": [1.0, 0.0, 0.0], "texCoord": [0.5, 0.25] } Will be stored in the array buffer as follows: 00 00 80 3F 00 00 00 40 00 00 0C 3F 7F 00 00 00 7F FF 3F FF Creating the array buffer First, we dynamically create the array buffer from JSON data using a DataView. Note the use of true because WebGL expects our data to be in little-endian. //load geometry with fetch() and Response.json() const response = await fetch('assets/geometry.json'); const vertices = await response.json(); //Create array buffer const buffer = new ArrayBuffer(20 * vertices.length); //Fill array buffer const dv = new DataView(buffer); for (let i = 0; i < vertices.length; i++) { dv.setFloat32(20 * i, ve...
...our data to be in little-endian. ...
...And 4 more matches
Using the aria-hidden attribute - Accessibility
This technique demonstrates how to use the aria-hidden attribute. The aria-hidden attribute can either expose or hide non-interactive content from the accessibility API. Description Adding aria-hidden="true" to an element removes that element and all of its children from the accessibility tree. This can improve the experience for assistive technology users by hiding: purely decorative content, such as icons or images duplicated content, such as repeated text offscreen or collapsed content, such as menus According to the fourth rule of ARIA, aria-hidden="true" should not be used on a focusable element. Additionally, since this attribute is inherited by an element's children, it should not be added onto the parent or ancestor of a focusable element. Using aria-hidden="false" will...
...content, such as menus According to the fourth rule of ARIA, aria-hidden="true" should not be used on a focusable element. Additionally, since this attribute is inherited by an element's children, it should not be added onto the parent or ancestor of a focusable element. Using aria-hidden="false" will not re-expose the element to assistive technology if any of its parents specify aria-hidden="true". WAI-ARIA Authoring Practices 1.1 notes that aria-hidden="false" currently behaves inconsistently across browsers. ...
...ute is inherited by an element's children, it should not be added onto the parent or ancestor of a focusable element. Using aria-hidden="false" will not re-expose the element to assistive technology if any of its parents specify aria-hidden="true". WAI-ARIA Authoring Practices 1.1 notes that aria-hidden="false" currently behaves inconsistently across browsers. ...
...And 4 more matches
ARIA: tab role - Accessibility
The common user experience pattern is a group of visual tabs above, or to the side of, a content area, and selecting a different tab changes the content and makes the selected tab more prominent than the other tabs. ...
... They should contain the aria-controls property identifying an element with the tabpanel role. When an element with the tabpanel role has focus, or a child of it has focus, that indicates that the connected element with the tab role is the active tab in a tablist. 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. Associated Roles and Attributes aria-selected boolean aria-controls id of element with tabpanel role id content Keyboard interaction Key Action Tab When focus ...
...ombines the role tab with tablist and elements with tabpanel to create an interactive group of tabbed content. Here we are enclosing our group of content in a div, with our tablist having an aria-label to label it for assistive technology. Each tab is a button with the attributes previously mentioned. The first tab has tabindex=0 on it, which we will later change to whatever tab has aria-selected=true. All of the tabpanel elements have tabindex=0 to make them tabbable, and all but the currently active one have the hidden attribute, which we will change with JavaScript. There is some basic styling applied that restyles the buttons and changes the z-index to of tab elements to give the illusion of it connecting to the tabpanel for active elements, and the illusion that inactive elements are behi...
...And 4 more matches
ARIA: listbox role - Accessibility
item is focused within the list, it gets announced next, followed by an indication of the item's position with the list if the screen reader supports this. As focus moves within the list, the screen reader announces the relevant items. Associated ARIA roles, states, and properties Associated Roles option One or more nested options are required. All selected options have aria-selected set to true. All options that are not selected have aria-selected set to false. If an option is not selectable, omit the aria-selected. list A section containing listitem elements States and Properties aria-activedescendant Holds the id string of the currently active element within the listbox. If that's an option element, then that would be the id of the most recently interacted with option, regar...
...to false. If an option is not selectable, omit the aria-selected. list A section containing listitem elements States and Properties aria-activedescendant Holds the id string of the currently active element within the listbox. If that's an option element, then that would be the id of the most recently interacted with option, regardless of whether that option has an aria-selected value of true or not. Takes the value of only one id, even in a multiselectable listbox. If the id does not refer to a DOM descendant of the listbox, then that id must be included among the IDs in the aria-owns attrubute. aria-owns This is a space-separated list of element IDs which are not DOM child elements of the listbox. IDs listed here cannot also be listed in aria-owns attributes of any other element...
... in a multiselectable listbox. If the id does not refer to a DOM descendant of the listbox, then that id must be included among the IDs in the aria-owns attrubute. aria-owns This is a space-separated list of element IDs which are not DOM child elements of the listbox. IDs listed here cannot also be listed in aria-owns attributes of any other elements. aria-multiselectable Include and set to true if the user can select more than one option. If set to true, every selectable option should have an aria-selected attribute included and set to true or false. Options which are not selectable should not have the aria-selected attribute. 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. aria-require...
...And 4 more matches
ARIA: textbox role - Accessibility
ement has the textbox role, the browser sends an accessible textbox event to assistive technologies, which can then notify the user about it. The default is a single line input, in which Return or Enter submits the form; in this case, it is preferable to use an HTML <input> with type="text". ...
...form; in this case, it is preferable to use an HTML <input> with type="text". To create a multi-line text box which supports line breaks, as in an HTML <textarea>, set aria-multiline="true". Including the HTML contenteditable attribute ensures the text node is editable. <!-- Simple text input field --> <div id="txtboxLabel">Enter your five-digit zipcode</div> <div role="textbox" contenteditable="true" aria-placeholder="5-digit zipcode" aria-labelledby="txtboxLabel"></div> <!-- Multi-line text area --> <div id="txtboxMultilineLabel">Enter the tags for the article</div> <div role="textbox" contenteditable="true" aria-multiline="true" aria-labelledby="txtboxMultilineLabel" aria-required="true"></div> Semantic elements are more concise and require no JavaScript to support textbox features. ...
...ire no JavaScript to support textbox features. <label for="txtbox">Enter your five-digit zipcode</label> <input type="text" placeholder="5-digit zipcode" id="txtbox"/> <!-- Multi-line text area --> <label for="txtboxMultiline">Enter the tags for the article</label> <textarea id="txtboxMultiline" required></textarea> Where a text field is read-only, indicated this by setting aria-readonly="true" on the element. Associated ARIA properties aria-activedescendent attribute Taking as it's value the ID of is either a descendant of the element with DOM focus or is a logical descendant as indicated by the aria-owns attribute, it indicates when that element has focus, when it is part of a composite widget such as a combobox. For example, in a combobox, focus may remain on the textbox whi...
...And 4 more matches
Alerts - Accessibility
at least a first name or a surname. The form First, please read about the aria-required technique if you have not done so, as this technique expands upon that. ...
...his technique expands upon that. ...
...Each field has a set of criteria which must be met in order to pass validation. In order to sim...
...And 4 more matches
Border-radius generator - CSS: Cascading Style Sheets
ction InputSliderManager() { var subscribers = {}; var sliders = []; var InputComponent = function InputComponent(obj) { var input = document.createElement('input'); input.setAttribute('type', 'text'); input.addEventListener('click', function(e) { this.select(); }); input.addEventListener('change', function(e) { var value = parseInt(e.target.value); if (isNaN(value) === true) setValue(obj.topic, obj.value); else setValue(obj.topic, value); }); subscribe(obj.topic, function(value) { input.value = value + obj.unit; }); return input; } var SliderComponent = function SliderComponent(obj, sign) { var slider = document.createElement('div'); var startX = null; var start_value = 0; slider.addEventListener("click", function(e) { setValue...
...unsubscribe } })(); /** * UI-ButtonManager */ var ButtonManager = (function CheckBoxManager() { var subscribers = []; var buttons = []; var CheckBox = function CheckBox(node) { var topic = node.getAttribute('data-topic'); var state = node.getAttribute('data-state'); var name = node.getAttribute('data-label'); var align = node.getAttribute('data-text-on'); state = (state === "true"); var checkbox = document.createElement("input"); var label = document.createElement("label"); var id = 'checkbox-' + topic; checkbox.id = id; checkbox.setAttribute('type', 'checkbox'); checkbox.checked = state; label.setAttribute('for', id); if (name) { label.className = 'text'; if (align) label.className += ' ' + align; label.textContent = name; } node.appe...
...var PreviewMouseTracking = (function Drag() { var active = false; var lastX = 0; var lastY = 0; var subscribers = []; var init = function init(id) { var elem = getElemById(id); elem.addEventListener('mousedown', dragStart, false); document.addEventListener('mouseup', dragEnd, false); } var dragStart = function dragStart(e) { if (e.button !== 0) return; active = true; lastX = e.clientX; lastY = e.clientY; document.addEventListener('mousemove', mouseDrag, false); } var dragEnd = function dragEnd(e) { if (e.button !== 0) return; if (active === true) { active = false; document.removeEventListener('mousemove', mouseDrag, false); } } var mouseDrag = function mouseDrag(e) { notify(e.clientX - lastX, e.clientY - lastY); ...
...And 4 more matches
Audio and Video Delivery - Developer guides
More options for Fallbacks. JavaScript Audio var myAudio = document.createElement('audio'); if (myAudio.canPlayType('audio/mpeg')) { myAudio.setAttribute('src','audiofile.mp3'); } else if (myAudio.canPlayType('audio/ogg')...
... More options for Fallbacks. ...
...yVideo.width = 480; myVideo.height = 320; We set the source of the video depending on the type of video file the browser supports we then set the width and height of the video. ...
...And 4 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
Web › HTTP › CORS
for server developers discussing cross-origin sharing from a server perspective (with PHP code snippets) is supplementary reading. What requests use CORS? This cross-origin sharing standard can enable cross-site HTTP requests for: Invocations of the XMLHttpRequest or Fetch APIs, as discussed above. Web Fonts (for cross-domain font usage in @font-face within CSS), so that servers can deploy TrueType fonts that can only be cross-site loaded and used by web sites that are permitted to do so. WebGL textures. Images/video frames drawn to a canvas using drawImage(). CSS Shapes from images. This article is a general discussion of Cross-Origin Resource Sharing and includes a discussion of the necessary HTTP headers. Functional overview The Cross-Origin Resource Sharing standard works by ...
...ed. In this example, content originally loaded from http://foo.example makes a simple GET request to a resource on http://bar.other which sets Cookies. Content on foo.example might contain JavaScript like this: const invocation = new XMLHttpRequest(); const url = 'http://bar.other/resources/credentialed-content/'; function callOtherDomain() { if (invocation) { invocation.open('GET', url, true); invocation.withCredentials = true; invocation.onreadystatechange = handler; invocation.send(); } } Line 7 shows the flag on XMLHttpRequest that has to be set in order to make the invocation with Cookies, namely the withCredentials boolean value. By default, the invocation is made without Cookies. Since this is a simple GET request, it is not preflighted, but the browser will reje...
...ge = handler; invocation.send(); } } Line 7 shows the flag on XMLHttpRequest that has to be set in order to make the invocation with Cookies, namely the withCredentials boolean value. By default, the invocation is made without Cookies. Since this is a simple GET request, it is not preflighted, but the browser will reject any response that does not have the Access-Control-Allow-Credentials: true header, and not make the response available to the invoking web content. Here is a sample exchange between client and server: GET /resources/credentialed-content/ HTTP/1.1 Host: bar.other User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-E...
...And 4 more matches
Iterators and generators - JavaScript
for...of function* and Generator yield and yield* Iterators In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. Specifically, an iterator is any object which implements the Iterator protocol by having a next() method that returns an object with two properties: value The next value in the iteration sequence. done This is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator's return value. Once created, an iterator object can be iterated explicitly by repeatedly calling next(). Iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. After a terminating value has been yielded additional calls to ne...
...y been consumed. If value is present alongside done, it is the iterator's return value. Once created, an iterator object can be iterated explicitly by repeatedly calling next(). Iterating over an iterator is said to consume the iterator, because it is generally only possible to do once. After a terminating value has been yielded additional calls to next() should simply continue to return {done: true}. The most common iterator in JavaScript is the Array iterator, which simply returns each value in the associated array in sequence. While it is easy to imagine that all iterators could be expressed as arrays, this is not true. Arrays must be allocated in their entirety, but iterators are consumed only as necessary. Because of this, iterators can express sequences of unlimited size, such as the...
...ty, 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.next(); } console.log("Iterated over sequence of size: ", result.value); // [5 numbers returned, that took interval in between: 0 to 10] Note: It is not possible ...
...And 4 more matches
Loops and iteration - JavaScript
ion]) statement When a for loop executes, the following occurs: The initializing expression initialExpression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables. The conditionExpression expression is evaluated. If the value of conditionExpression is true, the loop statements execute. If the value of condition is false, the for loop terminates. (If the condition expression is omitted entirely, the condition is assumed to be true.) The statement executes. To execute multiple statements, use a block statement ({ ... }) to group those statements. If present, the update expression incrementExpression is executed. Control returns to Step 2. Exampl...
...electForm.musicTypes)); }); </script> do...while statement The do...while statement repeats until a specified condition evaluates to false. A do...while statement looks as follows: do statement while (condition); statement is always executed once before the condition is checked. (To execute multiple statements, use a block statement ({ ... }) to group those statements.) If condition is true, the statement executes again. At the end of every execution, the condition is checked. When the condition is false, execution stops, and control passes to the statement following do...while. Example In the following example, the do loop iterates at least once and reiterates until i is no longer less than 5. let i = 0; do { i += 1; console.log(i); } while (i < 5); while statement A while...
...hecked. When the condition is false, execution stops, and control passes to the statement following do...while. Example In the following example, the do loop iterates at least once and reiterates until i is no longer less than 5. let i = 0; do { i += 1; console.log(i); } while (i < 5); while statement A while statement executes its statements as long as a specified condition evaluates to true. A while statement looks as follows: while (condition) statement If the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop. The condition test occurs before statement in the loop is executed. If the condition returns true, statement is executed and the condition is tested again. If the condition returns false, execution ...
...And 4 more matches
Boolean - JavaScript
an object wrapper for a boolean value. Description The value passed as the first parameter is converted to a boolean value, if necessary. 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. ...
... The value passed as the first parameter is converted to a boolean value, if necessary. 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. ...
...e first parameter is converted to a boolean value, if necessary. 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 4 more matches
NaN - JavaScript
ration (e.g. "foo"/3) Examples Testing against NaN NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself. ...
...ples Testing against NaN NaN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself. ...
...aN compares unequal (via ==, !=, ===, and !==) to any other value -- including to another NaN value. Use Number.isNaN() or isNaN() to most clearly determine whether a value is NaN. Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself. ...
...And 4 more matches
Object.create() - JavaScript
operties. Exceptions The proto parameter has to be either null or an Object excluding primitive wrapper objects. If proto is neither of these a TypeError is thrown. Custom and Null objects A new object created from a completely custom object (especially one created from the null object, which is basically a custom object with NO members) can behave in unexpected ways. This is especially true when debugging, since common object-property converting/detecting utility functions may generate errors, or simply lose information (especially if using silent error-traps that ignore errors). For example, here are two objects: oco = Object.create( {} ); // create a normal object ocn = Object.create( null ); // create a "null" object > console.log(oco) // {} -- Seems normal > console.log(ocn)...
...For example: A simple common debugging function: // display top-level property name:value pairs of given object function Sho...
...missing object-method directly from the standard-object does NOT work: ocn = Object.create( null ); // create "null" object (same as before) ocn.toString = Object.toString; // since new object lacks method then try assigning it directly from standard-object > ocn.toString // shows "toString() { [native code] }" -- missing method seems to be there now > ocn.toString == Object.toString // shows "true" -- method seems to be same as the standard object-method > ocn.toString() // error: Function.prototype.toString requires that 'this' be a Function Adding the missing object-method directly to new object's "prototype" does not work either, since the new object does not have a real prototype (which is really the cause of ALL these problems) and one cannot be directly added: ocn = Object.crea...
...And 4 more matches
Object.isFrozen() - JavaScript
properties (that is, properties which are not accessor properties with getter or setter components) are non-writable. Examples Using Object.isFrozen // A new object is extensible, so it is not frozen. Object.isFrozen({}); // === false // An empty object which is not extensible // is vacuously frozen. var vacuouslyFrozen = Object.preventExtensions({}); Object.isFrozen(vacuouslyFrozen); // === true // A new object with one property is also extensible, // ergo not 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 ob...
...ar 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. delete oneProp.p; Object.isFrozen(oneProp); // === true // A non-extensible object with a non-writable // but still configurable property is not frozen. var nonWritable = { e: 'plep' }; Object.preventExtensions(nonWritable); Object.defineProperty(nonWritable, 'e', { writable: false }); // make non-writable Object.isFrozen(nonWritable); // === false // Changing that property to non-configurable // then makes the object frozen. Object.defineProperty...
...table = { e: 'plep' }; Object.preventExtensions(nonWritable); Object.defineProperty(nonWritable, 'e', { writable: false }); // make non-writable Object.isFrozen(nonWritable); // === false // Changing that property to non-configurable // then makes the object frozen. Object.defineProperty(nonWritable, 'e', { configurable: false }); // make non-configurable Object.isFrozen(nonWritable); // === true // A non-extensible object with a non-configurable // but still writable property also isn't frozen. var nonConfigurable = { release: 'the kraken!' }; Object.preventExtensions(nonConfigurable); Object.defineProperty(nonConfigurable, 'release', { configurable: false }); Object.isFrozen(nonConfigurable); // === false // Changing that property to non-writable // then makes the object frozen. Obj...
...And 4 more matches
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. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x >= y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
...ples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x >= y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
...thub.com/mdn/interactive-examples and send us a pull request. Syntax x >= y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
...And 4 more matches
in operator - JavaScript
The in operator returns true if the specified property is in the specified object or its prototype chain. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax prop in object Parameters prop A string or symbol representing a property name or array index (non-symbols will be coerced to strings). object Object to check if it (or its prototype chain) contains the property with specified name (prop). Examples Basic usage The following examples show some uses of the in operator. ...
... prop A string or symbol representing a property name or array index (non-symbols will be coerced to strings). object Object to check if it (or its prototype chain) contains the property with specified name (prop). Examples Basic usage The following examples show some uses of the in operator. ...
...ting a property name or array index (non-symbols will be coerced to strings). object Object to check if it (or its prototype chain) contains the property with specified name (prop). Examples Basic usage The following examples show some uses of the in operator. ...
...And 4 more matches
Index - XPath
Web › XPath › Index
XPath This article seeks to document the difference between CSS Selectors and XPath for web developers to be able to better choose the right tool for the right job. 17 Functions Transforming_XML_with_XSLT, XPath, XPath_Reference, XSLT, XSLT_Reference No summary! 18 boolean XSLT, XSLT_Reference The boolean function evaluates an expression and returns true or false. 19 ceiling XSLT, XSLT_Reference The ceiling function evaluates a decimal number and returns the smallest integer greater than or equal to the decimal number. 20 choose Function, XPath, XSLT The choose function returns one of the specified objects based on a boolean parameter. 21 concat XSLT, XSLT_Reference The concat f...
...ose function returns one of the specified objects based on a boolean parameter. 21 concat XSLT, XSLT_Reference The concat function concatenates two or more strings and returns the resulting string. 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. 23 count XSLT, XSLT_Reference The count function counts the number of nodes in a node-set and returns an integer. 24 current XSLT, XSLT_Reference The current function can be used to get the context node in an XSLT instruction. 25 document XSLT, XSLT_Reference The document finds a node-set in an external document, or mult...
...rrent function can be used to get the context node in an XSLT instruction. 25 document XSLT, XSLT_Reference The document finds a node-set in an external document, or multiple external documents, and returns the resulting node-set. 26 element-available XSLT, XSLT_Reference The element-available function determines if an element is available and returns true or false. 27 false XSLT, XSLT_Reference The false function returns boolean false. 28 floor XSLT, XSLT_Reference The floor function evaluates a decimal number and returns the largest integer less than or equal to the decimal number. 29 format-number XSLT, XSLT_Reference The format-number function evaluates a number and returns a ...
...And 4 more matches
context-menu - Archive of obsolete content
rings. When matchPattern is an array, the context occurs when the menu is invoked on a page whose URL matches any of the patterns. These are the same match pattern strings that you use with the page-mod include property. Read more about patterns. PredicateContext(predicateFunction) predicateFunction is called when the menu is invoked, and the context occurs when the function returns a true value. The function is passed an object with properties describing the menu invocaton context. array An array of any of the other types. This context occurs when all contexts in the array occur. Menu items also have a context property that can be used to add and remove declarative contexts after construction. For example: var context = require("sdk/context-menu").SelectorConte...
... scripts. Like other APIs in the SDK, the context-menu API uses content scripts to let your add-on interact with pages in the browser. Each menu item you create in the top-level context menu can have a content script. A special event named "context" is emitted in your content scripts whenever the context menu is about to be shown. If you register a listener function for this event and it returns true, the menu item associated with the listener's content script is shown in the menu. For example, this item appears whenever the context menu is invoked on a page that contains at least one image: require("sdk/context-menu").Item({ label: "This Page Has Images", contentScript: 'self.on("context", function (node) {' + ' return !!document.querySelector("img");' + ...
...It will be executed the first time it is needed (i.e. when the context menu is first shown and all of the declarative contexts for your item are current) and then remains active until you destroy your context menu item or the page is unloaded. Handling menu item clicks In addition to ...
...And 3 more matches
HTML to DOM - Archive of obsolete content
k. Create your own function using unique name, ID, and so forth. ...
...tAttribute("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 page or frame if (doc.location.href == "about:blank" || doc.defaultView.frameElement) return; // do something with the DOM of doc ...
... Using a hidden XUL iframe (alternate example) Sometimes, a browser...
...And 3 more matches
Setting up an extension development environment - Archive of obsolete content
information about Mozilla preferences, refer to the mozillaZine article on "about:config". Tip: You can install either the Developer Profile or DevPrefs add-ons to handle setting these preferences automatically, and skip the rest of this section. DevPrefs can now be found at https://github.com/Noitidart/DevPrefs. maxVersion needs to be set in install.rdf javascript.options.showInConsole = true. Logs errors in chrome files to the Error Console. nglayout.debug.disable_xul_cache = true. Disables the XUL cache so that changes to windows and dialogs do not require a restart. This assumes you're using directories rather than JARs. Changes to XUL overlays will still require reloading of the document overlaid. browser.dom.window.dump.enabled = true. Enables the use of the dump() statement to...
...uire a restart. This assumes you're using directories rather than JARs. Changes to XUL overlays will still require reloading of the document overlaid. browser.dom.window.dump.enabled = true. Enables the use of the dump() statement to print to the standard console. See window.dump for more info. You can use nsIConsoleService instead of dump() from a privileged script. javascript.options.strict = true. Enables strict JavaScript warnings in the Error Console. Note that since many people have this setting turned off when developing, you will see lots of warnings for problems with their code in addition to warnings for your own extension. You can filter those with Console2. devtools.chrome.enabled = true. This enables to run JavaScript code snippets in the chrome context of the Scratchpad from t...
...d off when developing, you will see lots of warnings for problems with their code in addition to warnings for your own extension. You can filter those with Console2. devtools.chrome.enabled = true. This enables to run JavaScript code snippets in the chrome context of the Scratchpad from the Tools menu. Don't forget to switch from content to browser as context. devtools.debugger.remote-enabled = true. This adds a "Browser Debugger" entry to the "Web Developer" submenu of the "Tools" menu. The Browser Debugger can be used to debug the JavaScript code of extensions. The devtools.chrome.enabled preference must also be set to true for the Browser Debugger to be enabled. devtools.debugger.prompt-connection = false. This prevents the Browser Debugger from prompting for connection permission every...
...And 3 more matches
Dehydra Object Reference - Archive of obsolete content
th the Dehydra objects is to print out the objects: Dehydra example code an online tool for pretty-printing dehydra data Understanding Properties Dehydra only sets properties that are applicable. For example, class types and typedefs are declared and will have a .loc property. Intrinsic types such as "int" are not declared and will not have a .loc. Dehydra only sets boolean flags when they are true. For example, a pointer type will have .isPointer == true, but a class type will not have an .isPointer property. Common Properties Property Type Description .loc location object Source location of a type or declaration. .attributes array of objects Attributes of the type or declaration. Each member of the array has the following properties: { name: string, value: string or number...
...ject Provides the object being dereferenced, in the AST system. Applicable when accessing member variables or nonstatic member functions of aggregate types, e.g. the "foo" variable would be a .fieldOf memberVar/Fn in foo->memberVar or foo->memberFn(). Note that when constructing the return value of a function (e.g. return T();), no container variable is available; in this case, .isReturn will be true (see Function Variable). Variables can identified by their DehydraDecl() prototype. Function Variable Function objects are an extension of Variable Objects. The following additional properties are available on functions: Property Type Description .isVirtual true or "pure" true for virtual methods, or "pure" for pure virtuals (e.g. virtual void foo() = 0;). .isConstructor boolean flag...
... Type Objects Dehydra provides detailed type objects. Dehydra Type objects use the DehydraType() prototype. ...
...And 3 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
you really do want to know the exact browser in use, such as when you need to work around a bug in a specific version of a specific browser. For all other purposes you should check for the feature you need rather than the browsers you think will support that feature. JavaScript also allows inline conditional statements, which can help with code readability: var foo = (condition) ? conditionIsTrue : conditionIsFalse; For example, to retrieve an element, you would use: function getElement(aID){ return (document.getElementById) ? document.getElementById(aID) : document.all[aID]); } Differences between Mozilla and Internet Explorer First, I'll discuss the differences in the way HTML behaves between Mozilla and Internet Explorer. Tooltips Legacy bro...
...ble 3 shows how the W3C standard and Mozilla manipulate content, all of which are methods of any DOM node. Table 3. Methods Mozilla uses to manipulate content Method Description appendChild( aNode ) Creates a new child node. Returns a reference to the new child node. cloneNode( aDeep ) Makes a copy of the node it is called on and returns the copy. If aDeep is true, it copies over the node's entire subtree. createElement( aTagName ) Creates and returns a new and parentless DOM node of the type specified by aTagName. createTextNode( aTextValue ) Creates and returns a new and parentless DOM textnode with the data value specified by aTextValue. insertBefore( aNewNode, aChildNode ) Inserts aNewNode before aChildNode, which mu...
...strict mode, Mozilla's parser will see the first <script> and parse until it finds a closing tag for it, which would be the first </script>. This is because the parser has no knowledge about JavaScript (or any other language) when in strict mode. In quirks mode, the parser is aware of JavaScript when parsing (which slows it down). Internet Explorer is always in quirks mode, as it does not support true XHTML. To make this work in strict mode in Mozilla, separate the string into two parts: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ... <script> document.write("<script type='text\/javascript'>alert('Hello');</" + "script>") </script> Debug JavaScript Mozilla provides several ways to debug JavaScript-related issu...
...And 3 more matches
Supporting private browsing mode - Archive of obsolete content
nt for this session } Turning private browsing on and off Extensions can turn private browsing mode on and off by manipulating the value of the privateBrowsingEnabled attribute. var pbs = Components.classes["@mozilla.org/privatebrowsing;1"] .getService(Components.interfaces.nsIPrivateBrowsingService); var oldPrivateMode = pbs.privateBrowsingMode; pbs.privateBrowsingEnabled = true; /* this is all private */ pbs.privateBrowsingEnabled = oldPrivateMode; In this example, we save the current state of the private browsing mode setting in the oldPrivateMode variable, then turn on private browsing by setting its value to true. From that point until we restore the original value of the private browsing mode setting, things are done privately. This allows us to, for example, w...
...ct registers listeners for private browsing mode changes. This handles interacting with the private browsing service so you don't have to. ...
...browsing;1"] .getService(Components.interfaces.nsIPrivateBrowsingService); this._inPrivateBrowsing = pbs.privateBrowsingEnabled; } catch(ex) { // ignore exceptions in older versions of Firefox } }, observe : function (aSubject, aTopic, aData) { if (aTopic == "private-browsing") { if (aData == "enter") { this._inPrivateBrowsing = true; if (this.watcher && "onEnterPrivateBrowsing" in this._watcher) { this.watcher.onEnterPrivateBrowsing(); } } else if (aData == "exit") { this._inPrivateBrowsing = false; if (this.watcher && "onExitPrivateBrowsing" in this._watcher) { this.watcher.onExitPrivateBrowsing(); } } } else if (aTopic == "q...
...And 3 more matches
Building accessible custom components in XUL - Archive of obsolete content
nto the spreadsheet), we need to programmatically reset the focus to the previously focused cell. This is handled in the spreadsheet_focus function, which is registered as a handler for the focus event. ...
... the previously focused cell. This is handled in the spreadsheet_focus function, which is registered as a handler for the focus event. ...
...t cell, assistive technologies track the focus change and know which cell has received focus. <caption>Cells really get focus</caption> Clicking a row or column headers also changes the focus properly. <caption>Cells really get focus</caption> Further reading Key-navigable custom DHTML widgets on mozilla.org Adding Keyboard Navigation Download stage-4.zip install stage-4.xpi True accessibility requires complete keyboard navigability. We've already added the spreadsheet itself to the tab order, but that was only the first half. The second half is navigating between the cells and headers within the spreadsheet. As I mentioned in the previous section, we don't want to make every cell and header focusable. Other compound controls such as lists and treeviews support two-phased...
...And 3 more matches
OpenClose - Archive of obsolete content
d and closed by a script. Opening Menus Menus will display themselves automatically when needed without extra work. For instance, a menu's popup will open when the menu label is clicked, and a submenu will open when the mouse is hovered over the parent menu element. However, there may be situations when you wish to open a menu manually. The menu element has an open property which may be set to true to open the menu, or false to close the menu. A simple example: somemenu.open = true; This single line of code will open a menu referenced by the variable 'somemenu'. Note that the open property applies to the menu or button, not to the menupopup. Here is a complete example which uses a button to open a menu: <button label="Open Menu" oncommand="document.getElementById('editMenu').ope...
...open the menu, or false to close the menu. A simple example: somemenu.open = true; This single line of code will open a menu referenced by the variable 'somemenu'. Note that the open property applies to the menu or button, not to the menupopup. Here is a complete example which uses a button to open a menu: <button label="Open Menu" oncommand="document.getElementById('editMenu').open = true;"/> <menu id="editMenu" label="Edit"> <menupopup> <menuitem label="Cut"/> <menuitem label="Copy"/> <menuitem label="Paste"/> </menupopup> </menu> This technique may be used for both menupopups that use the menu tag, the button tag and the toolbarbutton tag. For menupopups attached to other elements using the popup or context attributes, see Opening a Popup below. As with other...
... These are situations when the popuphiding or popuphidden events may not fire as the element the events would be fired on are no longer available. If you need to perform uninitialization that would be done during these events, this could be done during an unload event. Testing Menu Open State To check if a menu is open, check the state of the menu's open property. If the open property is set to true, then the menu is open, otherwise the menu is closed. var open = somemenu.open; Opening a Popup For opening menupopups that use the menu tag, the button tag and the toolbarbutton tag, see Opening Menus above. Popups attached using the popup attribute will be opened when the user clicks the mouse with the left mouse button. There isn't a means of replicating this action with the keyboard, so ...
...And 3 more matches
Input Controls - Archive of obsolete content
y attributes, the textbox element creates a box in which the user can enter text. Textboxes accept many of the same attributes as HTML input controls. The following are some of them: id A unique identifier so that you can identify the textbox. class The style class of the textbox. value If you want the textbox to have default text, supply it with the value attribute. disabled Set to true to have text entry disabled. textbox.type You can set this attribute to the special value password to create a textbox that hides what it types. This is usually used for password entry fields. maxlength The maximum number of characters that the textbox allows. Note that while in HTML, several different kinds of fields can be created with the input element, in XUL there are separate elemen...
...tbox id="some-password" type="password" maxlength="8"/> Multiline textbox The textbox examples above will create text inputs that can only be used for entering one line of text. HTML also has a textarea element for creating a larger text entry area. In XUL, you can use the textbox element for this purpose as well -- two separate elements are not necessary. If you set the multiline attribute to true, the text entry field will display multiple rows. Example 2 : Source View <textbox multiline="true" value="This is some text that could wrap onto multiple lines."/> Like the HTML textarea, you can use the rows and cols attributes to set the size. This should be set to the number of rows and columns of characters to display. Our find files example Let's add a search entry field to ...
...ns of buttons. The checkbox element is used for options that can be enabled or disabled. Radio buttons can be used for a similar purpose when there are a set of them and only one can be selected at once. You can use most of the same attributes on checkboxes and radio buttons as with buttons. The example below shows some simple checkboxes and radio buttons. <checkbox id="case-sensitive" checked="true" label="Case sensitive"/> <radio id="orange" label="Orange"/> <radio id="violet" selected="true" label="Violet"/> <radio id="yellow" label="Yellow"/> The first line creates a simple checkbox. When the user clicks the checkbox, it switches between checked and unchecked. The checked attribute can be used to indicate the default state. You should set this to either true or false. The label attribu...
...And 3 more matches
XUL Questions and Answers - Archive of obsolete content
g 321172) When loading an XSLT stylesheet into an XML I get the error: "Error loading stylesheet: An XSLT stylesheet load was blocked for security reasons." That error is from a security check that has been put up to safeguard against cross-site-scripting attacks. A scheme is in development to allow servers to open up their site for cross-site access, but that's not yet done. hidechrome="true" doesn't work on a Mac? Unfortunately, no simple solution to this was posted. A workaround is to open the content in a new window using "window.open" and send titlebar="no" as one of the flags in the 3rd argument. Is it possible to have checkbox support for multi column lists? The current issue is a person exploring if it is possible to have checkbox support for multi column lists. The follo...
...tml="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> <listbox rows="4"> <listhead> <listheader label="multi-column"/> </listhead> <listcols> <listcol flex="1"/> </listcols> <listitem> <listcell type="checkbox" value="1" label="vghkvghk"/> </listitem> <listitem> <listcell type="checkbox" value="2" label="vghjkvk" checked="true"/> </listitem> <listitem> <listcell type="checkbox" value="3" label="hukfzgjcfj" disabled="true"/> </listitem> </listbox> <listbox rows="4"> <listhead> <listheader label="single-column"/> </listhead> <listitem type="checkbox" value="1" label="vghkvghk"/> <listitem type="checkbox" value="2" label="vghjkvk" checked="true"/> <listitem type="checkbox" value="3" label="...
...If user wants checkbox support for multicolumn lists, then they will have to implement one. ...
...And 3 more matches
XUL element attributes - Archive of obsolete content
center The elements are centered horizontally. right The elements are aligned on their right edges. The pack attribute is related to the alignment but is used to specify the position in the opposite direction. You can also specify the value of align using the style property -moz-box-align. allowevents Type: boolean If true, events are passed to children of the element. Otherwise, events are passed to the element only. allownegativeassertions Type: boolean Valid on any element that has a datasources attribute. When multiple datasources are used, one may override an assertion from another. This attribute, if true, which is the default, allows a datasource to negate an earlier assertion. class Typ...
... which is the default, allows a datasource to negate an earlier assertion. class Type: string The style class of the element. Multiple classes may be specified by separating them with spaces. coalesceduplicatearcs Type: boolean Valid on any element that has a datasources attribute. When multiple datasources are used, one may override an assertion from another. This attribute, if true, which is the default, allows a datasource to negate an earlier assertion. collapsed Type: boolean If true, then the element is collapsed and does not appear. It is equivalent to setting the CSS visibility property to collapse. container Type: boolean Set to true if the element is to act as a container which can have child elements. This would be used for folders. This will be...
...placed left to right or top to bottom in the order they appear in the XUL code. reverse For scales, the scale's values are ordered from right to left (for horizontal scales) or from bottom to top (for vertical scales). For other elements, they are placed right to left or bottom to top. This is reverse of the order in which they appear in the XUL code. empty Type: boolean Set to true if the element is a container that contains no children. This will be set by the template builder as needed. equalsize Type: one of the values below This attribute can be used to make the children of the element equal in size. always For a horizontally oriented element, this will make all of its children have the width of the widest child. For a vertically oriented element, this wi...
...And 3 more matches
Accessibility/XUL Accessibility Reference - Archive of obsolete content
I don't see a means of accessing a popup brought up via the popup attribute. Using context="popupId" allows access via Shift+F10 on Windows and Linux. ...
...p attribute. Using context="popupId" allows access via Shift+F10 on Windows and Linux. ...
...any, unpredictable issues with XUL inside of the iframe. Okay to use HTML inside of tabbrowser. See browser element for more info. ...
...And 3 more matches
menulist - Archive of obsolete content
nd the displayed text is larger than this maximum width, you may be able to use the max-width CSS property (or the maxwidth attribute) to override this size. For example, for a menuitem in a menu you can add the following CSS rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disableautoselect Type: boolean If this attribute is true or omitted, the selected item on the menu will update to match what the user entered in the textbox. If the text does not match any of the items in the list, the menu selection is cleared. If this attribute is false, the selection is never updated to match the text box. This attribute applies only to editable menulists. disabled Type: boolean Indicates whether the element is disabled or n...
.... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
... attribute, as it may need to update additional state. editable Type: boolean Indicates that the value of the menulist can be modified by typing directly into the value field. This is rendered as a textbox with a drop-down arrow beside it. The user may enter text into the textbox or select one of the choices by clicking from the drop-down. focused Type: boolean This attribute is true if the element is focused. image Type: URI The URI of the image to appear on the element. If this attribute is empty or left out, no image appears. The position of the image is determined by the dir and orient attributes. label Type: string The label that will appear on the element. If this is left out, no text appears. For an editable menuitem element the value of this attri...
...And 3 more matches
tabbrowser - Archive of obsolete content
contentcon...
... contentcontextmenu Type: id The id of a menupopup element serving as the context menu for the content area in the tabbrowser. ...
...refox Type: script code This script will be called when the new tab button is clicked. tabmodalPromptShowing Type: integer The number of tab modal prompts currently attached to the current tab. Properties browsers Type: nodelist of browser elements Holds a list of the browser elements inside the tabbrowser. canGoBack Type: boolean This read-only property is true if there is a page to go back to in the session history and the Back button should be enabled. canGoForward Type: boolean This read-only property is true if there is a page to go forward to in the session history and the Forward button should be enabled. contentDocument Type: document This read-only property contains the document object in the element. conten...
...And 3 more matches
XForms Input Element - Archive of obsolete content
of simple text into an instance node. Allows for free-form data entry (xhtml/xul). Characteristics A text field is presented to the user when there is no type given for the bound node or a type is specified that is not handled by one of the other widgets (as documented below). analogous widgets are <xhtml:input type="text"/> and <xul:textbox/> Specific handling of attributes incremental - if "true", the bound instance node will be updated on each character typed by the user. 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). Characteristics used when the instance n...
...If "false" then the instance node will be updated when the checkbox loses the focus. labelposition - a Mozilla XForms extension in the namespace http://www.mozilla.org/projects/xfor...009/extensions. ...
...r to a combobox. It consists of a text field for direct user input next to a button that when activated will 'drop down' a calender widget that the user can also interact with (xhtml/xul). Characteristics used when the instance node is of type xsd:date or a type derived from it. will not work with xsd:dateTime (behavior defaults to text input). Specific handling of attributes incremental - if "true", the bound instance node will be updated on each character typed by the user or when the user clicks on a date from the calendar widget. If "false" or the incremental attribute is omitted on this element then the bound instance node will be updated when the control loses focus. calendar A form author may notice a xforms input element represented by a calendar widget in the Mozilla XForms proces...
...And 3 more matches
Implementing controls using the Gamepad API - Game development
ddisconnected", gamepadAPI.disconnect); Due to security policy, you have to interact with the controller first while the page is visible for the event to fire. If the API worked without any interaction from the user it could be used to fingerprint them without their knowledge. Both functions are fairly simple: connect: function(evt) { gamepadAPI.controller = evt.gamepad; gamepadAPI.turbo = true; console.log('Gamepad connected.'); }, The connect() function takes the event as a parameter and assigns the gamepad object to the gamepadAPI.controller variable. We are using only one gamepad for this game, so it's a single object instead of an array of gamepads. We then set the turbo property to true. (We could use the gamepad.connected boolean for this purpose, but we wanted to have a separ...
...unction sets the gamepad.turbo property to false and removes the variable containing the gamepad object. Gamepad object There's lots of useful information contained in the gamepad object, with the states of buttons and axes being the most important: id: A string containing information about the controller. index: A unique indentifier for the connected device. connected: A boolean variable, true if the device is connected. mapping: The layout type of the buttons; standard is the only available option for now. axes: The state of each axis, represented by an array of floating-point values. buttons : The state of each button, represented by an array of GamepadButton objects containing pressed and value properties. The index variable is useful if we're connecting more than one controlle...
...is accepted. Without it you'd have to release the button and press it again to have the desired effect. 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... ...
...And 3 more matches
JavaScript basics - Learn web development
riables may hold values that have different data types: Variable Explanation Example String This is a sequence of text known as a string. To signify that the value is a string, enclose it in single quote marks. let myVariable = 'Bob'; Number This is a number. Numbers don't have quotes around them. let myVariable = 10; Boolean This is a True/False value. The words true and false are special keywords that don't need quote marks. let myVariable = true; Array This is a structure that allows you to store multiple values in a single reference. let myVariable = [1,'Bob','Steve',10]; Refer to each member of the array like this: myVariable[0], myVariable[1], etc. Object This can be anything. Everything i...
...ello ' + 'world!'; Subtraction, Multiplication, Division These do what you'd expect them to do in basic math. -, *, / 9 - 3; 8 * 2; // multiply in JS is an asterisk 9 / 3; Assignment As you've seen already: this assigns a value to a variable. = let myVariable = 'Bob'; Equality This performs a test to see if two values are equal. ...
... 9 / 3; Assignment As you've seen already: this assigns a value to a variable. = let myVariable = 'Bob'; Equality This performs a test to see if two values are equal. It returns a true/false (Boolean) result. === let myVariable = 3; myVariable === 4; Not, Does-not-equal This returns the logically opposite value of what it precedes. It turns a true into a false, etc.. When it is used alongside the Equality operator, the negation operator tests whether two values are not equal. !, !== For "Not", the basic expression is true, but the comparison returns false because we negate it: let myVariable = 3; !(myVariable === 3); "Does-not-equal" gives basically the same result with different syntax. Here we are testing "is my...
...And 3 more matches
Responsive images - Learn web development
uses the w unit, not px as you might expect. This is the image's real size, which can be found by inspecting the image file on your computer (for example, on a Mac you can select the image in Finder and press Cmd + I to bring up the info screen). sizes defines a set of media conditions (e.g. screen widths) and indicates what image size would be best to choose, when certain media conditions are true -- these are the hints we talked about earlier. In this case, before each comma we write: A media condition ((max-width:600px)) -- you'll learn more about these in the CSS topic, but for now let's just say that a media condition describes a possible state that the screen can be in. In this case, we are saying "when the viewport width is 600 pixels or less". A space The width of the slot the ...
...ier. In this case, before each comma we write: A media condition ((max-width:600px)) -- you'll learn more about these in the CSS topic, but for now let's just say that a media condition describes a possible state that the screen can be in. In this case, we are saying "when the viewport width is 600 pixels or less". A space The width of the slot the image will fill when the media condition is true (480px) Note: For the slot width, you may provide an absolute length (px, em) or a length relative to the viewport (vw), but not percentages. You may have noticed that the last slot width has no media condition (this is the default that is chosen when none of the media conditions are true). The browser ignores everything after the first matching condition, so be careful how you order the media...
... the last slot width has no media condition (this is the default that is chosen when none of the media conditions are true). The browser ignores everything after the first matching condition, so be careful how you order the media conditions. So, with these attributes in place, the browser will: Look at its device width. Work out which media condition in the sizes list is the first one to be true. Look at the slot size given to that media query. Load the image referenced in the srcset list that has the same size as the slot or, if there isn't one, the first image that is bigger than the chosen slot size. ...
...And 3 more matches
Drawing graphics - Learn web development
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). Note: 0 degrees is horizontally to the right. ...
...ckwise (anticlockwise) or clockwise (false is clockwise). Note: 0 degrees is horizontally to the right. Let's try adding another arc: ctx.fillStyle = 'yellow'; ctx.beginPath(); ctx.arc(200, 106, 50, degToRad(-45), degToRad(45), true); ctx.lineTo(200, 106); ctx.fill(); The pattern here is very similar, but with two differences: We have set the last parameter of arc() to true, meaning that the arc is drawn counterclockwise, which means that even though the arc is specified as starting at -45 degrees and ending at 45 degrees, we draw the arc around the 270 degrees not inside this portion. If you were to change true to false and then re-run the code, only the 90 degree slice of the circle would be drawn. Before calling fill(), we draw a line to the center of the circ...
...Let's look at the most interesting parts. First of all, we keep track of the mouse's X and Y coordinates and whether it is being clicked or not with three variables: curX, curY, and pressed. When the mouse moves, we fire a function set as the onmousemove event handler, which captures the current X and Y values. We also use onmousedown and onmouseup event handlers to change the value of pressed to true when the mouse button is pressed, and back to false again when it is released. let curX; let curY; let pressed = false; document.onmousemove = function(e) { curX = (window.Event) ? e.pageX : e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); curY = (window.Event) ? e.pageY : e.clientY + (document.documentElement.scrollTop ? do...
...And 3 more matches
Componentizing our React app - Learn web development
function Todo() { return ( ); } This is OK so far, but our component has to return something! ...
...occurrence of Eat with your name prop. Remember: when you're in the middle of a JSX expression, you use curly braces to inject the value of a variable. ...
...three unique tasks. Another problem remains though: they're all still checked by default. Is it completed? In our original static list, only Eat was checked. Once again, we want to reuse most of the UI that makes up a <Todo /> component, but change one thing. That's a good job for another prop! Give each <Todo /> call in App.js a new prop of completed. 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. Change the defaultChecked attribute on the <input /> so that its value is equal to the completed prop. Once you're done, the Todo component's <input /> element will read like this: <in...
...And 3 more matches
Beginning our React todo list - Learn web development
nput type="text" id="new-todo-input" className="input input__lg" name="text" autoComplete="off" /> <button type="submit" className="btn btn__primary btn__lg"> Add </button> </form> <div className="filters btn-group stack-exception"> <button type="button" className="btn toggle-btn" aria-pressed="true"> <span className="visually-hidden">Show </span> <span>all</span> <span className="visually-hidden"> tasks</span> </button> <button type="button" className="btn toggle-btn" aria-pressed="false"> <span className="visually-hidden">Show </span> <span>Active</span> <span className="visually-hidden"> tasks</span> </but...
...sually-hidden"> tasks</span> </button> </div> <h2 id="list-heading"> 3 tasks remaining </h2> <ul role="list" className="todo-list stack-large stack-exception" aria-labelledby="list-heading" > <li className="todo stack-small"> <div className="c-cb"> <input id="todo-0" type="checkbox" defaultChecked={true} /> <label className="todo-label" htmlFor="todo-0"> Eat </label> </div> <div className="btn-group"> <button type="button" className="btn"> Edit <span className="visually-hidden">Eat</span> </button> <button type="button" className="btn btn__danger"> Delete <span className="vis...
...eckbox to check it off as done. The form will allow us to make tasks; the buttons will let us filter them; the heading and list are our way to read them. The UI for editing a task is conspicuously absent for now. That's okay - we'll write that later. Accessibility features You may notice some unusual attributes here. For example: <button type="button" className="btn toggle-btn" aria-pressed="true"> <span className="visually-hidden">Show </span> <span>all</span> <span className="visually-hidden"> tasks</span> </button> Here, aria-pressed tells assistive technology (like screen readers) that the button can be in one of two states: pressed or unpressed. Think of these as analogs for on and off. Setting a value of true means that the button is pressed by default. The class visually-hi...
...And 3 more matches
Creating our first Vue component - Learn web development
to your ToDoItem.vue file. Add a props property inside the export default {} object, which contains an empty object. Inside this object, add two properties with the keys label and done. The label key's value should be an object with 2 properties (or props, as they are called in the context of being available to the components). The first is a required property, which will have a value of true. This will tell Vue that we expect every instance of this component to have a label field. Vue will warn us if a ToDoItem component does not have a label field. The second property we'll add is a type property. Set the value for this property as the JavaScript String type (note the capital "S"). This tells Vue that we expect the value of this property to be a string. Now on to the done p...
...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). Next add a type field with a value of Boolean. This tells Vue we expect the value prop to be a JavaScript boolean type. Your component object should now look like this: <script> export default { props: { label: { required: true, type: String }, done: { default: false, type: Boolean } } }; </script> Using registered props With these props defined inside the component object, we can now use these variable values inside our template. Let's start by adding the label prop to the component template. In your <template>, replace the contents of the <label> element with {{label}}. {{}} is a special template synta...
...e to access any of the necessary attributes from inside data if you used an arrow function. So don't use an arrow function for the data property. So let's add a data property to our ToDoItem component. This will return an object containing a single property that we'll call isDone, whose value is this.done. Update the component object like so: export default { props: { label: { required: true, type: String }, done: { default: false, type: Boolean } }, data() { return { isDone: this.done }; } }; Vue does a little magic here -- it binds all of your props directly to the component instance, so we don't have to call this.props.done. It also binds other attributes (data, which you've already seen, and others like methods, computed, etc.) directly to the instance. T...
...And 3 more matches
Introducing a complete toolchain - Learn web development
an not contain configuration options expressed in a JSON structure (though our tools and many others also support YAML, which you can switch to if that's your preferred flavour of configuration file). First of all, create a file in the root of your will-it-miss directory called .prettierrc.json. To configure prettier, give .prettierrc.json the following contents: { "singleQuote": true, "trailingComma": "es5" } With these settings, when prettier formats JavaScript for you it will use single quotes for all your quoted values, and it won't use trailing commas (a newer feature of ECMAScript that will cause errors in older browsers). You can find more about configuring Prettier in its documentation. Next up, we'll configure eslint -- create another file in the root of yo...
... quotes for all your quoted values, and it won't use trailing commas (a newer feature of ECMAScript that will cause errors in older browsers). You can find more about configuring Prettier in its documentation. ...
...quoted values, and it won't use trailing commas (a newer feature of ECMAScript that will cause errors in older browsers). You can find more about configuring Prettier in its documentation. ...
...And 3 more matches
Creating Custom Events That Can Pass Data
rs In order for your event to work the way it is described here it must be derived from nsDOMEvent. The problem that extension developers will hit is that you are not allowed derive from nsDOMEvent in an extension. You can try to rewrite code but it will have to be a lot of code because nsDOMEvent uses a lot of code outside of itself which you, again, cannot access from an extension. ...
...y to rewrite code but it will have to be a lot of code because nsDOMEvent uses a lot of code outside of itself which you, again, cannot access from an extension. This remains true even if you mark you extension code as "internal". Dispatching your event in JavaScript Here is how to dispatch your event in JavaScript. ...
...ewrite code but it will have to be a lot of code because nsDOMEvent uses a lot of code outside of itself which you, again, cannot access from an extension. This remains true even if you mark you extension code as "internal". Dispatching your event in JavaScript Here is how to dispatch your event in JavaScript. ...
...And 3 more matches
How to implement a custom autocomplete search component
rn ''; }, /** * Get the final value that should be completed when the user confirms * the match at the given index. * @return {string} the final value of the result at the given index */ getFinalCompleteValueAt: function(index) { return this.getValueAt(index); }, /** * Removes the value at the given index from the autocomplete results. * If removeFromDb is set to true, the value should be removed from * persistent storage as well. */ removeValueAt: function(index, removeFromDb) { this._results.splice(index, 1); if (this._comments) this._comments.splice(index, 1); }, getLabelAt: function(index) { return this._results[index]; }, QueryInterface: XPCOMUtils.generateQI([ Ci.nsIAutoCompleteResult ]) }; /** * @constructor * * @impl...
...urn ""; }, /** * Get the final value that should be completed when the user confirms * the match at the given index. * @return {string} the final value of the result at the given index */ getFinalCompleteValueAt: function(index) { return this.getValueAt(index); }, /** * Remove the value at the given index from the autocomplete results. * If removeFromDb is set to true, the value should be removed from * persistent storage as well. */ removeValueAt: function(index, removeFromDb) { this._results.splice(index, 1); this._comments.splice(index, 1); }, QueryInterface: function(aIID) { if (!aIID.equals(Ci.nsIAutoCompleteResult) && !aIID.equals(Ci.nsISupports)) throw Components.results.NS_ERROR_NO_INTERFACE; return this; } }; /...
...Mgr.unregisterFactoryLocation(CLASS_ID, aLocation); }, getClassObject: function(aCompMgr, aCID, aIID) { if (!aIID.equals(Components.interfaces.nsIFactory)) throw Components.results.NS_ERROR_NOT_IMPLEMENTED; if (aCID.equals(CLASS_ID)) return SimpleAutoCompleteSearchFactory; throw Components.results.NS_ERROR_NO_INTERFACE; }, canUnload: function(aCompMgr) { return true; } }; // Module initialization function NSGetModule(aCompMgr, aFileSpec) { return SimpleAutoCompleteSearchModule; } Starting in Gecko 2.0, component registration has been changed, so you need to make the following changes: Add an NSGetFactory() function: function NSGetFactory(cid) { if (cid.toString().toUpperCase() != CLASS_ID.toString().toUpperCase()) { throw Compone...
...And 3 more matches
Download
launch(); Promise showContainingDirectory(); Promise cancel(); Promise removePartialData(); Promise whenSucceeded(); Promise finalize([optional] boolean aRemovePartialData); Properties Attribute Type Description canceled Read only boolean Indicates that the download has been canceled. This property can become true, then it can be reset to false when a canceled download is restarted. This property becomes true as soon as the cancel() method is called, though the stopped property might remain false until the cancellation request has been processed. Temporary files or part files may still exist even if they are expected to be deleted, until the stopped property becomes true. contentType s...
... download source, and may not be known before the download is started. hasProgress Read only boolean Indicates whether this download's progress property is able to report partial progress while the download proceeds, and whether the value in totalBytes is relevant. This depends on the saver and the download source. launchWhenSucceeded boolean If this property is true when the download finishes successfully, the target file will be opened or executed automatically. launcherPath string Local file path of the application to be used to launch the target file, or null if the file should be launched with the default application associated with the contentType property or the extension of the target file. onchange Function This can...
...ype property or the extension of the target file. onchange Function This can be set to a function that is called after other properties change. Warning: This property cannot be used if the download is part of a DownloadList. progress Read only number Progress percent, from 0 to 100. Intermediate values are reported only if hasProgress is true. Note: You shouldn't rely on this property being equal to 100 to determine whether the download is completed. You should use the individual state properties (for example, the succeeded property) instead. saver Read only DownloadSaver Saver object associated with this download. source Read only DownloadSource Source of this download. startTime Read...
...And 3 more matches
PKCS11 Implement
to generate keys. The NSS interprets the combination of the CKF_LOGIN_REQUIRED and CKF_USER_PIN_INITIALIZED flags as shown in Table 1.1. 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. The NSS will use it without prompting the user for a PIN. ...
...use it without prompting the user for a PIN. TRUE FALSE The device is uninitialized. The NSS attempts to initialize the device only if it needs to generate a key or needs to set the user PIN. The NSS calls C_InitPIN to initialize the device and set the user PIN; if these calls are successful, the key is generated and at that point the CFK_USER_PIN_INITIALIZED flag should change from FALSE to TRUE. FALSE TRUE This is a general access device that can have a PIN set on it. Because it's a general access device, NSS never prompts for the PIN, even though it's possible to set a PIN with C_SetPIN. If the PIN is set successfully, the CFK_LOGIN_REQUIRED flag should change to TRUE. The NSS uses this combination of flags for its internal token when the key database password is NULL. These are n...
...The NSS checks whether the user is logged on, and if not prompts the user for a PIN. ...
...And 3 more matches
JS::CallArgs
argc, JS::Value *vp); Name Type Description args unsigned Number of argument. (2nd argument of JSNative) vp JS::Value * A pointer to the argument value array. (3nd argument of JSNative) Methods Methods of JS::CallArgs Method Description bool requireAtLeast(JSContext *cx, const char *fnname, unsigned required) Returns true if there are at least required arguments passed in. If false, it reports an error message on the context. Methods inherited from JS::CallArgsBase Method Description unsigned length() const Returns the number of arguments.. JS::MutableHandleValue operator[](unsigned i) const Returns the i-th zero-indexed argument. JS::HandleValue get(unsigned i)...
...rgsBase Method Description unsigned length() const Returns the number of arguments.. JS::MutableHandleValue operator[](unsigned i) const Returns the i-th zero-indexed argument. JS::HandleValue get(unsigned i) const Returns the i-th zero-indexed argument, or undefined if there's no such argument. bool hasDefined(unsigned i) const Returns true if the i-th zero-indexed argument is present and is not undefined. Methods inherited from JS::detail::CallReceiverBase Method Description JSObject &callee() const Returns the function being called, as an object. Must not be called after rval() has been used! JS::HandleValue calleev() const Returns the function being called, as a value. Must not be calle...
...This method must not be called when the function is being called as a constructor via new. The value may or may not be an object: it is the individual function's responsibility to box the value if needed. JS::Value computeThis(JSContext *cx) const Returns the this value if this is an object, otherwise calls JS_ComputeThis and returns it. bool isConstructing() const Returns true if the function is called via new. MutableHandleValue rval() const Returns the currently-set return value. The initial contents of this value are unspecified. Once this method has been called, callee() and calleev() can no longer be used. (If you're compiling against a debug build of SpiderMonkey, these methods will assert to aid debugging.) If the method you're implementing...
...And 3 more matches
Components.utils.Sandbox
pal); Null principal You can create a null principal using code like: Cc["@mozilla.org/nullprincipal;1"].createInstance(Ci.nsIPrincipal); From Firefox 37 onwards, you can also specify the null principal by simply passing null as the principal argument. options The constructor accepts an optional parameter. This parameter is an object with the following optional properties: freshZone If true creates a new GC region separate from both the calling context's and the sandbox prototype's region. Addons creating sandboxes whose expected lifetime is tied to that of a content window object will want to use sameZoneAs instead. sameZoneAs A JavaScript object in whose garbage collection region the sandbox should be created in. This helps to improve memory usage by allowing sandboxes to be ...
...is an absolute path to the script responsible for creating the sandbox. As of Gecko 13 (Firefox 13.0 / Thunderbird 13.0 / SeaMonkey 2.10), if you don't specify a sandbox name it will default to the caller's filename. sandboxPrototype A prototype object for the sandbox. The sandbox will inherit the contents of this object if it's provided. Passing a content window object, setting wantXrays:true (default) and using an extended principal provides a clean, isolated execution environment in which javascript code that needs Web APIs (such as accessing the window's DOM) can be executed without interference from untrusted content code. wantComponents A Boolean indicating whether the Components object is available or not in the sandbox. Default: true. If the sandbox interacts with untr...
...Default: false. wantGlobalProperties An array of strings. ...
...And 3 more matches
nsIEditorSpellCheck
void UpdateCurrentDictionary(); Methods AddWordToDictionary() Adds the specified word to the current personal dictionary. void AddWordToDictionary( in wstring word ); Parameters word The word to add to the current personal dictionary. canSpellCheck() Determines whether or not spell checking can be enabled. boolean canSpellCheck(); Parameters None. Return value Returns true if spell checking can be enabled. If there are no available dictionaries, the return value is false. checkCurrentDictionary() Call this after any change in installed dictionaries to ensure that the spell checker is not using a current dictionary which is no longer available. If the current dictionary is no longer available, pick another dictionary. void checkCurrentDictionary(); Parameters None.
...ctionary() Call this after any change in installed dictionaries to ensure that the spell checker is not using a current dictionary which is no longer available. If the current dictionary is no longer available, pick another dictionary. void checkCurrentDictionary(); Parameters None. CheckCurrentWord() Checks a given word. In spite of the name, this function checks the word you give it, returning true if the word is misspelled. If the word is misspelled, it will compute the suggestions which you can get from GetSuggestedWord(). boolean CheckCurrentWord( in wstring suggestedWord ); Parameters suggestedWord Missing Description Return value true if the specified word is misspelled; otherwise false. CheckCurrentWordNoSuggest() Like CheckCurrentWord(), checks the word you give it, retu...
...e word is misspelled. If the word is misspelled, it will compute the suggestions which you can get from GetSuggestedWord(). boolean CheckCurrentWord( in wstring suggestedWord ); Parameters suggestedWord Missing Description Return value true if the specified word is misspelled; otherwise false. CheckCurrentWordNoSuggest() Like CheckCurrentWord(), checks the word you give it, returning true if it is misspelled. This is faster than CheckCurrentWord() because it does not compute any suggestions. ...
...And 3 more matches
nsIMsgMessageService
string aSrcURI, in nsIStreamListener aCopyListener, in boolean aMoveMessage, in nsIUrlListener aUrlListener, in nsIMsgWindow aMsgWindow, out nsIURI aURL); Parameters aSrcURI The string url of the message to copy. aCopyListener An nsIStreamListener to be notified of copy events. aMoveMessage Set to true if you want the message to be moved. false leaves it as just a copy. aUrlListener A nsIUrlListener to be notified of url events. aMsgWindow nsIMsgWindow for progress and status feedback Return values aURL The new nsIURI of the message. CopyMessages() Copy multiple messages at a time. See CopyMessage [noscript] void CopyMessages(in nsMsgKeyArrayPtr keys, ...
...pyListener, in boolean aMoveMessage, in nsIUrlListener aUrlListener, in nsIMsgWindow aMsgWindow, out nsIURI aURL); Parameters keys An array of message keys to be copied. srcFolder aCopyListener An nsIStreamListener to be notified of copy events. aMoveMessage Set to true if you want the message to be moved. false leaves it as just a copy. aUrlListener An nsIUrlListener aMsgWindow nsIMsgWindow for progress and status feedback Return values aURL The new nsIURI of the message. (?) DisplayMessage() When you want a message displayed.... void DisplayMessage(in string aMessageURI, in nsISupports aDisplayConsumer, ...
...rateDummyEnvelope, in nsIUrlListener aUrlListener, out nsIURI aURL, in boolean canonicalLineEnding, in nsIMsgWindow aMsgWindow); Parameters aMessageURI Url representing the message to spool out to disk. aFile The file you want the message saved to. aGenerateDummyEnvelope Usually false. Set to true if you want the message appended at the end of the file. aUrlListener A nsIUrlListener for being notified when the copy is finished. canonicalLineEnding aMsgWindow nsIMsgWindow for progress and status feedback Return values aURL The new nsIURI of the saved message. Note: This operation may be obsolete. You always can use streamMessage to get the eml string representation of the messa...
...And 3 more matches
nsIMsgProtocolInfo
sgProtocolInfo interface describes the capabilities of an account type. Inherits from: nsISupports Implemented by: @mozilla.org/messenger/protocol/info;1?type=acct, where acct is the account type that are you are interested in. ...
...=acct, where acct is the account type that are you are interested in. Method overview long getDefaultServerPort(in boolean isSecure); Attributes Attribute Type Description canDelete boolean True if an account of this type may be deleted. Read only. canDuplicate boolean Unused. Read only. canGetIncomingMessages boolean True if Junk UI actions should be enabled for the account type. Read only. ...
...erverPort(in boolean isSecure); Attributes Attribute Type Description canDelete boolean True if an account of this type may be deleted. Read only. canDuplicate boolean Unused. Read only. canGetIncomingMessages boolean True if Junk UI actions should be enabled for the account type. Read only. canGetMessages boolean True if "Get Messages" UI actions should be enabled for the account type. Read only. canLoginAtStartUp boolean True if the account type can perform biff during startup. Read only. defaultDoBiff boolean True if the biff should be enabled by default for the account type. Read only. defaultLocalFilePath nsILocalFile The default path under which all server data...
...And 3 more matches
nsINavHistoryService
currently, history is disabled if the browser.hi...
...currently, history is disabled if the browser.history_expire_days pref is "0". Constants Transition type constants Constant Value Description TRANSITION_LINK 1 This transition type means the user followed a link and got a new toplevel window. ...
...ype means the user followed a link and got a new toplevel window. TRANSITION_TYPED 2 This transition type is set when the user typed the URL to get to the page. TRANSITION_BOOKMARK 3 This transition type is set when the user followed a bookmark to get to the page. TRANSITION_EMBED 4 This transition type is set when some inner content is loaded. This is true of all images on a page, and the contents of the iframe. It is also true of any content in a frame, regardless if whether or not the user clicked something to get there. TRANSITION_REDIRECT_PERMANENT 5 This transition type is set when the transition was a permanent redirect. TRANSITION_REDIRECT_TEMPORARY 6 This transition type is set when the transition was a tempora...
...And 3 more matches
Address Book examples
tion that will match against multiple email addresses stored in one card. Again, this function returns the first match that it finds in the collection, or null. let collection = ... let card = collection.cardForEmailAddress("foo@bar.invalid.com"); Note: Both of these functions may raise an NS_ERROR_NOT_IMPLEMENTED exception if the collection has not implemented that function. This is currently true in the case of LDAP, but may be true in other cases as well. How do I search for multiple contacts? Formulate a boolean search string (see nsIAbCard for built-in property names): var searchQuery = "(or(PrimaryEmail,bw,@V)(NickName,bw,@V)(and(IsMailList,=,TRUE)(Notes,bw,@V)))"; searchQuery = searchQuery.replace(/@V/g, encodeURIComponent("mystr") The search queries use Lisp syntax with operato...
...properties. However, outlook directories are the only other built-in write capable directories. ...
...e contact editor for a particular photo type. Each photo handler must implement the following interface: /* * onLoad: function(aCard, aDocument): * Called when the editor wants to populate the contact editor * input fields with information about aCard's photo. Note that * this does NOT make aCard's photo appear in the contact editor - * this is left to the onShow function. Returns true on success. * If the function returns false, the generic photo handler onLoad * function will be called. * * onShow: function(aCard, aDocument, aTargetID): * Called when the editor wants to show this photo type. * The onShow method should take the input fields in the document, * and render the requested photo in the IMG tag with id * aTargetID. Note that onShow does NOT save ...
...And 3 more matches
AudioWorkletProcessor.process - Web APIs
ive even if the user agent's internal logic would otherwise decide that it's safe to shut down the node. The returned value lets your processor have influence over the lifetime policy of the AudioWorkletProcessor and the node that owns it. If the combination of the return value and the state of the node causes the browser to decide to stop the node, process() will not be called again. ...
... process() will not be called again. 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 3 most common types of audio node are: A source of output. An AudioWorkletProcessor implementing such a node should return true from the process method as long as it produces an output. The method should return false as soon as it's known that it will no longer produce an output. ...
... A node that transforms its input. ...
...And 3 more matches
Using the CSS Painting API - Web APIs
he name we will use in our CSS as the parameter of the paint() function when we want to apply this styling to an element. The second parameter is the class that does all the magic, defining the context options and what to paint to the two-dimensional canvas that will be our image. registerPaint('headerHighlight', class { /* define if alphatransparency is allowed alpha is set to true by default. If set to false, all colours used on the canvas will be fully opaque */ static get contextOptions() { return { alpha: true }; } /* ctx is the 2D drawing context a subset of the HTML5 Canvas API. */ paint(ctx) { ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)'; ctx.fillRect(0, 15, 200, 20); /* order: x, y, w, h */ } ...
... to the size of the element's box model size. In the above image, the background proportional to the size of the element. The 3rd example has width: 50%; set on the block level element, making the element narrower and therefore the background image narrower. ...
... Custom properties In addition to accessing the size of the element, the worklet can also have access to CSS custom properties and regular CSS properties. registerPaint('cssPaintFunctionName', class { static get inputProperties() { return ['PropertyName1', '--customPropertyName2']; } static get inputArguments() { return ['<color>']; } static get contextOptions() { return {alpha: true}; } paint(drawingContext, elementSize, styleMap) { // Paint code goes here. } }); The three parameters of the paint() function include the drawing context, paint size and properties. To be able to access properties, we include the static inputProperties() method, which provides live access to CSS properties, including regular properties and custom properties, and returns an ...
...And 3 more matches
Drawing shapes with canvas - Web APIs
you can use the code snippet below. Just paste it into the draw() function we saw earlier. ...
... Note: To learn more about the arc() function, see the Arcs section below. Lines For drawing straight lines, use the lineTo() meth...
... Note: To learn more about the arc() function, see the Arcs section below. ...
...And 3 more matches
Element.classList - Web APIs
Web › API › Element › classList
jProto, " uCL", { enumerable: 0, configurable: 0, writeable: 0, value: ele }); } else { ele.classList=resTokenList, ele[" uCL"]=resTokenList, ele[" uCLp"]=protoObj.prototype; } ele.attachEvent( "onpropertychange", whenPropChanges ); } try { // Much faster & cleaner version for IE8 & IE9: // Should work in IE8 because Element.prototype instanceof Node is true according to the specs window.Object.defineProperty(window.Element.prototype, "classList", { enumerable: 1, get: function(val){ if (!hasOwnProp.call(this, "classList")) polyfillClassList(this); return this.classList; }, configurable: 0, set: function(val){this.className...
...k(n) {return n===void 0 ? 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] ? ...
... }; 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; }; if (!DOMTokenListProto.forEach) DOMTokenListProto.forEach = function(f){ if (arguments.length === 1) for (var i = 0, Len = this.length; i !== Len; ++i) f( this[i], i, this...
...And 3 more matches
Drag Operations - Web APIs
dering of the selection will appear and follow the mouse pointer as the drag occurs. However, this behavior is only the default drag behavior, if no listeners adjust the data to be dragged. In HTML, apart from the default behavior for images, links, and selections, no other elements are draggable by default. ...
... behavior for images, links, and selections, no other elements are draggable by default. To make other HTML elements draggable, three things must be done: Set the draggable="true" on the element that you wish to make draggable. Add a listener for the dragstart event. Set the drag data in the above listener. Here is an example which allows a section of content to be dragged. <p draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')"> This text <strong>may</strong> be dragged. </p> The draggable attribute is set to "true", so this element becomes draggable. If this attribute were omitted or set to "false", the element would not be dragged, and instead the text would be selected. The draggable attribute may be used on any element, includin...
... Note: When an element is made draggable, text or other elements within it can no longer be selected in the normal way by clicking and dragging with the mouse. ...
...And 3 more matches
RTCPeerConnection.createOffer() - Web APIs
createOffer([options]); myPeerConnection.createOffer(successCallback, failureCallback, [options]) Parameters options Optional An RTCOfferOptions dictionary providing options requested for the offer. RTCOfferOptions dictionary The RTCOfferOptions dictionary is used to customize the offer created by this method. iceRestart Optional To restart ICE on an active connection, set this to true. This will cause the returned offer to have different credentials than those already in place. If you then apply the returned offer, ICE will restart. Specify false to keep the same credentials and therefore not restart ICE. The default is false. offerToReceiveAudio Optional (Legacy) A legacy Boolean option which used to control whether or not to offer to the remote peer the opportunity to try ...
...se to keep the same credentials and therefore not restart ICE. The default is false. offerToReceiveAudio Optional (Legacy) A legacy Boolean option which used to control whether or not to offer to the remote peer the opportunity to try to send audio. If this value is false, the remote peer will not be offered to send audio data, even if the local side will be sending audio data. If this value is true, the remote peer will be offered to send audio data, even if the local side will not be sending audio data. The default behavior is to offer to receive audio only if the local side is sending audio, not otherwise. To emulate this behavior in modern implementations, the presence of this member with a value false, will set the direction of all existing audio transceivers to exclude reception (i.e.
...e default behavior is to offer to receive audio only if the local side is sending audio, not otherwise. To emulate this behavior in modern implementations, the presence of this member with a value false, will set the direction of all existing audio transceivers to exclude reception (i.e. set to either "sendonly" or "inactive"). In modern implementations, the presence of this member with a value true, will ensure there is at least one transceiver set to receive audio that has not been stopped, and if there isn't one, one will be created. Note: You shouldn't use this legacy property. Instead, use RTCRtpTransceiver to control whether or not to accept incoming audio. offerToReceiveVideo Optional (Legacy) A legacy Boolean option which used to control whether or not to offer to the remote p...
...And 3 more matches
A simple RTCDataChannel sample - Web APIs
ion/sdp form) between the two peers. Handling successful peer connection As each side of the peer-to-peer connection is successfully linked up, the corresponding RTCPeerConnection's icecandidate event is fired. 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. Connecting the data channel Once the RTCPeerConnection is open, the datachannel event is sent to the remote to complete the process of opening ...
...The user interface is updated correspondingly by enabling the text input box ...
...The user interface is updated correspondingly by enabling the text input box for the message to send, focusing the input box so that ...
...And 3 more matches
Migrating from webkitAudioContext - Web APIs
eb page's code could execute in the mean time. Because of these problems, this version of the createBuffer() method has been removed, and you should use the asynchronous decodeAudioData() method instead. ...
...ction() { 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 = function() { context.decodeAudioData(xhr.response, function onSuccess(decodedBuffer) { // Decoding was successful, do something useful with the audio buffer }, function onFailure() { alert("Decoding the audio buffer failed"); }); }; Note that the decodeAudioData() method is asynchronous, which means that it will return im...
...var isCustom = (osc.type == "custom"); // isCustom will be ...
...And 3 more matches
Using the aria-invalid attribute - Accessibility
ired field has not been filled in.The attribute should be programmatically set as a result of a validation process. This attribute can be used with any typical HTML form element; it is not limited to elements that have an ARIA role assigned. Values Vocabulary: false (default) No errors detected grammar A grammatical error has been detected. spelling A spelling error has been detected. true The value has failed validation. Any value not in this vocabulary should be treated as true. Possible effects on user agents and assistive technology User agents should inform the user when a field is invalid. Application authors should provide suggestions for correcting the problem, if possible. Authors may prevent a form from being submitted. Note: Opinions may differ on how assistive te...
...ed above is one of those opinions and therefore not normative. Examples Example 1: Simple form validation The following snippet shows a simplified version of two form fields with a validation function attached to the blur event. Note that since the default value for aria-required is false, it is not strictly necessary to add the attribute to input. ...
...ation function attached to the blur event. 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). The snippet below shows a very simple validation function, which only checks for the presence of a particular character (in ...
...And 3 more matches
Using media queries - CSS: Cascading Style Sheets
ds. Note: The examples on this page use CSS's @media for illustrative purposes, but the basic syntax remains the same for all types of media queries. Syntax A media query is composed of an optional media type and any number of media feature expressions. Multiple queries can be combined in various ways by using logical operators. Media queries are case-insensitive. A media query computes to true when the media type (if specified) matches the device on which a document is being displayed and all media feature expressions compute as true. Queries involving unknown media types are always false. Note: A style sheet with a media query attached to its <link> tag will still download even if the query returns false. Nevertheless, its contents will not apply unless and until the result of the q...
... Media types Media types describe the general category of a device. Except when using the not or only logical operators, the media type is optional and the all type will be implied. all Suitable for all devices. ...
...the viewport including width of scrollbar Logical operators The logical operators not, and, and only can be used to compose a complex media query. You can also combine multiple media queries into a single rule by separating them with commas. and The and operator is used for combining multiple media features together into a single media query, requiring each chained feature to return true in order for the query to be true. It is also used for joining media features with media types. not The not operator is used to negate a media query, returning true if the query would otherwise return false. If present in a comma-separated list of queries, it will only negate the specific query to which it is applied. If you use the not operator, you must also specify a media type. Note: In L...
...And 3 more matches
Rich-Text Editing in Mozilla - Developer guides
d by setting the designMode property of a document to "On", such as the document inside an iframe. Once designMode has been set to "On", the document becomes a rich-text editing area and the user can type into it as if it were a textarea. The most basic keyboard commands such as copy and paste are available, all others need to be implemented by the website. Similarly, setting contentEditable to "true" allows you to make individual elements of a document editable. Executing Commands When an HTML document has been switched to designMode, the document object exposes the document.execCommand method which allows one to run commands to manipulate the contents of the editable region. Most commands affect the document's selection (bold, italics, etc), while others insert new elements (adding a link...
...ailable at this time. --fumble 18:13, 24 Apr 2005 (PDT) Example 1 The first example is an HTML document setting its own designMode to "On". This makes the entire document editable in Mozilla 1.3. Internet Explorer, however, does not allow javascript to change the current document's designMode. For it to work in Internet Explorer, the contentEditable attribute of the body tag needs to be set to "true". Figure 2 : First example HTML: <body contentEditable="true" onload="load()"> JavaScript: function load(){ window.document.designMode = "On"; } Example 2 The second example is a simple rich text editing page, where text can be bolded/italicized/underlined, new links can be added and the color of text changed. The example page consists of an iframe, which will be the rich editing area, as...
...me,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.
...And 3 more matches
<input type="checkbox"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › checkbox
t perhaps. 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). It does not indicate whether this checkbox is currently checked: if the checkbox's state is changed, this content attribute does not refle...
...ked. If it is, then the value of the checkbox's value attribute is reported as the input's value. Unlike other browsers, Firefox by default persists the dynamic checked state of an <input> across page loads. Use the autocomplete attribute to control this feature. indeterminate If the indeterminate attribute is present on the <input> element defining a checkbox, the checkbox's value is neither true nor false, but is instead indeterminate, meaning that it's state cannot be determined or stated in pure binary terms. This may happen, for instance, if the state of the checkbox depends on multiple other checkboxes, and those checkboxes have different values. Essentially, then, the indeterminate attribute adds a third possible state to the checkbox: "I don't know." In this state, the browser may...
...ur forms. Indeterminate state checkboxes In addition to the checked and unchecked states, there is a third state a checkbox can be in: indeterminate. This is a state in which it's impossible to say whether the item is toggled on or off. This is set using the HTMLInputElement object's indeterminate property via JavaScript (it cannot be set using an HTML attribute): inputInstance.indeterminate = true; A checkbox in the indeterminate state has a horizontal line in the box (it looks somewhat like a hyphen or minus sign) instead of a check/tick in most browsers. There are not many use cases for this property. The most common is when a checkbox is available that "owns" a number of sub-options (which are also checkboxes). If all of the sub-options are checked, the owning checkbox is also checked...
...And 3 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
t values to numbers: + '42'; // 42 + '010'; // 10 + '0x10'; // 16 A special value called NaN (short for "Not a Number") is returned if the string is non-numeric: parseInt('hello', 10); // NaN NaN is toxic: if you provide it as an operand to any mathematical operation, the result will also be NaN: NaN + 5; // NaN You can test for NaN using the built-in isNaN() function: isNaN(NaN); // true JavaScript also has the special values Infinity and -Infinity: 1 / 0; // Infinity -1 / 0; // -Infinity You can test for Infinity, -Infinity and NaN values using the built-in isFinite() function: isFinite(1 / 0); // false isFinite(-Infinity); // false isFinite(NaN); // false The parseInt() and parseFloat() functions parse a string until they reach a character that isn't valid for the spe...
...nd undefined, which is a value of type undefined that indicates an uninitialized variable -- that is, a value hasn't even been assigned yet. We'll talk about variables later, but in JavaScript it is possible to declare a variable without assigning a value to it. If you do this, the variable's type is undefined. undefined is actually a constant. ...
... variable without assigning a value to it. If you do this, the variable's type is undefined. undefined is actually a constant. JavaScript has a boolean type, with possible values true and false (both of which are keywords.) Any value can be converted to a boolean according to the following rules: false, 0, empty strings (""), NaN, null, and undefined all become false. All other values become true. ...
...And 3 more matches
Grammar and types - JavaScript
f c is ' + c); // Uncaught ReferenceError: c is not defined let x; console.log('The value of x is ' + x); // The value of x is undefined console.log('The value of y is ' + y); // Uncaught ReferenceError: y is not defined let y; You can use undefined to determine whether a variable has a value. In the following code, the variable input is not assigned a value, and the if statement evaluates to true. var input; if (input === undefined) { doThis(); } else { doThat(); } The undefined value behaves as false when used in a boolean context. For example, the following code executes the function myFunction because the myArray element is undefined: var myArray = []; if (!myArray[0]) myFunction(); The undefined value converts to NaN when used in numeric context. var a; a + 2; // Evaluates...
...before ECMAScript 2015 does not have block statement scope. Rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example, the following code will log 5, because the scope of x is the global context (or the function context if the code is part of a function). The scope of x is not limited to the immediate if statement block. if (true) { var x = 5; } console.log(x); // x is 5 This behavior changes when using the let declaration (introduced in ECMAScript 2015). if (true) { let y = 5; } console.log(y); // ReferenceError: y is not defined Variable hoisting Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hois...
... without getting an exception. This concept is known as hoisting. Variables in JavaScript are, in a sense, "hoisted" (or "lifted") to the top of the function or statement. However, variables that are hoisted return a value of undefined. So even if you declare and initialize after you use or refer to this variable, it still returns undefined. ...
...And 3 more matches
Array.prototype.every() - JavaScript
index[, array]])[, thisArg]) Parameters callback A function to test for each element, taking three arguments: element The current element being processed in the array. index Optional The index of the current element being processed in the array. array Optional The array every was called upon. thisArg Optional A value to use as this when executing callback. 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 array until it finds the one where callback returns a falsy value. If such an element is found, the every method immediately returns false. Otherwise, if callback returns a truthy value for all elemen...
...unction 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 array until it finds the one where callback returns a falsy value. If such an element is found, the every method immediately returns false. Otherwise, if callback returns a truthy value for all elements, every returns true. Caution: Calling this method on an empty array will return true for any condition! callback is invoked only for array indexes which have assigned values. It is not invoked for indexes which have been deleted, or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. If a this...
...n of callback. Therefore, callback will not run on elements that are appended to the array after the call to every begins. If existing elements of the array are changed, their value as passed to callback will be the value at the time every visits them. Elements that are deleted are not visited. every acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true. (It is vacuously true that all elements of the empty set satisfy any given condition.) Polyfill every was added to the ECMA-262 standard in the 5th edition, and it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of every in implementations which do not natively support it. Thi...
...And 3 more matches
Array.isArray() - JavaScript
See the article "Determining with absolute accuracy whether or not a JavaScript object is an array" for more details. Given a TypedArray instance, false is always returned. ...
... See the article "Determining with absolute accuracy whether or not a JavaScript object is an array" for more details. Given a TypedArray instance, false is always returned. ...
... See the article "Determining with absolute accuracy whether or not a JavaScript object is an array" for more details. Given a TypedArray instance, false is always returned. ...
...And 3 more matches
Atomics - JavaScript
le threads can read and write the same data in memory. Atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted. Wait and notify The wait() and notify() methods are modeled on Linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs. Static methods Atomics.add() Adds the provided value to the existing value at the specified index of the array. Returns the old value at that index. Atomics.and() Computes a bitwise AND on the value at the specified index of the array with the provided value. Returns the old value at that index. Atomics.compareExchange() Stores a value at th...
... value. Returns the old value at that index. Atomics.compareExchange() Stores a value at the specified index of the array, if it equals a value. Returns the old value. Atomics.exchange() Stores a value at the specified index of the array. Returns the old value. Atomics.isLockFree(size) An optimization primitive that can be used to determine whether to use locks or atomic operations. Returns true if an atomic operation on arrays of the given element size will be implemented using a hardware atomic operation (as opposed to a lock). Experts only. Atomics.load() Returns the value at the specified index of the array. Atomics.notify() Notifies agents that are waiting on the specified index of the array. Returns the number of agents that were notified. Atomics.or() Computes a bitwise OR o...
...turns the old value at that index. ...
...And 3 more matches
Object.isSealed() - JavaScript
or this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.isSealed(obj) Parameters obj The object which should be checked. Return value A Boolean indicating whether or not the given object is sealed. Description Returns true if the object is sealed, otherwise false. An object is sealed if it is not extensible and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). Examples Using Object.isSealed // Objects aren't sealed by default. var empty = {}; Object.isSealed(empty); // === false // If you make an empty object non-extensible, // it is vacuously sealed. Obj...
...d if it is not extensible and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). Examples Using Object.isSealed // Objects aren't sealed by default. var empty = {}; Object.isSealed(empty); // === false // If you make an empty object non-extensible, // it is vacuously sealed. ...
... and if all its properties are non-configurable and therefore not removable (but not necessarily non-writable). Examples Using Object.isSealed // Objects aren't sealed by default. var empty = {}; Object.isSealed(empty); // === false // If you make an empty object non-extensible, // it is vacuously sealed. ...
...And 3 more matches
Proxy - JavaScript
set handler. let validator = { set: function(obj, prop, value) { if (prop === 'age') { if (!Number.isInteger(value)) { throw new TypeError('The age is not an integer'); } if (value > 200) { throw new RangeError('The age seems invalid'); } } // The default behavior to store the value obj[prop] = value; // Indicate success return true; } }; const person = new Proxy({}, validator); person.age = 100; console.log(person.age); // 100 person.age = 'young'; // Throws an exception person.age = 300; // Throws an exception Extending constructor A function proxy could easily extend a constructor with a new constructor. This example uses the construct and apply handlers. function extend(sup, base) { var descriptor = O...
...you want to toggle the attribute or class name of two different elements. Here's how using the set handler. ...
...{ 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.setAttrib...
...And 3 more matches
RegExp.prototype.test() - JavaScript
Otherwise, false. Description Use test() whenever you want to know whether a pattern is found in a string. ...
...Otherwise, false. Description Use test() whenever you want to know whether a pattern is found in a string. test() returns a boolean, unlike the String.prototype.search() method (which returns the index of a match, or -1 if not found). ...
...ch() method.) As with exec() (or in combination with it), test() called multiple times on the same global regular expression instance will advance past the previous match. Examples Using test() Simple example that tests if "hello" is contained at the very beginning of a string, returning a boolean result. ...
...And 3 more matches
Set - JavaScript
ach invocation of callbackFn. ...
... // 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, "some text", {...}, {...} ] in Firefox // logs Set(4) { 1, "some text", {...
...1, "b": 2}, {"a": 1, "b": 2} // (key and value are the same here) for (let [key, value] of mySet.entries()) console.log(key) // convert Set object to an Array object, with Array.from let myArr = Array.from(mySet) // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}] // the following will also work if run in an HTML document mySet.add(document.body) mySet.has(document.querySelector('body')) // true // converting between Set and Array mySet2 = new Set([1, 2, 3, 4]) mySet2.size // 4 [...mySet2] // [1, 2, 3, 4] // intersect can be simulated via let intersection = new Set([...set1].filter(x => set2.has(x))) // difference can be simulated via let difference = new Set([...set1].filter(x => !set2.has(x))) // Iterate set entries with forEach() mySet.forEach...
...And 3 more matches
Less than (<) - JavaScript
The less than operator (<) returns true if the left operand is less than the right operand, and false otherwise. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x < y Description The operands are compared using the Abstract Relational Comparison algorithm, which is roughly summarised below: First, objects are converted to primitives using Symbol.ToPrimitive. If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain. ...
...perands are compared using the Abstract Relational Comparison algorithm, which is roughly summarised below: First, objects are converted to primitives using Symbol.ToPrimitive. If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain. Otherwise JavaScript attempts to convert non-numeric types to numeric values: Boolean values true and false are converted to 1 and 0 respectively. null is converted to 0. undefined is converted to NaN. Strings are converted based on the values they contain, and are converted as NaN if they do not contain numeric values. If either value is NaN, the operator returns false. Otherwise the values are compared as numeric values. Examples String to string comparison console.log("...
...ted to 1 and 0 respectively. null is converted to 0. undefined is converted to NaN. Strings are converted based on the values they contain, and are converted as NaN if they do not contain numeric values. If either value is NaN, the operator returns false. Otherwise the values are compared as numeric values. ...
...And 3 more matches
Strict inequality (!==) - JavaScript
r its operands are not equal. It is the negation of the strict equality operator so the following two lines will always give the same result: x !== y !(x === y) For details of the comparison algorithm, see the page for the strict equality operator. ...
...ult: x !== y !(x === y) For details of the comparison algorithm, see the page for the strict equality operator. ...
...trict equality operator. ...
...And 3 more matches
<mo> - MathML
Web › MathML › Element › mo
hML <mo> element represents an operator in a broad sense. Besides operators in strict mathematical meaning, this element also includes "operators" like parentheses, separators like comma and semicolon, or "absolute value" bars. Attributes accent If the operator is used as an under- or overscript this attribute specifies whether the operator should be treated as an accent. Allowed values are true or false. class, id, style Provided for use with stylesheets. dir The text direction. Possible values are either ltr (left to right) or rtl (right to left). fence There is no visual effect for this attribute, but it specifies whether the operator is a fence (such as parentheses). Allowed values are true or false. form Specifies the role of the operator in an enclosed expression, which af...
...ment.) infix, for separators. (It is the default value if the operator is not included in a <mrow> element.) postfix, closing fences. (It is the default value if the operator is the last argument in a <mrow> element with more than one argument.) href Used to set a hyperlink to a specified URI. largeop Specifies whether the operator should be drawn larger than normal when displaystyle="true" is set. Allowed values are either true or false. lspace The amount of space before the operator (see length for values and units). The constant thickmathspace (5/18em) is the default value. mathbackground The background color. You can use #rgb, #rrggbb and HTML color names. mathcolor The text color. You can use #rgb, #rrggbb and HTML color names. mathsize The size of the content. See len...
...Allowed values are: infinity an arbitrary length movablelimits Specifies whether attached under- and overscripts move to sub- and superscript positions when displaystyle is false...
...And 3 more matches
Communicating With Other Scripts - Archive of obsolete content
fferent matching pages are loaded, content scripts attached to page A cannot interact with those attached to page B. If an add-on loads two or more content scripts into the same page, or panel, using two different method (e.g. a page-mod and a context-menu) they can directly communicate by dispatching and listening for CustomEvents on DOM objects they can access (e.g. the window object). This is true as long as both context scripts have direct access to the same DOM objects. The web content has no access to objects created by the content script, unless the content script explicitly makes them available. For more discussion and an example please see Content Scripts: Communicating with the add-on: Content script to content script. Page Scripts If a page includes its own scripts using <scri...
...ent script "content-script.js" adds an event listener to the button, that sends a custom event containing a message: var messenger = document.getElementById("message"); messenger.addEventListener("click", sendCustomEvent, false); function sendCustomEvent() { var greeting = {"greeting" : "hello world"}; var event = document.createEvent('CustomEvent'); event.initCustomEvent("addon-message", true, true, greeting); document.documentElement.dispatchEvent(event); } Finally, the page script "page-script.js" listens for the message and logs the greeting to the Web Console: window.addEventListener("addon-message", function(event) { console.log(event.detail.greeting); }, false); After Firefox 30: clone the message object This technique depends on being able to share the message payload...
...Also, there's no need to clone the message when using custom DOM events in this direction. In this example, "main.js" creates a page-mod to target the page we are int...
...And 2 more matches
places/bookmarks - Archive of obsolete content
base // and store the emitter let emitter = save(bookmark); // Listen for events emitter.on("data", function (saved, inputItem) { // on a "data" event, an item has been updated, passing in the // latest snapshot from the server as `saved` (with properties // such as `updated` and `id`), as well as the initial input // item as `inputItem` console.log(saved.title === inputItem.title); // true console.log(saved !== inputItem); // true console.log(inputItem === bookmark); // true }).on("end", function (savedItems, inputItems) { // Similar to "data" events, except "end" is an aggregate of // all progress events, with ordered arrays as `savedItems` // and `inputItems` }); Creating several bookmarks with a new group let { Bookmark, Group, save } = require("sdk/places/bookmarks"...
.../ Save `bookmarks` array -- notice we don't have `group` in the array, // although it needs to be saved since all bookmarks are children // of `group`. This will be saved implicitly. save(bookmarks).on("data", function (saved, input) { // A data event is called once for each item saved, as well // as implicit items, like `group` console.log(input === group || ~bookmarks.indexOf(input)); // true }).on("end", function (saves, inputs) { // like the previous example, the "end" event returns an // array of all of our updated saves. Only explicitly saved // items are returned in this array -- the `group` won't be // present here. console.log(saves[0].title); // "Ran" console.log(saves[2].group.title); // "Guitars" }); Searching for bookmarks Bookmarks can be queried with the sea...
...g items: if passing in freshly instantiated bookmark items or a duck-typed object, the item is created on the platform. updating items: for an item referenced from a previous save() or from the result of a search() query, changing the properties and calling save() will update the item on the server. deleting items: to delete a bookmark item, pass in a bookmark item with a property remove set to true. The function returns a PlacesEmitter that emits a data event for each item as it is saved, and an end event when all items have been saved. let { Bookmark, Group } = require("sdk/places/bookmarks"); let myGroup = Group({ title: "My Group" }); let myBookmark = Bookmark({ title: "Moz", url: "http://mozilla.com", group: myGroup }); save(myBookmark).on("data", function (item, inputItem) {...
...And 2 more matches
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
r the user to discover your buttons. Keep in mind most users don't know how to customize toolbars in Firefox. Let's add our own toolbar. This is done in the overlay as well. <window id="main-window"> <toolbox id="navigator-toolbox"> <toolbar id="xulschoolhello-toolbar" toolbarname="&xulschoolhello.toolbarName.label;" accesskey="&xulschoolhello.toolbar.accesskey;" customizable="true" mode="icons" context="toolbar-context-menu" defaultset="xulschoolhello-hello-world-button" insertbefore="PersonalToolbar" /> </toolbox> </window> (Note for Mac OS X: <window id="main-window"> and </window> are not required) Our toolbar is added as a child of the toolbox element in the main browser window. The toolbox is the collection of toolbars in Firefox, including the main ...
...ox element in the main browser window. The toolbox is the collection of toolbars in Firefox, including the main menu bar. Let's look at the attributes we used: The toolbarname is the name that will appear on the View > Toolbars menulist. This menu allows hiding and showing any toolbar. The customizable attribute determines if the user can customize the toolbar. You should normally set this to true, unless you have strong reasons not to want users changing your toolbar. The mode attribute is set to icons, which is the usual value. This can be changed in the Customize dialog by the user. The context attribute should also be set if you want a customizable toolbar. It points to the id of a popup element that holds the customization options that are displayed when the user right-clicks on the...
...region CSS property is used. Here are some examples of how the CSS for a toolbarbutton would look like on the 3 major platforms. This assumes that you've set the class xs-hw-toolbarbutton to all of your buttons. Windows: /* The second and third selectors at the bottom are necessary to prevent conflicts with installed themes. ...
...And 2 more matches
Index - Archive of obsolete content
f the HTML 5 specification. 429 Editor Embedding Guide Embedding Mozilla, Guide, Midas, NeedsHelp Given an nsIWebBrowser instance, get an nsIDOMWindow from the GetContentDOMWindow call. Then simply call nsIWebBrowser->do_GetInterface on the nsIWebBrowser to retrieve the nsIEditingSession from it. From there you call editingSession->MakeWindowEditable(domWindow, editortype, PR_TRUE). The first parameter is the nsIDOMWindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading. In calling this method, the editor is created underneath and the event listeners are all prepa if (NS_FAILED(rv)) return NS_ERROR_FAILURE; // we are not setup??!! nsCOMPtr<nsIEditingS...
... 804 close XUL Attributes, XUL Reference No summary! 805 closebutton XUL Attributes, XUL Reference No summary! 806 closemenu XUL Attributes, XUL Reference No summary! 807 coalesceduplicatearcs XUL Attributes, XUL Reference No summary! 808 colla...
...summary! 1819 action NeedsExample, XUL Elements, XUL Reference Used to specify the content that should be generated for each matching result from a query. The action should be contained within a query or rule element. 1820 appendChild Node appendChild ( Node newChild ) 1821 arrowscrollbox XUL Elements, XUL Reference clicktoscroll, if true, the arrows must be clicked to scroll the scrollbox content. 1822 assign XUL Elements, XUL Reference For XML templates, specifies an additional variable to assign a value to. 1823 attribute.align The align attribute specifies how child elements of the box are aligned, when the size of the box is larger than the total size of the children. For boxes that ...
...And 2 more matches
Extensions - Archive of obsolete content
o have different commands for different types of targets. While the popup is open, the gContextMenu global variable is set to an object which handles all of the functionality specific to the Firefox context menu. Specifically, this object is initialized with a set of properties that indiciate the type of object that was the target of the context menu. For instance, the 'onLink' property is set to true when a link was context-clicked. You may wish to use these properties instead of determining the type yourself, as the code already handles various special and complex cases that would take a lot of code to deal with manually. The following are the most common properties that you can check. An example follows. target The element that was context clicked. If the keyboard was used to ...
... of determining the type yourself, as the code already handles various special and complex cases that would take a lot of code to deal with manually. The following are the most common properties that you can check. An example follows. target The element that was context clicked. If the keyboard was used to open a context menu, this will be the focused element. onTextInput True if the target is a plain or password type input, a textarea, or an editable area. This would be used to enable or disable commands related to text editing. onImage True if the target is an image. hasBGImage True if the target or an ancestor has a background image. onMathML True if the target is a MathML element. onLink True if the target is a link. ...
... or password type input, a textarea, or an editable area. This would be used to enable or disable commands related to text editing. onImage True if the target is an image. hasBGImage True if the target or an ancestor has a background image. onMathML True if the target is a MathML element. onLink True if the target is a link. onMailtoLink True if the target is a link to an email address (a mailto: link). linkURL The URL of the link that was context clicked. inFrame True if the context click occured from within a frame. ...
...And 2 more matches
Multiple Rules - Archive of obsolete content
al images. Here is another example for an XML source: <radiogroup datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="person"/> <rule> <where subject="?gender" rel="equals" value="male"/> <action> <radio uri="?" label="?name is male"/> </action> </rule> <rule> <action> <radio uri="?" label="?name is female" disabled="true"/> </action> </rule> </template> </radiogroup> In this example, all male people are matched with the first rule, and a radio button is generated for each one. We assume that anyone that isn't male is female and use the second rule to create a disabled radio button for females. As all males have been filtered out by the first rule, we do not need any conditions for the second rule. ...
...itions allow a number of useful ways to filter results. <rule> <where subject="?name" rel="contains" value=" "/> <where subject="?letters" rel="less" value="15"/> <action> <label uri="?" value="?name has two names for a total length of ?letters"/> </action> </rule> Negating a Condition You can reverse a where clause by using the negate attribute. ...
...he negate attribute to true, the condition matches only those that don't match the condition, reversing the results that match. For example, these two conditions have the opposite effect. The first matches only results with a ?title of 'Canal', and the second matches those that do not. <where subject="?title" rel="equals" value="Canal"/> <where subject="?title" rel="equals" value="Canal" negate="true"/> You can use the negate attribute with all of the relational operators. For example, although there is no 'greater or equal' operator, you can acheive this effect with a negated 'less' operator. <where subject="?age" rel="less" value="10" negate="true"/> Additional Where Clause Attributes By default, the case of values must match in a condition. You can disable this for a where clause by s...
...And 2 more matches
Special Condition Tests - Archive of obsolete content
" value="?address"/> </action> </rule> </template> </vbox> Containment Tests For RDF sources, the simple rule syntax supports two special conditional tests that are commonly used with multiple rules. The first of these tests can be used to test if an element is a container or not. To use this test, place an iscontainer attribute on a <rule>. 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. A container is an RDF container such as a Seq. The iscontainer attribute makes it easier to handle recursive content since you can have one rule for all containers and another rule for all non-containers. You don't need to match by type or some other predicate. This allows you to recurse down to larger level...
...te. This allows you to recurse down to larger levels without needing additional rules. It is commonly used with menus, and we can rewrite the previous example using the iscontainer attribute instead. ...
...ule> <menupopup> <menuitem uri="rdf:*" label="rdf:http://www.xulplanet.com/rdf/address"/> </menupopup> </rule> </template> </button> The only difference in the code in this example is that the order of the rules has been switched around, the condition check for house has been removed and the iscontainer attribute has been added. Since the iscontainer attribute is set to true, the rule will match as long as the member value or child of the starting node is an RDF container. We could also have left the rules in the original order and set the iscontainer on the first rule to false. The only thing we need to make sure is that the rules are in the proper order, so that the right data will be matched by the right rule. Remember, the more specific rules should go before les...
...And 2 more matches
Commands - Archive of obsolete content
lly. If you re-enable the command, the buttons will become enabled again. Example: Toggling command disabled Example 2 : Source View <command id="cmd_openhelp" oncommand="alert('Help');"/> <button label="Help" command="cmd_openhelp"/> <button label="More Help" command="cmd_openhelp"/> <button label="Disable" oncommand="document.getElementById('cmd_openhelp').setAttribute('disabled','true');"/> <button label="Enable" oncommand="document.getElementById('cmd_openhelp').removeAttribute('disabled');"/> In this example, both buttons use the same command. When the Disable button is pressed, the command is disabled by setting its disabled attribute, and both buttons will be disabled as well. It is normal to put a group of commands inside a commandset element, together near the...
...for retrieving controllers for commands and for retrieving and modifying the focus. Adding Controllers You can implement your own controllers to respond to commands. You could even override the default handling of a command with careful placement of the controller. A controller is expected to implement four methods, which are listed below: supportsCommand (command) this method should return true if the controller supports a command. If you return false, the command is not handled and command dispatcher will look for another controller. A single controller may support multiple commands. isCommandEnabled (command) this method should return true if the command is enabled, or false if it is disabled. Corresponding buttons will be disabled automatically. doCommand (command) execute the co...
....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 the four methods described above. ...
...And 2 more matches
Modifying a XUL Interface - Archive of obsolete content
in the document. Copying Nodes To copy nodes however, you may call the cloneNode() function. This function makes a copy of an existing node so that you can add it somewhere else. The original node will stay where it is. It takes one boolean argument which indicates whether to copy all of the node's children or not. If false, only the node is copied, such that the copy won't have any children. ...
...t you can add it somewhere else. The original node will stay where it is. It takes one boolean argument which indicates whether to copy all of the node's children or not. If false, only the node is copied, such that the copy won't have any children. If true, all of the children are copied as well. This is done recursively, so for large tree structures make sure that this is desired before passing true to the cloneNode() function. Here is an example: Example 2 : Source View <hbox height="400"> <button label="Copy" oncommand="this.parentNode.appendChild(this.nextSibling.cloneNode(true));"/> <vbox> <button label="First"/> <button label="Second"/> </vbox> </hbox> When the Copy button is pressed.. we retrieve the nextSibling of the button, which will be the vbox element...
...this.label);"/> Toggling a checkbox Checkboxes have a checked property which may be used to check or uncheck the checkbox. It should be easy to determine how this is used. In this next example, we reverse the state of the checked property whenever the button is pressed. 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 propertie...
...And 2 more matches
Trees and Templates - Archive of obsolete content
. This would normally be set to an RDF property so that the label is pulled from the datasource. Template-built Tree Example The following example demonstrates a template-built tree, in this case for the file system. ...
...e direction in which the column will be sorted by default. Three values are possible: ascending the data is displayed is ascending order. descending the data is displayed is descending order. natural the data is displayed in natural order, which means the order the data is stored in the RDF datasource. ...
... the data is displayed in natural order, which means the order the data is stored in the RDF datasource. The final attribute, sortActive should be set to true for one column, the one that you would like to be sorted by default. ...
...And 2 more matches
listbox - Archive of obsolete content
ibleRow, getIndexOfItem, getItemAtIndex, getNumberOfVisibleRows, getRowCount, getSelectedItem, insertItemAt, invertSelection, moveByOffset, removeItemAt, removeItemFromSelection, scrollToIndex, selectAll, selectItem, selectItemRange, timedSelect, toggleItemSelection Examples <listbox id="theList"> <listitem label="Ruby"/> <listitem label="Emerald"/> <listitem label="Sapphire" selected="true"/> <listitem label="Diamond"/> </listbox> <listbox id="theList" rows="10" width="400"> <listhead> <listheader label="1ct Gem" width="240"/> <listheader label="Price" width="150"/> </listhead> <listcols> <listcol/> <listcol flex="1"/> </listcols> </listbox> var theList = document.getElementById('theList'); gems = [ {gem: "Ruby", Price: "$3,500 - $4,600"}, ...
...s disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...f the attribute, as it may need to update additional state. disableKeyNavigation Type: boolean If this attribute is not used, the user can navigate to specific items within the element by pressing keys corresponding to letters in the item's label. This is done incrementally, so typing more letters with select more specific items. This feature may be disabled by setting this attribute to true. preference Type: id Connects the element to a corresponding preference. This attribute only has any effect when used inside a prefwindow. More information is available in the Preferences System article. rows Type: integer The number of rows to display in the element. If the element contains more than this number of rows, a scrollbar will appear which the user can...
...And 2 more matches
menuitem - Archive of obsolete content
invoke the command. If this value is set, it overrides an assigned key set in the key attribute. This attribute does not apply to menus directly on the menubar. accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. ...
...r. accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. allowevents Type: boolean If true, events are passed to children of the element. Otherwise, events are passed to the element only. autocheck Type: boolean If this attribute is true or left out, the checked state of the button will be switched each time the button is pressed. If this attribute is false, the checked state must be adjusted manually. When autocheck is true, the button type should be "checkbox" or "radio". checked Type: boolean Indicates whether the element is checked or not. Use hasAttribute() to determine whether this attribute is set instead of getAt...
...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. ...
...And 2 more matches
prefwindow - Archive of obsolete content
the Preferences System article. Important note for XULrunner-based applications: the Preferences System - part of the toolkit - still relies on two browser.* preferences. The first one is browser.preferences.instantApply, a boolean preference. The preference window will not run correctly if you do not set this preference in your application's defaults (see bug 485150 for more information). A true value for this preference makes the preference window apply immediately the user choices, without waiting for the dialog to close with OK. The second preference is browser.preferences.animateFadeIn, again a boolean preference. 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. For ...
...tonlabelextra2 attribute and its command with the ondialogextra2 attribute. Note: If you don't want to display any buttons in the dialog box, set the value of this attribute to "," (a single comma). Warning: If the accept and cancel buttons are actually shown is system dependent and is mainly controlled by the value of the boolean preference browser.preferences.instantApply. ...
... defaultButton Type: string Normally this attribute should not be set, but if it is, it specifies the default button in the dialog. Typically, this means that the button will be activated when the Enter key is pressed. ...
...And 2 more matches
toolbar - Archive of obsolete content
When set to false, the default, the toolbar is visible. This only has an effect on Windows and needs to be combined with type="menubar" and a menubar element. currentset Not in SeaMonkey 1.x Type: comma-separated string The curr...
...ds insertItem Style classes chromeclass-toolbar Examples <toolbox> <toolbar id="nav-toolbar"> <toolbarbutton id="nav-users" accesskey="U" label="Users"/> <toolbarbutton id="nav-groups" accesskey="p" label="Groups"/> <toolbarbutton id="nav-events" accesskey="E" label="Events" disabled="true"/> </toolbar> </toolbox> Attributes autohide Type: boolean When set to true, the toolbar will be invisible unless the Alt key is pressed by the user. When set to false, the default, the toolbar is visible. This only has an effect on Windows and needs to be combined with type="menubar" and a menubar element. currentset Not in SeaMonkey 1.x Type: comma-separated string The current set of displayed items on the toolbar. This will be modified when the user customize...
... of item IDs from the toolbarpalette or, additionally, any of the following strings: "separator", "spring", "spacer". customindex Not in SeaMonkey 1.x Type: integer This value is the index of the toolbar in the list of the custom toolbars. The value is updated automatically by the toolbar customization dialog. customizable Not in SeaMonkey 1.x Type: boolean Set this attribute to true on toolbars that can be customized. This causes the set of buttons to be persisted across sessions. defaultset Not in SeaMonkey 1.x Type: comma-separated list of item ids The default set of displayed items on the toolbar. This should be set to a comma-separated list of item IDs from the toolbarpalette. For example, back-button,forward-button,print-button. grippyhidden SeaMonkey on...
...And 2 more matches
tooltip - Archive of obsolete content
wish to use the value none and the displayed text is larger than this maximum width, you may be able to use the max-width CSS property (or the maxwidth attribute) to override this size. For example, for a menuitem in a menu you can add the following CSS rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } default Type: boolean If true, the tooltip is used as the default popup for displaying tooltips in the window. label Type: string The label that will appear on the element. If this is left out, no text appears. For an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. noautohide Type: boolean If this attribute is set to false or...
... string The label that will appear on the element. If this is left out, no text appears. For an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. noautohide Type: boolean If this attribute is set to false or omitted, the tooltip will automatically disappear after a few seconds. If this attribute is set to true, this will not happen and the tooltip will only hide when the user moves the mouse to another element. onpopuphidden Type: script code This event is sent to a popup after it has been hidden. This event may also be received while the popup is still open, but when sub-menus contained within this popup are hidden. Example: <menupopup id="top" onpopuphidden="console.log('The onpopuphi...
...This handler is usually used to dynamically set the contents when the user requests to display it. Returning false from this event handler prevents the popup from appearing. onpopupshown Type: script code This event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened. ...
...And 2 more matches
XULRunner tips - Archive of obsolete content
("xpinstall.dialog.progress.skin", "chrome://mozapps/content/extensions/extensions.xul?type=themes"); pref("xpinstall.dialog.progress.chrome", "chrome://mozapps/content/extensions/extensions.xul?type=extensions"); pref("xpinstall.dialog.progress.type.skin", "Extension:Manager-themes"); pref("xpinstall.dialog.progress.type.chrome", "Extension:Manager-extensions"); pref("extensions.update.enabled", true); pref("extensions.update.interval", 86400); pref("extensions.dss.enabled", false); pref("extensions.dss.switchPending", false); pref("extensions.ignoreMTimeChanges", false); pref("extensions.logging.enabled", false); pref("general.skins.selectedSkin", "classic/1.0"); // NB these point at AMO pref("extensions.update.url", "chrome://mozapps/locale/extensions/extensions.properties"); pref("extensio...
...con of specific window, see Window icons. Reading command line arguments See Chrome: Command Line and XULRunner:CommandLine. Command line arguments are handled via nsICommandLineHandler. ...
... and XULRunner:CommandLine. Command line arguments are handled via nsICommandLineHandler. ...
...And 2 more matches
The global XML object - Archive of obsolete content
s. To add a method to XML.prototype, define XML.prototype.function::methodName or XML.prototype.function::[methodNameString]. The following example defines the fooCount() method, which returns the amount of <foo> elements in the XML: XML.prototype.function::fooCount = function fooCount() { return this..foo.length(); }; <foobar><foo/><foo/><foo/></foobar>.fooCount() // returns 3 ignoreComments true by default. This property tells E4X to ignore comment nodes when serializing and filtering. This means that if ignoreComments is true, the list returned by .comments() will be empty. Observe: var element = <foo> <!-- my comment --> <bar/> </foo>; element.comments().length(); // returns 0 element.toXMLString(); // returns <foo><bar/></foo> XML.ignoreC...
...-> <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. This property tells E4X to ignore processing instructions in XML when serializing and filtering. For example var element = <foo> <?process x="true"?> <bar/> <?process x="false"?> </foo>; element.toXMLString(); // returns <foo><bar/></foo> XML.ignoreProcessingInstructions = false; var element = <foo> <?proc...
...ault. This property tells E4X to ignore processing instructions in XML when serializing and filtering. For example var element = <foo> <?process x="true"?> <bar/> <?process x="false"?> </foo>; element.toXMLString(); // 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. Ignores whitespace between nodes and leading and trailing whitespace in text nodes, which would otherwise be interpreted as text nodes or as part of those text nodes, respectively. pret...
...And 2 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
in scope. If you intend to allow the execution of server-side JavaScript from the client-side, you can correct the code in listing 1 by doing one of three things. Change the runat attribute value of server to server-proxy. Add a statement inside the server-side script block to expose a particular server-side function to the browser. This statement is of the form <functionName>.proxy = true. Ensure the server-side function name is contained within the Jaxer.proxies array. Generally it's a best practice to use either the second or third strategy since in this case you are exposing only what's needed to the client. See Listing 5 for an update to Listing 1 to reflect this. Listing 5 - Demonstration of server-proxy <script runat="server"> function not...
...at's needed to the client. See Listing 5 for an update to Listing 1 to reflect this. ...
...If it passes validation, the formProcessor server-side function is invoked which does the same validation check using the shared validateComments function. Finally, the comment information is assembled into a string and appended to the dump file. Datab...
...And 2 more matches
Windows Media in Netscape - Archive of obsolete content
object detection of ActiveXObject and GeckoActiveXObject to determine if the Windows Media ActiveX control is supported and available for use. JavaScript will dynamically write out what browser you are running, and what kind of Windows Media Player technology you may have. 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). Below, some of the salient points are illustrated in a code snippet: if (window.ActiveXObject && navigator.userAgent.indexOf('Windows') != -1) { // IE for Windows object instantiation -- use of ActiveXObject } else if(wi...
...er or IE, and have installed Windows Media Player 7 or above, the snippet of code below should produce a Windows Media control and play a song. THIS IS THE EXAMPLE: NEEDS TO BE EMBEDDED IN WIKI PAGE (can it just be put here?) <object id="PlayerEx2" classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" height="200" width="200"> <param name="uiMode" value="full"> <param name="autoStart" value="True"> <param name="URL" value="media/preludesteel.wma"> Your browser does not support the ActiveX Windows Media Player </object> The same markup (used above and shown below) will work in both IE and Netscape 7.1. <object id="PlayerEx2" classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" height="200" width="200"> <param name="uiMode" value="full" /> <param name="autoStart" value...
... <param name="URL" value="media/preludesteel.wma"> Your browser does not support the ActiveX Windows Media Player </object> The same markup (used above and shown below) will work in both IE and Netscape 7.1. <object id="PlayerEx2" classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" height="200" width="200"> <param name="uiMode" value="full" /> <param name="autoStart" value="true" /> <param name="URL" value="preludesteel.wma" /> Your browser does not support the ActiveX Windows Media Player </object> The classid attribute references the clsid of Windows Media Player 7 and above -- Windows Media Player versions before 7 used a different clsid. Examples in this article all assume that the user is running Windows Media Player 7 and later, although Netscape 7.1 support...
...And 2 more matches
Audio for Web games - Game development
you create an audio context. You'll need to take account of the time between creating an audio context and when the first audio track starts playing. Recording this offset and querying the playing track's current time gives you enough information to synchronize separate pieces of audio. ...
...udio. ...
...by="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="fals...
...And 2 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
will sit on the same line as one another in the rendered output. 34 Block (scripting) CodingScripting, Glossary, JavaScript In JavaScript, a block is a collection of related statements enclosed in braces ("{}"). 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. 35 Block cipher mode of operation Block cipher mode of operation, Cryptography, Glossary, Security A block cipher mode of operation, usually just called a "mode" in context, specifies how a block cipher should be used to encrypt or decrypt messages that are longer than the block size. 36 Boolean Boolean, Codin...
...Security A block cipher mode of operation, usually just called a "mode" in context, specifies how a block cipher should be used to encrypt or decrypt messages that are longer than the block size. 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. 37 Boot2Gecko Boot2Gecko, Firefox OS, Glossary, Infrastructure, Intro Boot2Gecko (B2G) is the engineering codename for Firefox OS and refers to builds that haven't yet received official Firefox OS branding. (Firefox OS was also often called Boot2Gecko before the project had an official name.) 38 Bootstrap Bootstrap, CSS, Glossary, Intro, framework ...
...umbers are the operand and "+" is the operator. 304 Operator CodingScripting, Glossary Reserved syntax consisting of punctuation or alphanumeric characters that carries out built-in functionality. For example, in JavaScript the addition operator ("+") adds numbers together and concatenates strings, whereas the "not" operator ("!") negates an expression -- for example making a true statement return false. 305 Origin Glossary, Security, WebMechanics, origin Web content's origin is defined by the scheme (protocol), host (domain), and port of the URL used to access it. Two objects have the same origin only when the scheme, host, and port all match. 306 P2P Glossary, Infrastructure, Networking, P2P P2P (Peer-to-peer) is a computer netwo...
...And 2 more matches
Client-side storage - Learn web development
em('name'); // run nameDisplayCheck() to sort out displaying the // generic greeting again and updating the form display nameDisplayCheck(); }); It is now time to define the nameDisplayCheck() function itself. Here we check whether the name item has been stored in web storage by using localStorage.getItem('name') as a conditional test. If it has been stored, this call will evaluate to true; if not, it will be false. If it is true, we display a personalized greeting, display the "forget" part of the form, and hide the "Say hello" part of the form. If it is false, we display a generic greeting and do the opposite. Again, put the following code at the bottom: // define the nameDisplayCheck() function function nameDisplayCheck() { // check whether the 'name' data item is stored in...
...Here we first grab a reference to the existin...
...: 'frog' }, { 'name' : 'monster' }, { 'name' : 'pig' }, { 'name' : 'rabbit' } ]; To start with, once the database is successfully opened we run an init() function. This loops through the different video names, trying to load a record identified by each name from the videos database. If each video is found in the database (easily checked by seeing whether request.result evaluates to true -- if the record is not present, it will be undefined), its video files (stored as blobs) and the video name are passed straight to the displayVideo() function to place them in the UI. If not, the video name is passed to the fetchVideoFromNetwork() function to ... you guessed it -- fetch the video from the network. function init() { // Loop through the video names one by one for(let i = 0;...
...And 2 more matches
Cookies Preferences in Mozilla
prompting was removed in Firefox 44) 2 = Accept for current session only 3 = Accept for N days network.cookie.lifetime.days Default Value: 90 Only used if network.cookie.lifetimePolicy is set to 3 Sets the number of days that the lifetime of cookies should be limited to. ...
...nly used if network.cookie.lifetimePolicy is set to 3 Sets the number of days that the lifetime of cookies should be limited to. ...
... New in Thunderbird 3 This preference is applicable to Thunderbird 3 and later. Earlier versions of Thunderbird only allowed cookies on RSS feeds. network.cookie.prefsMigrated Default Value: false Migration pref f...
...And 2 more matches
Debugging on Mac OS X
ay need to take one of the following steps to make sure this file is used. If you are using lldb on the command line (independently of Xcode) and you will always run it from either the top source directory, the object directory or else the dist/bin subdirectory of the object directory, then adding the following setting to your $HOME/.lldbinit is sufficient: settings set target.load-cwd-lldbinit true However, if you will run lldb from a different directory, or if you will be running it indirectly by debugging in Xcode (Xcode always runs lldb from "/"), then this setting will not help you. Instead, add the following to your $HOME/.lldbinit: # This automatically sources the Mozilla project's .lldbinit as soon as lldb # starts or attaches to a Mozilla app (that's in an object directory). # # T...
...t's in an object directory). # # This is mainly a workaround for Xcode not providing a way to specify that # lldb should be run from a given directory. (Xcode always runs lldb from "/", # regardless of what directory Xcode was started from, and regardless of the # value of the "Custom working directory" field in the Scheme's Run options. # Therefore setting `settings set target.load-cwd-lldbinit true` can't help us # without Xcode providing that functionality.) # # The following works by setting a one-shot breakpoint to break on a function # that we know will both run early (which we want when we start first start the # app) and run frequently (which we want so that it will trigger ASAP if we # attach to an already running app). The breakpoint runs some commands to # figure out the object di...
... running app). The breakpoint runs some commands to # figure out the object directory path from the attached target and then # sources the .lldbinit from there. # # NOTE: This scripts actions take a few seconds to complete, so the custom # formatters, commands etc. that are added may not be immediately available. # breakpoint set --name nsThread::ProcessNextEvent --thread-index 1 --auto-continue true --one-shot true breakpoint command add -s python # This script that we run does not work if we try to use the global 'lldb' # object, since it is out of date at the time that the script runs (for # example, `lldb.target.executable.fullpath` is empty). Therefore we must # get the following objects from the 'frame' object. target = frame.GetThread().GetProcess().GetTarget() ...
...And 2 more matches
IME handling guide
example, if WidgetKeyboardEvent should be dispatched when there is a composition is managed by this class in XP level. First of use, native IME handlers get the rights to use TextEventDispatcher with a call of BeginNativeInputTransaction(). Then, StartComposition(), SetPendingComposition(), FlushPendingComposition(), CommitComposition(), etc. are available if BeginNativeInputTransaction() return true. These methods automatically manage composition state and dispatch WidgetCompositionEvent properly. This is also used by mozilla::TextInputProcessor which can emulates (or implements) IME with chrome script. So, native IME handlers using this class means that the dispatching part is also tested by automated tests. mozilla::WidgetCompositionEvent Internally, WidgetCompositionEvent represents na...
...ludes NOTIFY_TEXT_CHANGE. If two or more text changes occurred after previous NOTIFY_IME_OF_TEXT_CHANGE or NOTIFY_IME_OF_FOCUS, the ranges of all changes are merged. E.g., if first change is from 1 to 5 and second change is from 5 to 10, the notified range is from 1 to 10. If all merged text changes were caused by composition, IMENotification::mTextChangeData::mCausedOnlyByComposition is set to true. This is useful if native IME handler wants to ignore all text changes which are expected by native IME. If at least one text change of the merged text changes was caused by current composition, IMENotification::mTextChangeData::mIncludingChangesDuringComposition is set to true. This is useful if native IME handler wants to ignore delayed text change notifications. If at least one text change o...
... text changes was caused by current composition, IMENotification::mTextChangeData::mIncludingChangesDuringComposition is set to true. This is useful if native IME handler wants to ignore delayed text change notifications. If at least one text change of the merged text changes was caused when there was no composition, IMENotification::mTextChangeData::mIncludingChangesWithoutComposition is set to true. NOTIFY_IME_OF_SELECTION_CHANGE When selection (or caret position) is changed in focused editor, widget is notified of this. If the last selection change was occurred by a composition event event handling, IMENotification::mSelectionChangeData::mCausedByComposition is set to true. This is useful if native IME handler wants to ignore the last selection change which is expected by native IME. I...
...And 2 more matches
Extending a Protocol
e shall soon see!). In our case, our protocol, which we will call PEcho.ipdl, will send a message to a parent, and the parent will respond with the message we sent. As a heirarchy, this will look like this: This means that, PWindowGlobal.ipdl: Manages: meaning that PWindowGlobal.ipdl is responsible managing the creation of instances of PEcho children and the parent. And the inverse is also true, as you will soon see: PEcho.idpl will need explicitly state that PWindowGlobal.ipdl is managing it. Includes: this is kinda like "#includes" in C++, except it's not a preprocessor directive. It just includes the defintion and makes it available to PWindowGlobal.ipdl. Constructs: by which we mean, PWindowGlobal is in charge of contructing the parent/child relationship. Without this, we can't...
...Naturally, we want to remove that once we done implementing. Implementing methods on WindowGlobalChild.cpp So, now we need to do the child. Open up dom/ipc/WindowGlobalChild.cpp and let's implement: AllocPEchoChild() DeallocPEchoChild(PEchoChild* aActor) already_AddRefed<EchoChild> WindowGlobalChild::Allo...
...lobalChild.cpp So, now we need to do the child. ...
...And 2 more matches
IPDL Tutorial
reject/failure callbacks take a mozilla::ipc::ResponseRejectReason&& and are called in case of a fatal error, such as an IPC error. Therefore, besides callback/promise style response handling, these two overloads are functionally equivalent. ...
... are called in case of a fatal error, such as an IPC error. Therefore, besides callback/promise style response handling, these two overloads are functionally equivalent. ...
...}; In some cases, however, external code may hold references to actor implementations which require refcounting or other lifetime strategies. In this case, the alloc/dealloc pairs can perform different actions. Here is an example of refcounting: class ExampleChild : public nsIObserver, public PExampleChild { ... }; virtual PExampleChild* TopLevelChild::AllocPExample() { RefPtr<Ex...
...And 2 more matches
AsyncTestUtils extended framework
ng contract: The Asynchronous Function Contract A function should yield false or return false when something asynchronous is going on. When the asynchronous operation is complete, something needs to call async_driver(). Returning false tells the asynchronous driver that it should yield control up to the top-level. Calling async_driver() lets it know to start up again. A function should yield true or return true when the asynchronous driver should continue executing without stopping. A function that does not return anything (or returns undefined) and is not a generator is treated like a function that returned true. Most of the things you will want to do already have helper functions that take care of all of this, so all you need to do is pass their return values through. For example, yo...
...e nsIMsgDBHdrs for the messages that were inserted into the folder. This is used by routines that need to process the messages grouped by the folder they belong to, such as initiating message moves. foldersWithXpcomHdrArrays [getter] Same as foldersWithMsgHdrs but the second element in each sub-list is an nsIMutableArray instead of a JS list. Manipulating messages setRead(aBeRead) setRead(true) marks all the messages in the set as read, setRead(false) marks them as unread. setStarred(aBeStarred) setStarred(true) marks all the messages in the set as starred ("flagged" in IMAP parlance), setStarred(false) makes them not be starred. addTag(aTagKey) Adds the given tag to all the messages in the set. The tag key must correspond to an existing tag. The tag key is not the label, but what ...
...pond to an existing tag. The tag key is not the label, but what is actually stored on the IMAP server. For example, all our default tags are actually things like $label1 and $label2, but that is not what we show to the user. removeTag(aTagKey) Removes the given tag from all the messages in the set. See the addTag notes. setJunk(aBeJunk) Sets the junk score for the messages in the set as junk (true) / not junk (false). This does not involves the bayesian classifier and does not do anything like moving the message to the junk folder. It does, however, send a JunkStatusChanged notification via the nsIMsgFolderNotificationService's itemEvent mechanism. Set manipulation union(aOtherSet) Take the union of this set and the provided other set and return the (new, not modified) result. You sh...
...And 2 more matches
Midas
ommand will set the background color of the document. bold If there is no selection, the insertion point will set bold for subsequently typed characters. If there is a selection and all of the characters are already bold, the bold will be removed. Otherwise, all selected characters will become bold. contentReadOnly This command will make the editor readonly(true)or editable(false). Anticipated usage is for temporarily disabling input while something else is occurring elsewhere in the web page. copy If there is a selection, this command will copy the selection to the clipboard. If there isn't a selection, nothing will happen. note: this command won't work without setting a pref or using signed JS. See: more about security preferences ...
...ommand will set the hilite color of the selection or at the insertion point. It only works with styleWithCSS enabled. increasefontsize This command will add a <big> tag around selection or at insertion point. indent Indent the block where the caret is located. If the caret is inside a list, that item becomes a sub-item one level deeper. insertbronreturn true/false Selects whether pressing return inside a paragraph creates another paragraph or just inserts a <br> tag. inserthorizontalrule null/string (when string is the Line's id) This command will insert a horizontal rule (line) at the insertion point. Does it delete the selection? Yes! inserthtml A string. This command will insert the given html into the <bod...
...n, the insertion point will set strikethrough for subsequently typed characters. If there is a selection and all of the characters are already striked, the strikethrough will be removed. Otherwise, all selected characters will have a line drawn through them. styleWithCSS This command is used for toggling the format of generated content. By default (at least today), this is true. 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. subscript If there is no selection, the insertion point will set subscript for subsequently typed characters. If there is a selection and all of the characters are already subscripted, the subscri...
...And 2 more matches
pkfnc.html
slot is implemented in hardware or software. Syntax #include <pk11func.h> #include <prtypes.h> PRBool PK11_IsHW(PK11SlotInfo *slot); Parameters This function has the following parameter: slot A pointer to a slot info structure. Returns The function returns one of these values: If the slot is implemented in hardware, PR_TRUE. If the slot is implemented in software, PR_FALSE. PK11_IsPresent Finds out whether the token for a slot is available. Syntax #include <pk11func.h> #include <prtypes.h> PRBool PK11_IsPresent(PK11SlotInfo *slot); Parameters This function has the following parameter: slot A pointer to a slot info structure. Returns ...
...t Finds out whether the token for a slot is available. Syntax #include <pk11func.h> #include <prtypes.h> PRBool PK11_IsPresent(PK11SlotInfo *slot); Parameters This function has the following parameter: slot A pointer to a slot info structure. Returns The function returns one of these values: If token is available, PR_TRUE. If token is disabled or missing, PR_FALSE. PK11_IsReadOnly Finds out whether a slot is read-only. Syntax #include <pk11func.h> #include <prtypes.h> PRBool PK11_IsReadOnly(PK11SlotInfo *slot); Parameters This function has the following parameter: slot A pointer to a slot info structure. Returns The function returns...
...PK11_IsReadOnly Finds out whether a slot is read-only. Syntax #include <pk11func.h> #include <prtypes.h> PRBool PK11_IsReadOnly(PK11SlotInfo *slot); Parameters This function has the following parameter: slot A pointer to a slot info structure. Returns The function returns one of these values: If slot is read-only, PR_TRUE. Otherwise, PR_FALSE. PK11_SetPasswordFunc Defines a callback function used by the NSS libraries whenever information protected by a password needs to be retrieved from the key or certificate databases. Syntax #include <pk11func.h> #include <prtypes.h> void PK11_SetPasswordFunc(PK11PasswordFunc func); Parameter This function has the following parameter: fun...
...And 2 more matches
Parser API
rently consists of a single method. Reflect.parse(src[, options]) Coerces src to a string and parses the result as a JavaScript program. By default, the parsing returns a Program object (see below) representing the parsed abstract syntax tree (AST). Additional options may be provided via the options object, which can include any of the following properties: loc Boolean Default: true When loc is true, the parser includes source location information in the returned AST nodes. source String Default: null A description of the input source; typically a filename, path, or URL. This string is not meaningful to the parsing process, but is produced as part of the source location information in the returned AST nodes. line Number Default...
... params: [ Pattern ]; defaults: [ Expression ]; rest: Identifier | null; body: BlockStatement | Expression; generator: boolean; expression: boolean; } A function declaration or expression. The body of the function may be a block statement, or in the case of an expression closure, an expression. Note: Expression closures are SpiderMonkey-specific. If the generator flag is true, the function is a generator function, i.e., contains a yield expression in its body (other than in a nested function). Note: Generators are SpiderMonkey-specific. If the expression flag is true, the function is an expression closure and the body field is an expression. Statements interface Statement <: Node { } Any statement. interface EmptyStatement <: Statement { type: "EmptyStateme...
...nt { type: "ForStatement"; init: VariableDeclaration | Expression | null; test: Expression | null; update: Expression | null; body: Statement; } A for statement. interface ForInStatement <: Statement { type: "ForInStatement"; left: VariableDeclaration | Expression; right: Expression; body: Statement; each: boolean; } A for/in statement, or, if each is true, a for each/in statement. Note: The for each form is SpiderMonkey-specific. interface ForOfStatement <: Statement { type: "ForOfStatement"; left: VariableDeclaration | Expression; right: Expression; body: Statement; } A for/of statement. interface LetStatement <: Statement { type: "LetStatement"; head: [ VariableDeclarator ]; body: Statement; } A let statement. ...
...And 2 more matches
Gecko object attributes
d have posinset="1", and the last item should have a posinset value equal to the setsize. Applied to: listitem, option Exposed in ARIA: aria-posinset setsize If this item is in a group, this indicates the number of items in the group. This is useful when combined with the posinset object attribute. Applied to: listitem, option Exposed in ARIA: aria-setsize Live region attribues atomic true when the entire region should be presented as a whole, when changes within it are considered important enough to automatically present. Applied to: any role Exposed via ARIA: aria-atomic live A hint as to whether changes within the current region or subtree should be automatically presented. Possible values are "off" which is the same as not being set -- this means the region is not live. Oth...
...? See the Live Region Support for more information. event-from-input Was the root cause of this event explicit user input? See the Live Region Support for more information. member-of Points to the root of the atomic container that this object is in. This will always be an ancestor of the current object. See the Live Region Support for more information. Common widget attributes checkable true when the widget is known to behave like a checkbox. Note some widgets which appear to be checkboxes might in fact be cyclers (see "cycles" below). Action 0 is named either "check" or "uncheck". Applied to: STATE_CHECKABLE state datatype WARNING: obsolete, do not use! A qname that refers to an XSD (schema) defined type. For example, a datatype may be xsd:integer. When this is not specified, ...
... an XSD (schema) defined type. For example, a datatype may be xsd:integer. When this is not specified, the default is string, unless the Value interface is exposed, which indicates the type is numeric. For more information please read about schema datatypes. Applied to: any widget that accepts input Exposed via ARIA: aria-datatype Exposed in XForms: from boud instance node datatype draggable true when the accessible object can be grabbed. dropeffect Indicates what functions can be performed when the dragged object is released on the drop target. Refer to aria-dropeffect for the list of possible values. grabbed true when the accessible object has been selected for dragging. haspopup true when the object displays a pop-up menu or window when invoked. Applied to: STATE_HASPOPUP Expos...
...And 2 more matches
Finishing the Component
(NS_CATEGORYMANAGER_CONTRACTID, NS_GET_IID(nsICategoryManager), getter_AddRefs(catman)); if (NS_FAILED(rv)) return rv; char* previous = nsnull; rv = catman->AddCategoryEntry("xpcom-startup", "WebLock", WebLock_ContractID, PR_TRUE, PR_TRUE, &previous); if (previous) nsMemory::Free(previous); rv = catman->AddCategoryEntry("content-policy", "WebLock", WebLock_ContractID, PR_TRUE, PR_TRUE, &previo...
...h would require you to do the parsing yourself, you can compare the nsIURI objects with each other, as in the following section. This ensures that the URLs are canonical before they are compared. Checking the White List The WebLock implementation of the ShouldLoad method starts by extracting the scheme of the incoming nsIURI. If the scheme isn't "http", "https", or "ftp", it immediately returns true, which continues the loading process unblocked. These three are the only kinds of URI that Weblock will try to block. When it has one, it walks the linked list and creates a new nsIURI object for each string URL in the list. From each object, ShouldLoad() extracts the host and compares it to the URI. If they match, the component allows the load to continue by returning true. If these two strings...
... heap allocation will be made for every XPCOM object created. The string comparison with the URL type "http", "https", and "ftp" looks like this: nsEmbedCString scheme; contentLocation->GetScheme(scheme); if (strcmp("http", scheme.get()) != 0 && strcmp("https", scheme.get()) != 0 && strcmp("ftp", scheme.get()) != 0) { // this isn't a type of URI that we deal with. *_retval = PR_TRUE; return NS_OK; } Creating nsIURI Objects To create an nsIURI, use nsIIOService. nsIIOService is the part of the networking library ("necko") that's responsible for kicking off network requests, managing protocols such as http, ftp, or file, and creating nsIURIs. Necko offers tremendous network functionality, but all the WebLock component needs is to create the nsIURI object that can be compa...
...And 2 more matches
Mozilla internal string guide
with nsAString. Since every string derives from nsAString (or nsACString), they all share a simple API. Common read-only methods: .Length() - the number of code units (bytes for 8-bit string classes and char16_ts for 16-bit string classes) in the string. .IsEmpty() - the fastest way of determining if the string has any value. Use this instead of testing string.Length == 0 .Equals(string) - TRUE if the given string has the same value as the current string. Common methods that modify the string: .Assign(string) - Assigns a new value to the string. .Append(string) - Appends a value to the string. .Insert(string, position) - Inserts the given string before the code unit at position. .Truncate(length) - shortens the string to the given length. Complete documentation can be found in...
...ed. Iterators Because Mozilla strings are always a single buffer, iteration over the characters in the string is done using raw pointers: /** * Find whether there is a tab character in `data` */ bool HasTab(const nsAString& data) { const char16_t* cur = data.BeginReading(); const char16_t* end = data.EndReading(); for (; cur < end; ++cur) { if (char16_t('\t') == *cur) return true; } return false; } Note that `end` points to the character after the end of the string buffer. It should never be dereferenced. Writing to a mutable string is also simple: /** * Replace every tab character in `data` with a space. */ void ReplaceTabs(nsAString& data) { char16_t* cur = data.BeginWriting(); char16_t* end = data.EndWriting(); for (; cur < end; ++cur) { if (char16_...
...Length() before BeginWriting() or use the BulkWrite() API described below. Bulk Write BulkWrite() allows capacity-aware cache-friendly low-level writes to the string's buffer. Capacity-aware means that the caller is made aware of how the caller-requested buffer capacity was rounded up to mozjemalloc buckets. This is useful when initially requesting best-case buffer size without yet knowing the true size need. If the data that actually needs to be written is larger than the best-case estimate but still fits within the rounded-up capacity, there is no need to reallocate despite requesting the best-case capacity. Cache-friendly means that the zero terminator for C compatibility is written after the new content of the string has been written, so the result is a forward-only linear write access...
...And 2 more matches
nsIAppShellService
void topLevelWindowIsModal(in nsIXULWindow aWindow, in boolean aModal); Obsolete since Gecko 1.9.1 void unregisterTopLevelWindow(in nsIXULWindow aWindow); Note: Prior to Gecko 8.0, all references to nsIDOMWindow used in this interface were nsIDOMWindowInternal. Attributes Attribute Type Description applicationProvidedHiddenWindow boolean Return true if the application hidden window was provided by the application. If it was not, the default hidden window was used. This will usually be false on all non-mac platforms. Read only. hiddenDOMWindow nsIDOMWindow Return the (singleton) application hidden window, automatically created and maintained by this AppShellService. Read only. hiddenWindow nsIXULWindow Return th...
... Creates the initial state of the application by launching tasks specfied by "general.startup.*" prefs. Note: SIZE_TO_CONTENT may be used for width or height. boolean createStartupState( in long aWindowWidth, in long aWindowHeight ); Parameters aWindowWidth The width to make the initial window(s) opened. aWindowHeight The height to make the initial window(s) opened. Return value true if a window was opened. createTopLevelWindow() This method creates a window, which will be initially invisible. nsIXULWindow createTopLevelWindow( in nsIXULWindow aParent, in nsIURI aUrl, in boolean aShowWindow, in boolean aLoadDefaultPage, in PRUint32 aChromeMask, in long aInitialWidth, in long aInitialHeight, in nsIAppShell aAppShell ); Parameters aParent The parent win...
...ocity One of the e* constants. createWindowlessBrowser() This method creates a browser that does not have a window. If the browser is exited, this windowless browser will not prevent Firefox from exiting. E10s notes: The browser is created in process. To get an out of process element you want to communicate with via message manager, then append a browser element with remote attribute set to true. ...
...And 2 more matches
nsIMacDockSupport
n's icon in the dock. Methods activateApplication() Activates the application, making it the frontmost application. The application should call this to activate itself when one of its dock menu items are selected, since doing so does not automatically activate the application. void activateApplication( in boolean aIgnoreOtherApplications ); Parameters aIgnoreOtherApplications If true, the application is activated regardless of the state of other applications. If false, the application is only activated if other applications are not currently active. About dockMenu By default Firefox adds two menu items to the dock menu. The menu items are "New Window" and "New Private Window". If permanent private browsing mode is enabled then the "New Private Window" menu item is hidden. Th...
...in.document.createElementNS('http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul', 'menuitem'); macMenuItem.setAttribute('label', 'Show Most Recent Window'); macMenuItem.setAttribute('id', 'myMacMenuItem'); macMenuItem.addEventListener('command', function(){ var dockSupport = Cc['@mozilla.org/widget/macdocksupport;1'].getService(Ci.nsIMacDockSupport); dockSupport.activateApplication(true); Services.wm.getMostRecentWindow(null).focus() }) macMenu.appendChild(macMenuItem); var mainPopupSet = win.document.getElementById('mainPopupSet'); mainPopupSet.appendChild(macMenu); let dockMenuElement = macMenu; //document.getElementById("menu_mac_dockmenu");66 let nativeMenu = Cc["@mozilla.org/widget/standalonenativemenu;1"].createInstance(Ci.nsIStandaloneNativeMenu); console.log('dockMen...
...ocument.getElementById("menu_mac_dockmenu");66 let nativeMenu = Cc["@mozilla.org/widget/standalonenativemenu;1"].createInstance(Ci.nsIStandaloneNativeMenu); console.log('dockMenuElement:', dockMenuElement); nativeMenu.init(dockMenuElement); dockSupport.dockMenu = nativeMenu; This replaces the default menu with this one menuitem that says "Show Most Recent Window". Notice the activateApplication(true), if this is not done then Firefox will not be activated. The result of this code is shown below. Notice how the "New Window" and "New Private Window" menuitem's are missing. Therefore, if you would like to add or remove items to the menu it is recommended to manipulate the default menu item which is on the hidden window of Firefox. Note: The hidden window of Firefox (Services.appShel.hiddenDOMW...
...And 2 more matches
nsIMessenger
ssage (if any) using the given character set. void setDocumentCharset(in ACString characterSet); Parameters characterSet The character set to use. saveAs() Save the URL given. void saveAs(in ACString aURI, in boolean aAsFile, in nsIMsgIdentity aIdentity, in AString aMsgFilename); Parameters aURI The URL of the message to save. aAsFile If true a file picker is spawned with the option save the message as HTML, text, or EML. If false, the message is saved as a Template aIdentity The identity to use if saving as a Template. aMsgFilename The filename to use as the default filename if we are saving as a file. openAttachment() Open an attachment. void openAttachment(in ACString contentType, in ACString url, ...
... in ACString messageUri, in boolean isExternalAttachment); Parameters contentType The content type of the attachment. url The url of the attachment. displayName The file name for display purposes. messageUri The url of the message containing the attachment. isExternalAttachment Is the attachment inside a message or saved somewhere externally. If set to true the attachment is opened inside the message pane which in turn should trigger the helper app dialog. Same as just using the openURL() method. saveAttachment() Save an attachment. void saveAttachment(in ACString contentType, in ACString url, in ACString displayName, in ACString messageUri, in boolean isExterna...
... in ACString messageUri, in boolean isExternalAttachment); Parameters contentType The content type of the attachment. url The url of the attachment. displayName The file name for display purposes. messageUri The url of the message containing the attachment. isExternalAttachment Is the attachment inside a message or saved somewhere externally. If set to true the attachment is opened inside the message pane which in turn should trigger the helper app dialog. Same as just using the openURL() method. saveAllAttachments() Launches a filepicker and saves all attachments listed in an array. void saveAllAttachments(in unsigned long count, [array, size_is(count)] in string contentTypeArray, [array, size_...
...And 2 more matches
nsIMsgDBView
to determine if the command is available. void getCommandStatus(in nsMsgViewCommandTypeValue command, out boolean selectable_p, out nsMsgViewCommandCheckStateValue selected_p); Parameters command The nsMsgViewCommandTypeValue to perform. Defined in the interface: nsMsgViewCommandType. Return values selectable_p The state of the command. true if it is enabled. false if it is disabled. selected_p The returned check state of the command. Defined in the interface: nsMsgViewCommandCheckState. This is not used for all commands and will return the notUsed value most of the time. viewNavigate() Change the view to show a particular message. This method will automatically expand the destination thread. void viewNavigate(in nsMsgNavigati...
...d long in MailNewsTypes2.idl. threadIndex The index of the new thread. nsMsgViewIndex is defined as a unsigned long in MailNewsTypes2.idl. navigateStatus() Indicates if the passed motion type is currently valid. boolean navigateStatus(in nsMsgNavigationTypeValue motion); Parameters motion The nsMsgNavigationTypeValue. Defined in ther interface: nsMsgNavigationType. Return values True if the motion is available. False otherwise. getKeyAt() Gets the key for the message at a particular index. nsMsgKey getKeyAt(in nsMsgViewIndex index); Parameters index The index of the message. nsMsgViewIndex is defined as a unsigned long in MailNewsTypes2.idl. Return value The key of the message. nsMsgKey is defined as an unsigned long in MailNewsTypes2.idl. getFolderForViewIndex...
... load. nsMsgViewIndex is defined as a unsigned long in MailNewsTypes2.idl. loadMessageByUrl() Loads a message into the message pane. void loadMessageByUrl(in string aUrl); Parameters aUrl The URL of the message reloadMessage() Reload the currently shown message. void reloadMessage(); reloadMessageWithAllParts() Reload the currently shown message with fetchCompleteMessage set to true. This forces everything to be re-downloaded. void reloadMessageWithAllParts(); selectMsgByKey() Selects a message based on its key. Used by "go to folder" feature and "remember last selected message" feature. If key is not found, nothing is selected. void selectMsgByKey(in nsMsgKey key); Parameters key The Key of the message to load. nsMsgKey is defined as an unsigned long in MailNe...
...And 2 more matches
nsIOutputStream
tream. Forces the output stream to flush() any buffered data. Note: This method may be called more than once, but subsequent calls are ignored. void close(); Parameters None. Exceptions thrown NS_BASE_STREAM_WOULD_BLOCK Indicates that closing the output stream would block the calling thread for an indeterminate amount of time. This exception may only be thrown if isNonBlocking() returns true. flush() This method may be called to instruct the output stream to write out the contents of any internal buffers to a low-level data sink, such as a file on disk. However, the flush method may simply do nothing depending on the implementation of the output stream. void flush(); Parameters None. Exceptions thrown NS_BASE_STREAM_WOULD_BLOCK Indicates that flushing the output stream wo...
...-level data sink, such as a file on disk. However, the flush method may simply do nothing depending on the implementation of the output stream. void flush(); Parameters None. Exceptions thrown NS_BASE_STREAM_WOULD_BLOCK Indicates that flushing the output stream would block the calling thread for an indeterminate amount of time. This exception may only be thrown if isNonBlocking() returns true. isNonBlocking() Note: Writing to a blocking output stream will block the calling thread until all given data can be consumed by the stream. Note: A non-blocking output stream may implement nsIAsyncOutputStream to provide consumers with a way to wait for the stream to accept more data once its write() method is unable to accept any data without blocking. boolean isNonBlocking(); Parameters...
...te: Writing to a blocking output stream will block the calling thread until all given data can be consumed by the stream. Note: A non-blocking output stream may implement nsIAsyncOutputStream to provide consumers with a way to wait for the stream to accept more data once its write() method is unable to accept any data without blocking. boolean isNonBlocking(); Parameters None. Return value true if stream is non-blocking. Exceptions thrown NS_BASE_STREAM_WOULD_BLOCK A non-blocking stream may throw this exception when written to if space for the data is not immediately available. write() This method copies data from a buffer into the stream. Note: Though this method is scriptable, JavaScript code must only pass an ASCII character string as the aBuf parameter. C++ code may however...
...And 2 more matches
nsIProcess
ng count); void runwAsync([array, size_is(count)] in wstring args, in unsigned long count, [optional] in nsIObserver observer, [optional] in boolean holdWeak); Attributes Attribute Type Description exitValue long The value returned by the process upon exit. This is only valid after the process has exited. Read only. isRunning boolean true if the process is running, otherwise false. Only accurate if the process was run with blocking disabled. Read only. location nsIFile The location of the executable file on disk. Read only. Gecko 1.9.1 note This attribute is no longer implemented as of Gecko 1.9.1, and is removed entirely in Gecko 1.9.2. pid unsigned long The process ID of the pro...
...n Windows or Mac OS X. Now it does. void kill(); Parameters None. run() Starts executing the process. Gecko 1.9.1 note Prior to Gecko 1.9.1 (Firefox 3.5), this method returned the process ID of the newly executing process. It no longer returns a value. void run( in boolean blocking, [array, size_is(count)] in string args, in unsigned long count ); Parameters blocking If true, this method will block until the process terminates; if false, the method returns immediately. args An array of count arguments, using the native character set, to be passed to the executable on its command line. count The number of arguments in the args array. runAsync() Asynchronously runs the process with which the object was initialized, optionally calling an observer when the process...
...using the native character set. This array must have count entries. count The number of arguments passed in the args array. observer Optional An observer that will be notified when the process exits. The observer will receive this nsIProcess instance as the subject and "process-finished" or "process-failed" as the topic. The observer will be notified on the main thread. holdWeak Optional If true, a weak reference is used to hold the observer. runw() Executes the file this object was initialized with. void runw( in boolean blocking, [array, size_is(count)] in wstring args, in unsigned long count ); Parameters blocking If true, this method will block until the process terminates; if false, the method returns immediately. args An array of count arguments, using UTF-16, ...
...And 2 more matches
nsISHistoryListener
HistoryPurge(in long aNumEntries); boolean OnHistoryReload(in nsIURI aReloadURI, in unsigned long aReloadFlags); Methods OnHistoryGoBack() Called when navigating to a previous session history entry, for example due to an nsIWebNavigation.goBack() call. boolean OnHistoryGoBack( in nsIURI aBackURI ); Parameters aBackURI The URI of the session history entry being navigated to. ...
...OnHistoryGotoIndex() Called when navigating to a session history entry by index, for example, when nsIWebNavigation.gotoIndex() is called. boolean OnHistoryGotoIndex( in long aIndex, in nsIURI aGotoURI ); Parameters aIndex The index in session history of the entry to be loaded. ...
...ration to proceed or false to cancel it. OnHistoryGotoIndex() Called when navigating to a session history entry by index, for example, when nsIWebNavigation.gotoIndex() is called. boolean OnHistoryGotoIndex( in long aIndex, in nsIURI aGotoURI ); Parameters aIndex The index in session history of the entry to be loaded. aGotoURI The URI of the session history entry to be loaded. Return value true to allow the operation to proceed or false to cancel it. OnHistoryNewEntry() Called when a new document is added to session history. New documents are added to session history by the docshell when new pages are loaded in a frame or content area; for example by calling nsIWebNavigation.loadURI(). Note: You can't cancel this operation. void OnHistoryNewEntry( in nsIURI aNewURI ); Parameters aNe...
...And 2 more matches
Type conversion
)(); var someCFunction = library.declare("someCFunction", ctypes.default_abi, ctypes.void_t, ctypes.char.ptr); someCFunction(buffer); // here ctypes.char.array(10)() is converted to ctypes.char.ptr type Implicit conversion can be tested in the following way: var myStruct = ctypes.StructType("myStructType", [ { "v": ctypes.bool } ])(); myStruct.v = 1; console.log(myStruct.v.toString()); // 'true' Boolean type Target Type Source Converted value ctypes.bool JS boolean src JS number (0 or 1) if src == 0: false if src == 1: true var myStruct = ctypes.StructType("myStructType", [ { "v": ctypes.bool } ])(); myStruct.v = true; console.log(myStruct.v.toString()); // 'true' myStruct.v = false; console.log(myStruct.v.toString()); // 'f...
...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; // throws Error myStruct.v = "a"; // throws Error Integer types Target Type Source Converted value ctypes.char16_t JS string (only if its length == 1) src.charCodeAt(0) any integer types JS number (only if fits to the size) src JS boolea...
...0; console.log(myStruct.v.toString()); // 'false' myStruct.v = 10; // throws Error myStruct.v = "a"; // throws Error Integer types Target Type Source Converted value ctypes.char16_t JS string (only if its length == 1) src.charCodeAt(0) any integer types JS number (only if fits to the size) src JS boolean if src == true: 1 if src == false: 0 var myStruct = ctypes.StructType("myStructType", [ { "v": ctypes.char16_t } ])(); myStruct.v = 0x41; console.log(myStruct.v.toString()); // "A" myStruct.v = true; console.log(myStruct.v.toString()); // "\x01" myStruct.v = "X"; console.log(myStruct.v.toString()); // "X" myStruct.v = "XX"; // throws Error var myStruct = ctypes.StructType("mySt...
...And 2 more matches
Browser Console - Firefox Developer Tools
ndow scope, the Browser Console executes them in the scope of the browser's chrome window. This means you can interact with all the browser's tabs using the gBrowser global, and even with the XUL used to specify the browser's user interface. NB: The Browser Console command line (to execute JavaScript expressions) is disabled by default. To enable it set the devtools.chrome.enabled preference to true in about:config, or set the "Enable browser chrome and add-on debugging toolboxes" (Firefox 40 and later) option in the developer tool settings. Opening the Browser Console You can open the Browser Console in one of two ways: from the menu: select "Browser Console" from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on macOS). from the keyb...
...sole. The module is available at Mozilla DXR. We see we can not only access the Browser Console but also Web Console. Here is an example on how to clear the contents of the Browser console: Components.utils.import("resource://devtools/shared/Loader.jsm"); var HUDService = devtools.require("devtools/client/webconsole/hudservice"); var hud = HUDService.getBrowserConsole(); hud.jsterm.clearOutput(true); If you would like to access the content document of the Browser Console this can be done with the HUDService. This example here makes it so that when you mouse over the "Clear" button it will clear the Browser Console: Components.utils.import("resource://devtools/shared/Loader.jsm"); var HUDService = devtools.require("devtools/client/webconsole/hudservice"); var hud = HUDService.getBrowserCo...
...Here's an example add-on that just logs an error when the user clicks a widget: widget = require("sdk/widget").Widget({ id: "an-error-happened", label: "Error!", width: 40, content: "Error!", onClick: logError }); function logError() { console.error("something went wrong!"); }...
...And 2 more matches
Using the CSS Typed Object Model - Web APIs
btnWidth = allComputedStyles.get('width') console.log( btnWidth ); // CSSMathSum console.log( btnWidth.values ); // CSSNumericArray {0: CSSUnitValue, 1: CSSUnitValue, length: 2} console.log( btnWidth.operator ); // 'sum' // CSSTransformValue let transform = allComputedStyles.get('transform'); console.log( transform ); // CSSTransformValue {0: CSSScale, 1: CSSTranslate, length: 2, is2D: true} console.log( transform.length ); // 1 console.log( transform[0] ); // CSSScale {x: CSSUnitValue, y: CSSUnitValue, z: CSSUnitValue, is2D: true} console.log( transform[0].x ); // CSSUnitValue {value: 0.95, unit: "number"} console.log( transform[0].y ); // CSSUnitValue {value: 0.95, unit: "number"} console.log( transform[0].z ); // CSSUnitValue {value: 1, unit: "number"} console.log( tran...
...sform.length ); // 1 console.log( transform[0] ); // CSSScale {x: CSSUnitValue, y: CSSUnitValue, z: CSSUnitValue, is2D: true} console.log( transform[0].x ); // CSSUnitValue {value: 0.95, unit: "number"} console.log( transform[0].y ); // CSSUnitValue {value: 0.95, unit: "number"} console.log( transform[0].z ); // CSSUnitValue {value: 1, unit: "number"} console.log( transform.is2D ); // true // CSSImageValue let bgImage = allComputedStyles.get('background-image'); console.log( bgImage ); // CSSImageValue console.log( bgImage.toString() ); // url("https://mdn.mozillademos.org/files/16793/magicwand.png") // CSSUnparsedValue let unit = allComputedStyles.get('--unit'); console.log( unit ) // let parsedUnit = CSSNumericValue.parse( unit ); console.log( parsedUnit ); conso...
...alue, 1: CSSUnitValue, length: 2} console.log( btnWidth.operator ); // 'sum' CSSTransformValue with CSSScale The display: inline-block; also enables transforming. In our CSS we have transform: scale(0.95);, which is a transform function. ...
...And 2 more matches
Document - Web APIs
Web › API › Document
DOM implementation associated with the current document. Document.lastStyleSheetSetRead only Returns the name of the style sheet set that was last enabled. Has the value null until the style sheet is changed by setting the value of selectedStyleSheetSet. Document.linksRead only Returns a list of all the hyperlinks in the document. Document.mozSyntheticDocument Returns a Boolean that is true only if this document is synthetic, such as a standalone image, video, audio file, or the like. Document.pluginsRead only Returns a list of the available plugins. Document.featurePolicy Read only Returns the FeaturePolicy interface which provides a simple API for introspecting the feature policies applied to a specific document. Document.preferredStyleSheetSetRead only Returns the prefe...
...s an ordered list of the applets within a document. Document.bgColor Gets/sets the background color of the current document. Document.charset Read only Alias of Document.characterSet. Use this property instead. Document.domConfig Should return a DOMConfiguration object. Document.fgColor Gets/sets the foreground color, or text color, of the current document. Document.fullscreen true when the document is in full-screen mode. Document.height Gets/sets the height of the current document. Document.inputEncoding Read only Alias of Document.characterSet. Use this property instead. Document.linkColor Gets/sets the color of hyperlinks in the document. Document.rootElement Like Document.documentElement, but only for <svg> root elements. Use this property instead. D...
... document. Document.rootElement Like Document.documentElement, but only for <svg> root elements. Use this property instead. Document.vlinkColor Gets/sets the color of visited hyperlinks. Document.width Returns the width of the current document. Document.xmlEncoding Returns the encoding as determined by the XML declaration. 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. Document.xmlVersion Obsolete since Gecko 10 Returns the version number as specified in the XML declaration or "1.0" if the declaration is absent. Methods This interface also inherits from the Node and EventTarget interfaces. Document.adoptNode() A...
...And 2 more matches
Element: mousedown event - Web APIs
s. Its functionality is simple: the thickness of the line is set to 1, and the color is always black. When the page loads, constants myPics and context are created to store a reference to the canvas and the 2d context we will use to draw. Drawing begins when the mousedown event fires. First we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isDrawing to true. As the mouse moves over the page, the mousemove event fires. If isDrawing is true, the event handler calls the drawLine function to draw a line from the stored x and y values to the current location. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by sett...
...e() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mousedown, mousemove, and mouseup myPics.addEventListener('mousedown', e => { x = e.offsetX; y = e.offs...
...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. ...
...And 2 more matches
Element: mousemove event - Web APIs
s. Its functionality is simple: the thickness of the line is set to 1, and the color is always black. When the page loads, constants myPics and context are created to store a reference to the canvas and the 2d context we will use to draw. Drawing begins when the mousedown event fires. First we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isDrawing to true. As the mouse moves over the page, the mousemove event fires. If isDrawing is true, the event handler calls the drawLine function to draw a line from the stored x and y values to the current location. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by sett...
...e() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mousedown, mousemove, and mouseup myPics.addEventListener('mousedown', e => { x = e.offsetX; y = e.offs...
...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. ...
...And 2 more matches
Element: mouseup event - Web APIs
s. Its functionality is simple: the thickness of the line is set to 1, and the color is always black. When the page loads, constants myPics and context are created to store a reference to the canvas and the 2d context we will use to draw. Drawing begins when the mousedown event fires. First we store the x and y coordinates of the mouse pointer in the variables x and y, and then set isDrawing to true. As the mouse moves over the page, the mousemove event fires. If isDrawing is true, the event handler calls the drawLine function to draw a line from the stored x and y values to the current location. When the drawLine() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by sett...
...e() function returns, we adjust the coordinates and then save them in x and y. The mouseup event draws the final line segment, sets x and y to 0, and stops further drawing by setting isDrawing to false. HTML <h1>Drawing with mouse events</h1> <canvas id="myPics" width="560" height="360"></canvas> CSS canvas { border: 1px solid black; width: 560px; height: 360px; } JavaScript // When true, moving the mouse draws on the canvas let isDrawing = false; let x = 0; let y = 0; const myPics = document.getElementById('myPics'); const context = myPics.getContext('2d'); // event.offsetX, event.offsetY gives the (x,y) offset from the edge of the canvas. // Add the event listeners for mousedown, mousemove, and mouseup myPics.addEventListener('mousedown', e => { x = e.offsetX; y = e.offs...
...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. ...
...And 2 more matches
EventTarget.removeEventListener() - Web APIs
? While addEventListener() will let you add the same listener more than once for the same type if the options are different, the only option removeEventListener() checks is the capture/useCapture flag. Its value must match for removeEventListener() to match, but the other values don't. 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. The second succeeds, since useCapture matches up. Now consider this: element.addEventListener("mous...
...alls 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. The second succeeds, since useCapture matches up. Now consider this: element.addEventListener("mousedown", handleMouseDown, { passive: true }); Here, we specify an options object in which passive is set to true, while the other options are left to the default value of false. Now look at each of these calls to removeEventListener() in turn. Any of them in which capture or useCapture is true fail; all others succeed. Only the capture setting matters to removeEventListener(). element.removeEventListener("mousedown", handleMouseDown,...
...we specify an options object in which passive is set to true, while the other options are left to the default value of false. Now look at each of these calls to removeEventListener() in turn. Any of them in which capture or useCapture is true fail; all others succeed. Only the capture setting matters to removeEventListener(). ...
...And 2 more matches
Ajax navigation example - Web APIs
e the following files (or git clone https://github.com/giabao/mdn-ajax-nav-example.git ): Note: For fully integrating the <form> elements within this mechanism, please take a look at the paragraph Submitting forms and uploading files. 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>" . $page_title . "</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>This paragraph is shown only when the navigation starts from <strong>first_page.php</strong>.</p> <div id="ajax-content"> <?php } ?> <p>This is the content of ...
...$page_title . "</title>"; ?> </head> <body> <?php include "include/before_content.php"; ?> <p>This paragraph is shown only when the navigation starts from <strong>second_page.php</strong>.</p> <div id="ajax-content"> <?php } ?> <p>This is the content of...
... } } closeReq(); } function filterURL (sURL, sViewMode) { return sURL.replace(rSearch, "") + ("?" + sURL.replace(rHost, "&").replace(rView, sViewMode ? ...
...And 2 more matches
KeyboardEvent - Web APIs
from. The NumLock key does not fall into this group and is always encoded with the location DOM_KEY_LOCATION_STANDARD. Examples include the digits on the numeric keypad, the keypad's Enter key, and the decimal point on the keypad. Properties This interface also inherits properties of its parents, UIEvent and Event. KeyboardEvent.altKey Read only Returns a Boolean that is true if the Alt ( Option or ? on OS X) key was active when the key event was generated. KeyboardEvent.code Read only Returns a DOMString with the code value of the physical key represented by the event. Warning: This ignores the user's keyboard layout, so that if the user presses the key at the "Y" position in a QWERTY keyboard layout (near the middle of the row above the home row), this will alwa...
...es the key at the "Y" position in a QWERTY keyboard layout (near the middle of the row above the home row), this will always return "KeyY", even if the user has a QWERTZ keyboard (which would mean the user expects a "Z" and all the other properties would indicate a "Z") or a Dvorak keyboard layout (where the user would expect an "F"). KeyboardEvent.ctrlKey Read only Returns a Boolean that is true if the Ctrl key was active when the key event was generated. KeyboardEvent.isComposing Read only Returns a Boolean that is true if the event is fired between after compositionstart and before compositionend. KeyboardEvent.key Read only Returns a DOMString representing the key value of the key represented by the event. KeyboardEvent.locale Read only Returns a DOMString representing a loca...
...he locale of the data being entered. A user may be using one keyboard layout while typing text in a different language. KeyboardEvent.location Read only Returns a Number representing the location of the key on the keyboard or other input device. A list of the constants identifying the locations is shown above in Keyboard locations. ...
...And 2 more matches
MediaStreamTrack - Web APIs
traints, and settings to learn how to correctly work with constrainable properties. Not doing so correctly will result in your code being unreliable. MediaStreamTrack.contentHint A string that may be used by the web application to provide a hint as to what type of content the track contains to guide how it should be treated by API consumers. 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. If the track has been disconnected, this value can be changed but has no more effect. Note: You can implement standard "mute" functionality by setting enabled to false. The muted property refers to a condition in which th...
...ffect. Note: You can implement standard "mute" functionality by setting enabled to false. The muted property refers to a condition in which there's no media because of a technical issue. MediaStreamTrack.id Read only Returns a DOMString containing a unique identifier (GUID) for the track; it is generated by the browser. MediaStreamTrack.isolated Read only Returns a Boolean value which is true if the track is isolated; that is, the track cannot be accessed by the document that owns the MediaStreamTrack. This happens when the peerIdentity property is set, or if the track comes from a cross-origin source. MediaStreamTrack.kind Read only Returns a DOMString set to "audio" if the track is an audio track and to "video", if it is a video track. It doesn't change if the track is deassociat...
...d is empty as long as no source has been connected. When the track is deassociated from its source, the label is not changed. MediaStreamTrack.muted Read only Returns a Boolean value indicating whether the track is unable to provide media data due to a technical issue. Note: You can implement standard "mute" functionality by setting enabled to false, and unmute the media by setting it back to true again. MediaStreamTrack.readonly Read only Returns a Boolean value with a value of true if the track is readonly (such a video file source or a camera that settings can't be modified), false otherwise. MediaStreamTrack.readyState Read only Returns an enumerated value giving the status of the track. This will be one of the following values: "live" which indicates that an input is conne...
...And 2 more matches
MouseEvent - Web APIs
font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">MouseEvent</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructor MouseEvent() Creates a MouseEvent object. Properties This interface also inherits properties of its parents, UIEvent and Event. MouseEvent.altKey Read only Returns true if the alt key was down when the mouse event was fired. MouseEvent.button Read only The button number that was pressed (if applicable) when the mouse event was fired. MouseEvent.buttons Read only The buttons being depressed (if any) when the mouse event was fired. MouseEvent.clientX Read only The X coordinate of the mouse pointer in local (DOM content) coordinates. MouseEvent.clientY R...
...f applicable) when the mouse event was fired. MouseEvent.buttons Read only The buttons being depressed (if any) when the mouse event was fired. MouseEvent.clientX Read only The X coordinate of the mouse pointer in local (DOM content) coordinates. MouseEvent.clientY Read only The Y coordinate of the mouse pointer in local (DOM content) coordinates. MouseEvent.ctrlKey Read only Returns true if the control key was down when the mouse event was fired. MouseEvent.metaKey Read only Returns true if the meta key was down when the mouse event was fired. MouseEvent.movementX Read only The X coordinate of the mouse pointer relative to the position of the last mousemove event. MouseEvent.movementY Read only The Y coordinate of the mouse pointer relative to the position of the last mo...
... the event. If no hit region is affected, null is returned. MouseEvent.relatedTarget Read only The secondary target for the event, if there is one. MouseEvent.screenX Read only The X coordinate of the mouse pointer in global (screen) coordinates. MouseEvent.screenY Read only The Y coordinate of the mouse pointer in global (screen) coordinates. MouseEvent.shiftKey Read only Returns true if the shift key was down when the mouse event was fired. MouseEvent.which Read only The button being pressed when the mouse event was fired. MouseEvent.mozPressure Read only The amount of pressure applied to a touch or tablet device when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure). Instead of using this deprecated (and non-standar...
...And 2 more matches
MutationObserverInit.attributeFilter - Web APIs
The MutationObserverInit dictionary's optional attributeFilter property is an array of strings specifying the names of the attributes whose values are to be monitored for changes. If this property is specified, there's no need to also set attributes to true, as it's implied. If the attributes permission is true but no attributeFilter is included in the options object, all attributes' values are watched for changes. Syntax var options = { attributeFilter: [ "list", "of", "attribute", "names" ] } Value An array of DOMString objects, each specifying the name of one attribute whose value is to be monitored for changes. There is no default value. If this property exists on the options object when the MutationObserver() constructor is used to create a new MutationObserver, attribute monito...
...of", "attribute", "names" ] } Value An array of DOMString objects, each specifying the name of one attribute whose value is to be monitored for changes. There is no default value. If this property exists on the options object when the MutationObserver() constructor is used to create a new MutationObserver, attribute monitoring is enabled regardless of whether or not the attributes property is true. Example In this example, a Mutation Observer is set up to watch for changes to the status and username attributes in any elements contained within a subtree that displays the names of users in a chat room. This lets the code, for example, reflect changes to users' nicknames, or to mark them as away from keyboard (AFK) or offline. function callback(mutationList) { mutationList.forEach(functi...
...For any items representing an attribute change (which can be detected by the value of MutationRecord.type being "attributes"), we use the attribute's name, obtained using MutationRecord.attributeName, to identify the ty...
...And 2 more matches
MutationObserverInit - Web APIs
The MutationObserverInit dictionary describes the configuration of a mutation observer. As such, it's primarily used as the type of the options parameter on the MutationObserver.observe() method. Properties At a minimum, one of childList, attributes, and/or characterData must be true when you call observe(). Otherwise, a TypeError exception will be thrown. subtree Optional Set to true to extend monitoring to the entire subtree of nodes rooted at target. ...
...Data must be true when you call observe(). Otherwise, a TypeError exception will be thrown. subtree Optional Set to true to extend monitoring to the entire subtree of nodes rooted at target. All of the other MutationObserverInit properties are then extended to all of the nodes in the subtree instead of applying solely to the target node. The default value is false. childList Optional Set to true to monitor the target node (and, if subtree is true, its descendants) for the addition of new child nodes or removal of existing child nodes. The default value is false. attributes Optional Set to true to watch for changes to the value of attributes on the node or nodes being monitored. ...
... solely to the target node. The default value is false. childList Optional Set to true to monitor the target node (and, if subtree is true, its descendants) for the addition of new child nodes or removal of existing child nodes. The default value is false. attributes Optional Set to true to watch for changes to the value of attributes on the node or nodes being monitored. The default value is true if either of attributeFilter or attributeOldValue is specified, otherwise the default value is false. attributeFilter Optional An array of specific attribute names to be monitored. If this property isn't included, changes to all attributes cause mutation notifications. ...
...And 2 more matches
PublicKeyCredentialCreationOptions.extensions - Web APIs
o support any other extension in future Extension identifier Type Description authnSel Array of BufferSource Authenticator selection. Restricts the list of authenticator models which may be used. If no matching authenticator is available, the credential is still generated with another available authenticator. exts Boolean Supported extensions. If true, the client outputs an array of strings containing the extensions which are supported by the authenticator. uvi Boolean User verification index. If true, the client outputs an ArrayBuffer which contains a value uniquely identifying a user verification data record. In other words, this may be used server side to check if the current operation is based on the same biometric data that...
...ch are supported by the authenticator. uvi Boolean User verification index. If true, the client outputs an ArrayBuffer which contains a value uniquely identifying a user verification data record. In other words, this may be used server side to check if the current operation is based on the same biometric data that the previous authentication. loc Boolean Location. If true, the client outputs a Coordinates object representing the geolocation of the authenticator. uvm Boolean User verification method. If true, the client outputs an array of arrays with 3 values containing information about how the user was verified (e.g. fingerprint, pin, pattern), how the key is protected, how the matcher (tool used for the authentication operation) is protected. ...
...ingerprint, pin, pattern), how the key is protected, how the matcher (tool used for the authentication operation) is protected. biometricPerfBounds Object with two numerical properties: FAR and FRR Biometric authenticator performance bounds. The client must not use any authenticator with false acceptance rate (FAR) and false rejection rate (FRR) below the inputs. ...
...And 2 more matches
format - Web APIs
y of SVGGlyphRefElement property. If the font is in one of the formats listed in CSS2([CSS2], section15.3.5), then its value is the corresponding <string> parameter of the font. Syntax string = myGlyph.format; myGlyph.format = string; Value The format values listed below are taken from CSS2([CSS2], section15.3.5). ...
...fElement property. If the font is in one of the formats listed in CSS2([CSS2], section15.3.5), then its value is the corresponding <string> parameter of the font. Syntax string = myGlyph.format; myGlyph.format = string; Value The format values listed below are taken from CSS2([CSS2], section15.3.5). ...
... Syntax string = myGlyph.format; myGlyph.format = string; Value The format values listed below are taken from CSS2([CSS2], section15.3.5). ...
...And 2 more matches
Screen Capture API - Web APIs
ackConstraints.displaySurface A ConstrainDOMString indicating what type of display surface is to be captured. The value is one of application, browser, monitor, or window. MediaTrackConstraints.logicalSurface Indicates whether or not the video in the stream represents a logical display surface (that is, one which may not be entirely visible onscreen, or may be completely offscreen). A value of true indicates a logical display surface is to be captured. MediaTrackSettings MediaTrackSettings.cursor A string which indicates whether or not the display surface currently being captured includes the mouse cursor, and if so, whether it's only visible while the mouse is in motion or if it's always visible. The value is one of always, motion, or never. MediaTrackSettings.displaySurface A stri...
...ludes the mouse cursor, and if so, whether it's only visible while the mouse is in motion or if it's always visible. The value is one of always, motion, or never. MediaTrackSettings.displaySurface A string indicating what type of display surface is currently being captured. The value is one of application, browser, monitor, or window. ...
...Surface A string indicating what type of display surface is currently being captured. The value is one of application, browser, monitor, or window. MediaTrackSettings.logicalSurface A Boolean value which is true if the video being captured doesn't directly correspond to a single onscreen display area. MediaTrackSupportedConstraints MediaTrackSupportedConstraints.cursor A Boolean which is true if the user agent and device support the MediaTrackConstraints.cursor constraint. ...
...And 2 more matches
SubtleCrypto.exportKey() - Web APIs
Keys can be exported in several formats: see Supported formats in the SubtleCrypto.importKey() page for details. Keys are not exported in an encrypted format: to encrypt keys when exporting them use the SubtleCrypto.wrapKey() API instead. ...
...xportKey( "raw", key ); const exportedKeyBuffer = new Uint8Array(exported); const exportKeyOutput = document.querySelector(".exported-key"); exportKeyOutput.textContent = `[${exportedKeyBuffer}]`; } /* Generate an encrypt/decrypt secret key, then set up an event listener on the "Export" button. */ window.crypto.subtle.generateKey( { name: "AES-GCM", length: 256, }, true, ["encrypt", "decrypt"] ).then((key) => { const exportButton = document.querySelector(".raw"); exportButton.addEventListener("click", () => { exportCryptoKey(key); }); }); PKCS #8 export This example exports an RSA private signing key as a PKCS #8 object. The exported key is then PEM-encoded. See the complete code on GitHub. /* Convert an ArrayBuffer into a string from https://de...
...(".exported-key"); exportKeyOutput.textContent = pemExported; } /* Generate a sign/verify key pair, then set up an event listener on the "Export" button. */ window.crypto.subtle.generateKey( { name: "RSA-PSS", // Consider using a 4096-bit key for systems that require long-term security modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256", }, true, ["sign", "verify"] ).then((keyPair) => { const exportButton = document.querySelector(".pkcs8"); exportButton.addEventListener("click", () => { exportCryptoKey(keyPair.privateKey); }); }); SubjectPublicKeyInfo export This example exports an RSA public encryption key as a PEM-encoded SubjectPublicKeyInfo object. See the complete code on GitHub. /* Convert an ArrayBuffer into a str...
...And 2 more matches
SubtleCrypto.importKey() - Web APIs
ort or export RSA or Elliptic Curve public or private keys, as well as AES and HMAC secret keys. JSON Web Key format is defined in RFC 7517. It describes a way to represent public, private, and secret keys as JSON objects. A JSON Web Key looks something like this (this is an EC private key): { "crv": "P-384", "d": "wouCtU7Nw4E8_7n5C1-xBjB4xqSb_liZhYMsy8MGgxUny6Q8NCoH9xSiviwLFfK_", "ext": true, "key_ops": ["sign"], "kty": "EC", "x": "SzrRXmyI8VWFJg1dPUNbFcc9jZvjZEfH7ulKI1UkXAltd7RGWrcfFxqyGPcwu6AQ", "y": "hHUag3OvDzEr0uUQND4PXHQTXP5IDGdYhJhL-WLKjnGjQAw0rNGy5V29-aV-yseW" }; Examples Note: You can try the working examples on GitHub. Raw import This example imports an AES key from an ArrayBuffer containing the bytes to use. See the complete code on GitHub. const rawKey = wi...
...b. const rawKey = window.crypto.getRandomValues(new Uint8Array(16)); /* Import an AES secret key from an ArrayBuffer containing the raw bytes. Takes an ArrayBuffer string containing the bytes, and returns a Promise that will resolve to a CryptoKey representing the secret key. */ function importSecretKey(rawKey) { return window.crypto.subtle.importKey( "raw", rawKey, "AES-GCM", true, ["encrypt", "decrypt"] ); } PKCS #8 import This example imports an RSA private signing key from a PEM-encoded PKCS #8 object. See the complete code on GitHub. /* Convert a string into an ArrayBuffer from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String */ function str2ab(str) { const buf = new ArrayBuffer(str.length); const bufView = ne...
...See the complete code on GitHub. // from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String function str2ab(str) { const buf = new ArrayBuffer(str.length); const bufView = new Uint8Array(buf...
...And 2 more matches
WebGL2RenderingContext - Web APIs
cifies a list of color buffers to be drawn into. WebGL2RenderingContext.clearBuffer[fiuv]() Clears buffers from the currently bound framebuffer. Query objects Methods for working with WebGLQuery objects. WebGL2RenderingContext.createQuery() Creates a new WebGLQuery object. WebGL2RenderingContext.deleteQuery() Deletes a given WebGLQuery object. WebGL2RenderingContext.isQuery() Returns true if a given object is a valid WebGLQuery object. WebGL2RenderingContext.beginQuery() Begins an asynchronous query. WebGL2RenderingContext.endQuery() Marks the end of an asynchronous query. WebGL2RenderingContext.getQuery() Returns a WebGLQuery object for a given target. WebGL2RenderingContext.getQueryParameter() Returns information about a query. Sampler objects WebGL2RenderingContext...
...a given target. WebGL2RenderingContext.getQueryParameter() Returns information about a query. Sampler objects WebGL2RenderingContext.createSampler() Creates a new WebGLSampler object. WebGL2RenderingContext.deleteSampler() Deletes a given WebGLSampler object. WebGL2RenderingContext.bindSampler() Binds a given WebGLSampler to a texture unit. ...
... WebGL2RenderingContext.deleteSync() Deletes a given WebGLSync object. WebGL2RenderingContext.clientWaitSync() Blocks and waits for a WebGLSync object to become signaled or a given timeout to be passed. ...
...And 2 more matches
Window.customElements - Web APIs
Specification Specification Status Comment HTML Living StandardThe definition of 'window.customElements' in that specification. Living Standard Initial definition. Browser compatibility The compatibility table in this page is generated from structured data. If you'd like to cont...
...To change preferences in Firefox, visit about:config.IE No...
...Disabled Disabled From version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.customelements.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config. No support ? -- 59Disabled Disabled Until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to true) and the dom.webcomponents.customelements.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 41Safari Full support 10.1WebView Android Full support ...
...And 2 more matches
HTML in XMLHttpRequest - Web APIs
u try to set responseType of an XMLHttpRequest object after it is opened as "sync". This throws an error in the browsers that implement the feature and works on others. function HTMLinXHR() { if (!window.XMLHttpRequest) return false; var req = new window.XMLHttpRequest(); req.open('GET', window.location.href, false); try { req.responseType = 'document'; } catch(e) { return true; } return false; } View on JSFiddle This method is synchronous, does not rely on external assets though it may not be as reliable as method 2 described below since it does not check the actual feature but an indication of that feature. Method 2 There are two challenges to detecting exactly if a browser supports HTML parsing in XMLHttpRequest. First, the detection result is obtained asyn...
...e file is named detect.html, the following function can be used for detecting HTML parsing support: function detectHtmlInXhr(callback) { if (!window.XMLHttpRequest) { window.setTimeout(function() { callback(false); }, 0); return; } var done = false; var xhr = new window.XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && !done) { done = true; callback(!!(this.responseXML && this.responseXML.title && this.responseXML.title == "&&<")); } } xhr.onabort = xhr.onerror = function() { if (!done) { done = true; callback(false); } } try { xhr.open("GET", "detect.html"); xhr.responseType = "document"; xhr.send(); } catch (e) { window.setTimeout(function() { if (!done) { done...
... View on JSFiddle Character encoding If the character encoding is declared in the HTTP Content-Type header, that character encoding is used. Failing...
...And 2 more matches
ARIA: checkbox role - Accessibility
l the functionality required: <input type="checkbox" id="chk1-label"> <label for="chk1-label">Remember my preferences</label> Description The native HTML checkbox form control can only have two checked states ("checked" or "not checked"), with an indeterminate state settable via JavaScript. Similarly, an element with role="checkbox" can expose three states through the aria-checked attribute: true, false, or mixed. Since a checkbox is an interactive control, it must be focusable and keyboard accessible. If the role is applied to a non-focusable element, use the tabindex attribute to change this. The expected keyboard shortcut for activating a checkbox is the Space key. The developer is required to change the value of the aria-checked attribute dynamically when the checkbox is activated. ...
...bute to change this. The expected keyboard shortcut for activating a checkbox is the Space key. The developer is required to change the value of the aria-checked attribute dynamically when the checkbox is activated. Associated WAI-ARIA Roles, States, and Properties aria-checked The value of aria-checked defines the state of a checkbox. 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. Keyboard interactions Key Function Space Activates the checkbox Required JavaScript Required event handler...
...andle the checked or unchecked status of the element. ...
...And 2 more matches
Basic form hints - Accessibility
ARIA provides the aria-describedby attribute to directly associate the description with the control. The example below shows a <button> element that is described by a sentence in a separate <div> ele...
...red property can be applied to a form element, to indicate to an AT that it is required to complete the form. The aria-invalid state can be programmatically applied, to indicate to an AT which data fields have incorrect data, so that the user knows they have entered invalid data. The example below shows a simple form with three fields. On lines 4 and 12, the aria-required attributes are set to true (in addition to the asterisks next to the labels), indicating that the name and email fields are required. The second part of the example, a snippet of JavaScript validates the email format, and sets the aria-invalid attribute of the email field (line 12 of the HTML) according to the result (in addition to changing the presentation of the element). <form> <div> <label for="name">* Name:</l...
... the name and email fields are required. The second part of the example, a snippet of JavaScript validates the email format, and sets the aria-invalid attribute of the email field (line 12 of the HTML) according to the result (in addition to changing the presentation of the element). ...
...And 2 more matches
WAI ARIA Live Regions/API Support - Developer guides
levant "[additions] [removals] [text]" | "all" "additions text" What types of mutations are possibly relevant? See [#Events_fired_for_web_page_mutations the mutation events list] to match the type of event with this attribute's value, to determine whether the author believed the event should be presented to the user or not. aria-relevant on ancestor element container-busy "true" | "false" | "error" "false" The current changes are not yet complete. A state change event for the A11y API's BUSY state will be fired on the container object currently marked as BUSY, once it is no longer BUSY. This is especially important in atomic regions. The entire atomic region should be presented once when it is finally no longer BUSY. aria-busy on ancestor element conta...
...rror" "false" The current changes are not yet complete. A state change event for the A11y API's BUSY state will be fired on the container object currently marked as BUSY, once it is no longer BUSY. This is especially important in atomic regions. The entire atomic region should be presented once when it is finally no longer BUSY. ...
... atomic region should be presented once when it is finally no longer BUSY. aria-busy on ancestor element container-atomic "true" | "false" "false" Is this change inside a region that should always be presented at once. If yes, member-of relation will point to the root of the region (see next section) aria-atomic on ancestor element member-of If container-atomic=true, points to an ancestor accessible object (thus it is actually an accessible relation, not object attribute) Not in atomic region if not provided Points to the root of the atomic container that this object is in. ...
...And 2 more matches
Making content editable - Developer guides
the grabber that allows moving of absolutely-positioned elements. See bug 1449564 and Firefox-specific HTML editing UI has been deprecated for additional details. How does it work? All you have to do is set the contenteditable attribute on nearly any HTML element to make it editable. Here's a simple example which creates a <div> element whose contents the user can edit. <div contenteditable="true"> This text can be edited by the user. </div> Here's the above HTML in action: Executing commands When an HTML element has contenteditable set to true, the document.execCommand() method is made available. This lets you run commands to manipulate the contents of the editable region. Most commands affect the document's selection by, for example, applying a style to the text (bold, italics, e...
...ccess"); user_pref("capability.policy.allowclipboard.Clipboard.paste", "allAccess"); Example: A simple but complete rich text editor <!doctype html> <html> <head> <title>Rich Text Editor</title> <script type="text/javascript"> var oDoc, sDefTxt; function initDoc() { oDoc = document.getElementById("textBox"); sDefTxt = oDoc.innerHTML; if (document.compForm.switchMode.checked) { setDocMode(true); } } function formatDoc(sCmd, sValue) { if (validateMode()) { document.execCommand(sCmd, false, sValue); oDoc.focus(); } } function validateMode() { if (!document.compForm.switchMode.checked) { return true ; } alert("Uncheck \"Show HTML\"."); oDoc.focus(); return false; } function setDocMode(bToSource) { var oContent; if (bToSource) { oContent = document.createTextNode(oDoc.
...ompForm.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); document.execCommand("defaultParagraphSeparator", false, "div"); } else { if (document.all) { oDoc.innerHTML = oDoc.innerText; } else { oContent = document.createRange(); oContent.selectNodeContents(oDoc.firstChild); oDoc.innerHTML = oContent.toString(); } oDoc.contentEditable = true; } ...
...And 2 more matches
Browser detection using the user agent - HTTP
moved it. Most importantly, it assumed no other browsers would support the feature. Support could have been added to other browsers at any time, but this code would have continued choosing the inferior path. 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 splitUpString = isLookBehindSupported ? function(str) { return (""+str).split(new RegExp("(?<=[A-Z])")); } : function(str) { return str.replace(/[A-Z]/g,"z$1").split(/z(?=[A-Z])/g); }; As the a...
...ts" in navigator) { hasTouchScreen = navigator.maxTouchPoints > 0; } else if ("msMaxTouchPoints" in navigator) { hasTouchScreen = navigator.msMaxTouchPoints > 0; } else { var mQ = window.matchMedia && matchMedia("(pointer:coarse)"); if (mQ && mQ.media === "(pointer:coarse)") { hasTouchScreen = !!mQ.matches; } else if ('orientation' in window) { hasTouchScreen = true; // deprecated, but good fallback } else { // Only as a last resort, fall back to user agent sniffing var UA = navigator.userAgent; hasTouchScreen = ( /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) || /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA) ); } } if (hasTouchScreen) document.getElementById("exampleButton").style.pa...
...t sniffing to save on performance. For example, Webkit 6 has a bug whereby when the device orientation changes, the browser might not fire MediaQueryList listeners when it should. To overcome this bug, observe the code below. ...
...And 2 more matches
Access-Control-Allow-Credentials - HTTP
The Access-Control-Allow-Credentials response header tells browsers whether to expose the response to frontend JavaScript code when the request's credentials mode (Request.credentials) is include. When a request's credentials mode (Request.credentials) is include, browsers will only expose the response to frontend JavaScript code if the Access-Control-Allow-Credentials value is true. Credentials are cookies, authorization headers or TLS client certificates. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. Note that simple GET requests are not preflighted, and so if a request is made for a resource with credentials, if this header is not returned with the resource, the response is ignored by the browser a...
...sers to expose the response to frontend JavaScript code, both the server (using the Access-Control-Allow-Credentials header) and the client (by setting the credentials mode for the XHR, Fetch, or Ajax request) must indicate that they're opting in to including credentials. ...
...sponse to frontend JavaScript code, both the server (using the Access-Control-Allow-Credentials header) and the client (by setting the credentials mode for the XHR, Fetch, or Ajax request) must indicate that they're opting in to including credentials. ...
...And 2 more matches
JavaScript data types and data structures - JavaScript
her data structures. Wherever possible, comparisons with other languages are drawn. Dynamic typing JavaScript is a loosely typed and dynamic language. ...
...ort of Object we are using is instanceof keyword. But even in that case there might be misconceptions. Primitive values All types except objects define immutable values (that is, values which can't be changed). For example (and unlike in C), Strings are immutable. We refer to values of these types as "primitive values". Boolean type Boolean represents a logical entity and can have two values: true and false. See Boolean and Boolean for more details. Null type The Null type has exactly one value: null. See null and Null for more details. Undefined type A variable that has not been assigned a value has the value undefined. See undefined and Undefined for more details. Number type ECMAScript has two built-in numeric types: Number and BigInt (see below). The Number type is a double-prec...
...() as well as Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER. Beyond this range, integers in JavaScript are not safe anymore and will be a double-precision floating point approximation of the value. The number type has only one integer with two representations: 0 is represented as both -0 and +0. (0 is an alias for +0.) In the praxis, this has almost no impact. For example, +0 === -0 is true. However, you are able to notice this when you divide by zero: > 42 / +0 Infinity > 42 / -0 -Infinity Although a number often represents only its value, JavaScript provides binary (bitwise) operators. Caution: Although bitwise operators can be used to represent several Boolean values within a single number using bit masking, this is usually considered a bad practice. JavaScript offers other ...
...And 2 more matches
Details of the object model - JavaScript
public String machine; public Engineer () { dept = "engineering"; machine = ""; } public Engineer (String mach) { dept = "engineering"; machine = mach; } } These JavaScript definitions use a special idiom for setting default values: this.name = name || ''; The JavaScript logical OR operator (||) evaluates its first argument. If that argument converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance. Note: This may not work as expe...
...ed by new Foo(). Every object has a __proto__ object property (except Object); every function has a prototype object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's __proto__ to a function's prototype object. ...
...as a prototype object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's __proto__ to a function's prototype object. JavaScript provides a shortcut: the instanceof operator tests an object against a function and returns true if the object inherits from the function prototype. For example, var f = new Foo(); var isTrue = (f instanceof Foo); For a more detailed example, suppose you have the same set of definitions shown in Inheriting properties. Create an Engineer object as follows: var chris = new Engineer('Pigman, Chris', ['jsd'], 'fiji'); With this object, the following statements are all true: chris.__proto__ == Engineer.prototype; chris.__proto__.__proto__ == WorkerBee.prototype; chris.__proto__.__prot...
...And 2 more matches
Indexed collections - JavaScript
nts. For example: let emp = [] emp[0] = 'Casey Jones' emp[1] = 'Phil Lesh' emp[2] = 'August West' Note: If you supply a non-integer value to the array operator in the code above, a property will be created in the object representing the array, instead of an array element. let arr = [] arr[3.4] = 'Oranges' console.log(arr.length) // 0 console.log(arr.hasOwnProperty(3.4)) // true You can also populate an array when you create it: let myArray = new Array('Hello', myVar, 3.14159) // OR let myArray = ['Mango', 'Apple', 'Orange'] Understanding length At the implementation level, JavaScript's arrays actually store their elements as standard object properties, using the array index as the property name. The length property is special. It always returns the index of the ...
... Array methods The Array ...
...t) { console.log(element) }) // logs each item in turn map(callback[, thisObject]) returns a new array of the return value from executing callback on every array item. let a1 = ['a', 'b', 'c'] let a2 = a1.map(function(item) { return item.toUpperCase() }) console.log(a2) // logs ['A', 'B', 'C'] filter(callback[, thisObject]) returns a new array containing the items for which callback returned true. ...
...And 2 more matches
Array.prototype.includes() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax arr.includes(valueToFind[, fromIndex]) Parameters valueToFind The value to search for. Note: When comparing strings and characters, includes() is case-sensitive. fromIndex Optional The position in this array at which to begin searching for valueToFind. ...
...l The position in this array at which to begin searching for valueToFind. The first element to be searched is found at fromIndex for positive values of fromIndex, or at arr.length + fromIndex for negative values of fromIndex (using the absolute value of fromIndex as the number of elements from the end of the array at which to start the search). Defaults to 0. Return value A Boolean which is true if the value valueToFind is found within the array (or the part of the array indicated by the index fromIndex, if specified). Values of zero are all considered to be equal, regardless of sign. (That is, -0 is considered to be equal to both 0 and +0), but false is not considered to be the same as 0. Note: Technically speaking, includes() uses the sameValueZero algorithm to determine whether the...
... the array indicated by the index fromIndex, if specified). Values of zero are all considered to be equal, regardless of sign. (That is, -0 is considered to be equal to both 0 and +0), but false is not considered to be the same as 0. Note: Technically speaking, includes() uses the sameValueZero algorithm to determine whether the given element is found. Examples [1, 2, 3].includes(2) // true [1, 2, 3].includes(4) // false [1, 2, 3].includes(3, 3) // false [1, 2, 3].includes(3, -1) // true [1, 2, NaN].includes(NaN) // true fromIndex is greater than or equal to the array length If fromIndex is greater than or equal to the length of the array, false is returned. The array will not be searched. let arr = ['a', 'b', 'c'] arr.includes('c', 3) // false arr.includes('c', 100...
...And 2 more matches
Array - JavaScript
o be quoted (because it begins with a digit). But it's also possible to quote the array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. As a result, '2' and '02' would refer to two different slots on the years object, and the following example could be true: console.log(years['2'] != years['02']) Relationship between length and numerical properties A JavaScript array's length property and numerical properties are connected. Several of the built-in array methods (e.g., join(), slice(), indexOf(), etc.) take into account the value of an array's length property when they're called. Other methods (e.g., push(), splice(), etc.) also result in updat...
...regular expression. The number of possible parenthesized substrings is unlimited. [1]: "bB" [2]: "d" Constructor Array() Creates a new Array object. Static properties get Array[@@species] The constructor function is used to create derived objects. Static methods Array.from() Creates a new Array instance from an array-like or iterable object. Array.isArray() Returns true if the argument is an array, or false otherwise. Array.of() Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments. Instance properties Array.prototype.length Reflects the number of elements in an array. Array.prototype[@@unscopables] A symbol containing property names to exclude from a with binding scope. Instance methods Ar...
... a with binding scope. Instance methods Array.prototype.concat() Returns a new array that is this array joined with other array(s) and/or value(s). Array.prototype.copyWithin() Copies a sequence of array elements within the array. Array.prototype.entries() Returns a new Array Iterator object that contains the key/value pairs for each index in the array. Array.prototype.every() Returns true if every element in this array satisfies the testing function. Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. Array.prototype.filter() Returns a new array containing all elements of the calling array for which the provided filtering function returns true. Array.prototype.find() Returns the found element in the array, if some...
...And 2 more matches
JSON.stringify() - JavaScript
by returning a string (the same as date.toISOString()). Thus, they are treated as strings. The numbers Infinity and NaN, as well as the value null, are all considered null. All the other Object instances (including Map, Set, WeakMap, and WeakSet) will have only their enumerable properties serialized. ...
...ame as date.toISOString()). Thus, they are treated as strings. The numbers Infinity and NaN, as well as the value null, are all considered null. All the other Object instances (including Map, Set, WeakMap, and WeakSet) will have only their enumerable properties serialized. ...
... As a function, it takes two parameters: the key and the value being stringified. The object in which the key was found is provided as the replacer's this parameter. Initially, the re...
...And 2 more matches
Number.isNaN() - JavaScript
e is Number. It is a more robust version of the original, global isNaN(). The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Number.isNaN(value) Parameters value The value to be tested for NaN. 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. This situation is unlike all other possible value comparisons in JavaScript. In comparison to the global isNaN() function, Number.isNaN() doesn't suffer the problem of force...
... unlike all other possible value comparisons in JavaScript. In comparison to the global isNaN() function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true. ...
...t aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true. Polyfill The following works because NaN is the only value in javascript which is not equal to itself. Number.isNaN = Number.isNaN || function isNaN(input) { return typeof input === 'number' && input !== input; } Examples Using isNaN Number.isNaN(NaN); // true Number.isNaN(Number.NaN); // true Number.isNaN(0 / 0); // true // e.g. ...
...And 2 more matches
Object.assign() - JavaScript
n error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised. Note: Object.assign() does not throw on null or undefined sources. ...
...on-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised. Note: Object.assign() does not throw on null or undefined sources. ...
... If the source value is a reference to an object, it only copies the reference value. function test() { 'use strict'; l...
...And 2 more matches
Object.prototype.constructor - JavaScript
The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name. The value is only read-only for primitive values such as 1, true, and "test". Description All objects (with the exception of objects created with Object.create(null)) will have a constructor property. ...
...h as 1, true, and "test". Description All objects (with the exception of objects created with Object.create(null)) will have a constructor property. Objects created without the explicit use of a constructor function (such as object- and array-literals) will have a constructor property that points to the Fundamental Object constructor type for that object. let o = {} o.constructor === Object // true let o = new Object o.constructor === Object // true let a = [] a.constructor === Array // true let a = new Array a.constructor === Array // true let n = new Number(3) n.constructor === Number // true Examples Displaying the constructor of an object The following example creates a constructor (Tree) and an object of that type (theTree). The example then displays the constructor property fo...
... object theTree. function Tree(name) { this.name = name } let theTree = new Tree('Redwood') console.log('theTree.constructor is ' + theTree.constructor) This example displays the following output: theTree.constructor is function Tree(name) { this.name = name } Changing the constructor of an object The following example shows how to modify the constructor value of generic objects. ...
...And 2 more matches
Object.prototype.hasOwnProperty() - JavaScript
iption All descendents of Object inherit the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check for a property in the object's prototype chain. If an Object is an Array, hasOwnProperty method can check whether an index exists. ...
...d property as a direct property of that object; unlike the in operator, this method does not check for a property in the object's prototype chain. If an Object is an Array, hasOwnProperty method can check whether an index exists. Note hasOwnProperty returns true even if the value of the property is null or undefined. o = new Object(); o.propOne = null; o.hasOwnProperty('propOne'); // returns true o.propTwo = undefined; o.hasOwnProperty('propTwo'); // returns true Examples Using hasOwnProperty to test for a property's existence The following example determines whether the o object contains a property named prop: o = new Object(); o.hasOwnProperty('prop'); // returns false o.prop = 'exists'; o.hasOwnProperty('prop'); // returns true Direct vs. inherited properties The followin...
...t 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. Note that the for...in loop is already only iterating enumerable items, so one should not assume based on the lack of non-en...
...And 2 more matches
Comparing Reflect and Object methods - JavaScript
n the methods available on the Object and Reflect APIs. Please note that if a method does not exist in an API, it is marked as N/A. Method Name Object Reflect defineProperty() Object.defineProperty() returns the object that was passed to the function. Returns a TypeError if the property was not successfully defined on the object. Reflect.defineProperty() returns true if the property was defined on the object and false if it was not. defineProperties() Object.defineProperties() returns the objects that were passed to the function. Returns a TypeError if any properties were not successfully defined on the object. N/A set() N/A Reflect.set() returns true if the property was set successfully on the object and false if it was not. Thr...
... getOwnPropertyDescriptor() Object.getOwnPropertyDescriptor() returns a property descriptor of the given property if it exists on the object argument passed in, and returns undefined if it does not exist. ...
...rns null if there are no inherited properties, and throws a TypeError for non-objects. setPrototypeOf() Object.setPrototypeOf() returns the object itself if its prototype was set successfully. Throws a TypeError if the prototype being set was anything other than an Object or null, or if the prototype for the object being modified is non-extensible. Reflect.setPrototypeOf() returns true if the prototype was successfully set on the object and false if it wasn't (including if the prototype is non-extensible). Throws a TypeError if the target passed in was not an Object, or if the prototype being set was anything other than an Object or null. isExtensible() Object.isExtensible() returns true if the object is extensible, and false if it is not. Throws a TypeError in ES5 ...
...And 2 more matches
Reflect - JavaScript
s specified by the argumentsList parameter. See also Function.prototype.apply(). Reflect.construct(target, argumentsList[, newTarget]) The new operator as a function. Equivalent to calling new target(...argumentsList). Also provides the option to specify a different prototype. Reflect.defineProperty(target, propertyKey, attributes) Similar to Object.defineProperty(). Returns a Boolean that is true if the property was successfully defined. Reflect.deleteProperty(target, propertyKey) The delete operator as a function. Equivalent to calling delete target[propertyKey]. Reflect.get(target, propertyKey[, receiver]) Returns the value of the property. Works like getting a property from an object (target[propertyKey]) as a function. Reflect.getOwnPropertyDescriptor(target, propertyKey) Simila...
...or of the given property if it exists on the object, undefined otherwise. Reflect.getPrototypeOf(target) Same as Object.getPrototypeOf(). Reflect.has(target, propertyKey) Returns a Boolean indicating whether the target has the property. Either as own or inherited. Works like the in operator as a function. Reflect.isExtensible(target) Same as Object.isExtensible(). ...
...erty. Either as own or inherited. Works like the in operator as a function. Reflect.isExtensible(target) Same as Object.isExtensible(). Returns a Boolean that is true if the target is extensible. Reflect.ownKeys(target) Returns an array of the target object's own (not inherited) property keys. Reflect.preventExtensions(target) Similar to Object.preventExtensions(). Returns a Boolean that is true if the update was successful. Reflect.set(target, propertyKey, value[, receiver]) A function that assigns values to properties. Returns a Boolean that is true if the update was successful. Reflect.setPrototypeOf(target, prototype) A function that sets the prototype of an object. Returns a Boolean that is true if the update was successful. Examples Detecting whether an object contains certa...
...And 2 more matches
Greater than (>) - JavaScript
The greater than operator (>) returns true if the left operand is greater than the right operand, and false otherwise. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax x > y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
...com/mdn/interactive-examples and send us a pull request. Syntax x > y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
... y Description The operands are compared using the Abstract Relational Comparison algorithm. See the documentation for the Less than operator for a summary of this algorithm. ...
...And 2 more matches
Inequality (!=) - JavaScript
e the same result: x != y !(x == y) For details of the comparison algorithm, see the page for the equality operator. ...
...hm, see the page for the equality operator. ...
...lity operator. ...
...And 2 more matches
Strict mode - JavaScript
; (or 'use strict';) before any other statements. // Whole-script strict mode syntax 'use strict'; var v = "Hi! I'm a strict mode script!"; This syntax has a trap that has already bitten a major site: it isn't possible to blindly concatenate conflicting scripts. Consider concatenating a strict mode script with a non-strict mode script: the entire concatenation looks strict! The inverse is also true: non-strict plus strict looks non-strict. Obviously, concatenation of scripts is never ideal, but if you must, consider enabling strict on a function-by-function basis. You can also take the approach of wrapping the entire contents of a script in a function and having that outer function use strict mode. This eliminates the concatenation problem and it means that you have to explicitly export an...
...ntax error: 'use strict'; var sum = 015 + // !!! syntax error 197 + 142; var sumWithOctal = 0o10 + 8; console.log(sumWithOctal); // 16 Seventh, strict mode in ECMAScript 2015 forbids setting properties on primitive values. Without strict mode, setting properties is simply ignored (no-op), with strict mode, however, a TypeError is thrown. (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. Many compiler optimizations rely on the ability to say that variable X is stored in that location: this is critical to fully optimizing JavaScript code. JavaScript som...
...JavaScript environments must restrict. Thus for a strict mode function, the specified this is not boxed into an object, and if unspecified, this will be undefined: 'use strict'; function fun() { return this; } console.assert(fun() === undefined); console.assert(fun.call(2) === 2); console.assert(fun.apply(null) === null); console.assert(fun.call(undefined) === undefined); console.assert(fun.bind(true)() === true); That means, among other things, that in browsers it's no longer possible to reference the window object through this inside a strict mode function. Second, in strict mode it's no longer possible to "walk" the JavaScript stack via commonly-implemented extensions to ECMAScript. In normal code with these extensions, when a function fun is in the middle of being called, fun.caller is...
...And 2 more matches
Interacting with page scripts - Archive of obsolete content
tion() { alert(window.foo.greetme("page script")); }, false); </script> </body> </html> Reverting to the old behavior You can switch Firefox back to the old behavior in which content scripts could expose objects and functions to page scripts using unsafeWindow. To do this, add an option called "unsafe-content-script" under the "permissions" key in package.json, and set it to true. "permissions": { "unsafe-content-script": true } This is only a temporary migration aid, and will be removed eventually. Communicating with page scripts There are two different ways a content script can communicate with a page script: using the DOM postMessage() API using custom DOM events Using the DOM postMessage API Note that before Firefox 31 code in content scripts can't us...
...cript> </body> </html> The content script "content-script.js" adds an event listener to the button, that sends a custom event containing a message: var messenger = document.getElementById("message"); messenger.addEventListener("click", sendCustomEvent, false); function sendCustomEvent() { var greeting = {"greeting" : "hello world"}; var event = new CustomEvent("addon-message", { bubbles: true, detail: greeting }); document.documentElement.dispatchEvent(event); } Finally, the page script "page-script.js" listens for the message and logs the greeting to the Web Console: window.addEventListener("addon-message", function(event) { console.log(event.detail.greeting); }, false); After Firefox 30: clone the message object This technique depends on being able to share the message pay...
...Also, there's no need to clone the message when using custom DOM events in this direction. In this example, "main.js" creates a page-mod to target the page we are interested in:...
...ain.org/talk.html", contentScriptFile: data.url("listen.js") }); The web page "talk.html" creates and dispatches a custom DOM event, using initCustomEvent()'s detail parameter to supply the payload: <!DOCTYPE html> <html> <head></head> <body> <script> function sendMessage() { var event = document.createEvent('CustomEvent'); event.initCustomEvent("addon-message", true, true, { hello: 'world' }); document.documentElement.dispatchEvent(event); } </script> <button onclick="sendMessage()">Send Message</button> </body> </html> Finally, the content script "listen.js" listens for the new event and retrieves the payload from its detail attribute: window.addEventListener("addon-message", function(event) { console.log(JSON.stringify(event.det...
util/array - Archive of obsolete content
Helper functions for working with arrays. Globals Functions has(array, element) Returns true if the given Array contains the element or false otherwise. A simplified version of array.indexOf(element) >= 0. let { has } = require('sdk/util/array'); let a = ['rock', 'roll', 100]; has(a, 'rock'); // true has(a, 'rush'); // false has(a, 100); // true Parameters array : array The array to search. element : * The element to search for in the array. Returns boolean : A boolean indicating whether or not the element was found in the array. hasAny(array, elements) Returns true if the given Array contains any of the elements in the elements array, or false otherwise. let { hasAny } = require('sdk/util/array'); let a = ['rock', 'roll', 100]; hasAny(a, ['rock', 'bright', 'light']); // tr...
...ush', 'coil', 'jet']); // false Parameters array : array The array to search for elements. elements : array An array of elements to search for in array. Returns boolean : A boolean indicating whether or not any of the elements were found in the array. add(array, element) If the given array does not already contain the given element, this function adds the element to the array and returns true. Otherwise, this function does not add the element and returns false. let { add } = require('sdk/util/array'); let a = ['alice', 'bob', 'carol']; add(a, 'dave'); // true add(a, 'dave'); // false add(a, 'alice'); // false console.log(a); // ['alice', 'bob', 'carol', 'dave'] Parameters array : array The array to add the element to. element : * The element to add Returns boolean : A boolea...
... add(a, 'alice'); // false console.log(a); // ['alice', 'bob', 'carol', 'dave'] Parameters array : array The array to add the element to. element : * The element to add Returns boolean : A boolean indicating whether or not the element was added to the array. remove(array, element) If the given array contains the given element, this function removes the element from the array and returns true. Otherwise, this function does not alter the array and returns false. let { remove } = require('sdk/util/array'); let a = ['alice', 'bob', 'carol']; remove(a, 'dave'); // false remove(a, 'bob'); // true remove(a, 'bob'); // false console.log(a); // ['alice', 'carol'] Parameters array : array The array to remove the element from. element : * The element to remove from the array if it cont...
.../util/array'); let i = new Set(); i.add('otoro'); i.add('unagi'); i.add('keon'); fromIterator(i) // ['otoro', 'unagi', 'keon'] Parameters iterator : iterator The Iterator object over which to iterate and place results into an array. Returns array : The iterator's results in an array. find(iterator) Iterates over given array and applies given predicate function until predicate(element) is true. If such element is found it's retured back otherwise third optional fallback argument is returned back. If fallback is not provided returns undefined. let { find } = require('sdk/util/array'); let isOdd = (x) => x % 2; find([2, 4, 5, 7, 8, 9], isOdd); // => 5 find([2, 4, 6, 8], isOdd); // => undefiend find([2, 4, 6, 8], isOdd, null); // => null fromIterator(i) // ['otoro', 'unagi',...
Code snippets - Archive of obsolete content
RL + collection).get()).length; Dump the cleartext of each record in a collection to the console. ...
...nsole.log(item.cleartext); }; coll.get(); Print an individual record let collection = "history"; let id = "GUID_GOES_HERE"; Components.utils.import("resource://services-sync/main.js"); Components.utils.import("resource://services-sync/record.js"); let recordType = Weave.Engines.get(collection)._recordObj; let coll = new Collection(Weave.Service.storageURL + collection, recordType); coll.full = true; coll.ids = [id]; coll.recordHandler = function(item) { item.collection = collection; item.decrypt(); console.log(item.cleartext); }; coll.get(); Count types of bookmark records Components.utils.import("resource://services-sync/main.js"); Components.utils.import("resource://services-sync/record.js"); let deleted = 0; let items = {}; let collection = "bookmarks"; let record...
... Long-tap the log in question.
...let old = resource.get(); // Delete. resource.put(del); // Restore the old value. resource.put(old); ...
Supporting per-window private browsing - Archive of obsolete content
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). To do this, observe the last-pb-context-exiting notification and set the data field of the nsISupportsPRBool subject to true. var os = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); os.addObserver(function (aSubject, aTopic, aData) { aSubject.QueryInterface(Components.interfaces.nsISupportsPRBool); // if another extension has not already canceled entering the private mode if (!aSubject.data) { /* you should display some u...
...However, sometimes you need to adjust the privacy status on a channel manually, for example, if you have created the channel directly yourself. You can...
...l manually, for example, if you have created the channel directly yourself. You can use the nsIPrivateBrowsingChannel interface for this purpose. The example below creates a channel to load a URL, and forces it to be in private mode. var channel = Services.io.newChannel("http://example.org", null, null); channel.QueryInterface(Components.interfaces.nsIPrivateBrowsingChannel); channel.setPrivate(true); // force the channel to be loaded in private mode Similarly, XMLHttpRequest objects created via createInstance(Ci.nsIXMLHttpRequest) will often require explicit adjustment, since they have no context from which to derive a privacy status. var xhr = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Components.interfaces.nsIXMLHttpReqeust); var channel = xhr.channel.Que...
...jects created via createInstance(Ci.nsIXMLHttpRequest) will often require explicit adjustment, since they have no context from which to derive a privacy status. var xhr = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Components.interfaces.nsIXMLHttpReqeust); var channel = xhr.channel.QueryInterface(Components.interfaces.nsIPrivateBrowsingChannel); channel.setPrivate(true); ...
Floating Panels - Archive of obsolete content
Floating Panels A floating panel is used for secondary popups such as tool palettes and property inspector panels. It will have a titlebar which the user may use to move the panel around on the screen. A floating panel can be created using the panel element with at least two additional attributes as in the following example: <panel id="tools-panel" noautohide="true" titlebar="normal"> <label control="name" value="Name:"/> <textbox id="name"/> </panel> The noautohide attribute is used to indicate that the panel is not temporary. When set to true, the popup will not close when the user clicks outside of it, nor when the user presses the Escape key. The titlebar attribute creates a panel with a titlebar. Currently, only the value normal is supported, which creates a default titlebar. In the...
...ntly of the main window, however it will always appear above the main window. On Mac, floating panels are invisible when another application is made active, and become visible again when the XUL application is made active. A floating panel may contain any type of element. ...
...See Closing a Popup for more information about this. ...
...See Closing a Popup for more information about this. The hidePopup method would be used if you wish to place your own close button on the panel, or wish to close the panel in response to a user action. ...
Panels - Archive of obsolete content
e normal way in which a user would cancel the operation. You may wish to also place a cancel or close button within the panel, especially if the panel is larger with a lot of controls within it. Sometimes, however, you may wish to keep the panel open, even if the user clicks outside of it. This is useful when creating floating tool panels. To do this, set the noautohide attribute on the panel to true. <panel id="search-panel" noautohide="true"> <textbox id="search"/> <button label="Search" oncommand="doSearch();"/> <button label="Cancel" oncommand="this.parentNode.hidePopup();"/> </panel> Because the panel can no longer be closed by clicking elsewhere, the panel should always provide a means to close the panel itself. In this example a cancel button has been added. For more informat...
...ssing the Tab key. If you want to set the focus to an element by default when a panel is opened, adjust the focus within a popupshown event handler. For instance, to have the textbox initially focused in the example above: <panel id="search-panel" onpopupshown="document.getElementById('search').focus()"> To disable the adjusting of focus when a panel is opened, set the noautofocus attribute to true: <panel noautofocus="true"> This will cause the focus to remain on the element within the main window that has focus when the panel is opened. Note that this will also keep the focus within the panel when it is closed. When a panel is closed, the focus is removed from the element within the panel which has the focus event, if any, and whatever element was focused before the panel was opened i...
... window that has focus when the panel is opened. Note that this will also keep the focus within the panel when it is closed. When a panel is closed, the focus is removed from the element within the panel which has the focus event, if any, and whatever element was focused before the panel was opened is refocused. You can prevent the focus from being removed by setting the noautofocus attribute to true as above. In addition, the norestorefocus attribute should be set to true in order to prevent the previously focused element from being refocused. Normally, only the latter would be set if needed. This process of removing the focus when opening and closing a popup occurs after the popupshowing event or popuphiding event is fired, which means that if those events are cancelled, the focus is not a...
...d by grabbing the background Requires Gecko 7.0(Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) Starting in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4), you can use the backdrag attribute to create panels that the user can drag by clicking and dragging anywhere on their backgrounds. This is a simple, Boolean attribute, so you can enable this feature like this: <panel backdrag="true"> ...
Tree Widget Changes - Archive of obsolete content
nsITreeView.progressNormal -> nsITreeView.PROGRESS_NORMAL (1) nsITreeView.progressUndetermined -> nsITreeView.PROGRESS_UNDETERMINED (2) nsITreeView.progressNode -> nsITreeView.PROGRESS_NONE (3) As well, the drag and drop methods canDropOn and canDropBeforeAfter have been replaced with a single method canDrop(idx,orientation) which handles both. ...
...return true if a drop is allowed on a row. Checkbox columns Tree columns now implement the checkbox type. Previously the value existed but was not implemented. Now it is. You can create a checkbox column by setting the type attribute of a column to checkbox. <treecol type="checkbox"> You can then set or clear the checkbox for a particular cell in that column by setting the value attribute to true, or leaving out the attribute. Note that it's the value attribute you use, not the label attribute. <treecell/> <treecell value="true"/> You need to specify the checkbox image with CSS for the checkbox to display. (Do NOT set id of the column to be 'checked' it will cause problems with the CSS) treechildren::-moz-tree-checkbox(checked) { /* css for checked cells */ list-style-image: u...
...ll value="true"/> You need to specify the checkbox image with CSS for the checkbox to display. (Do NOT set id of the column to be 'checked' it will cause problems with the CSS) treechildren::-moz-tree-checkbox(checked) { /* css for checked cells */ list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif"); } In addition, checkmark columns support editing: <tree editable="true"> <treecols> <treecol type="checkbox" editable="true"> ... </treecol> </treecols> </tree> If the column is editable, the user can click the cell to change the state of the checkbox. When the user clicks the cell, the view's setCellValue method will be called with either the value true or false. Note that the tree must also be marked as editable using the editable attribute in...
... Currently, only checkbox columns support editing, although the content-based tree handles the nsITreeView.setCellValue() and nsITreeView.setCellText() functions to change the tree content with a script for other types of cells. ...
Creating Dialogs - Archive of obsolete content
The dialog element has some additional attributes that windows do not have. The buttons attribute is used to specify which buttons should appear in the dialog. The following values may be used, seperated by c...
...The dialog element has some additional attributes that windows do not have. The buttons attribute is used to specify which buttons should appear in the dialog. The following values may be used, seperated by commas: accept - an OK button cancel - a Cancel button help - a Hel...
...ore information You can set code to execute when the buttons are pressed using the ondialogaccept, ondialogcancel, ondialoghelp and ondialogdisclosure attributes. If you try the example above, you will find that the doOK() function is called when the OK button is pressed and the doCancel() function is called when the Cancel button is pressed. The two functions doOK() and doCancel() both return true, which indicates that the dialog should be closed. If the dialog shouldn't be closed, false should be returned instead. This would be used, for example, if an invalid value was entered in a field in the dialog. Amongst other useful attributes are buttonlabelaccept - label to appear on the accept button egSave buttonaccesskeyaccept - access key to use for the accept button egS defaultButton ...
.../keymaster/gatekeeper/there.is.only.xul" onload="window.sizeToContent();" buttons="accept,cancel" buttonlabelaccept="Set Favourite" buttonaccesskeyaccept="S" ondialogaccept="return doSave();" buttonlabelcancel="Cancel" buttonaccesskeycancel="n" ondialogcancel="return doCancel();"> <script> function doSave(){ //doSomething() return true; } function doCancel(){ return true; } </script> <dialogheader title="My dialog" description="Example dialog"/> <groupbox flex="1"> <caption label="Select favourite fruit"/> <radio id="orange" label="Oranges because they are fruity"/> <radio id="violet" selected="true" label="Strawberries because of their colour"/> <radio id="yellow" label="Bananas because they are pre-packaged"/> </gr...
Document Object Model - Archive of obsolete content
is always a single global object that is always available. You can refer to the properties and methods of the global object without having to qualify them with an object. For example, if the global object has a 'name' property, you can change the name with the code 'name = 7', without having to specify any object to use. In a browser context, the window is the global object, and the same is also true for XUL. Naturally, this global object will be different for each window. Each frame will also have a separate window object. The window is often referred to using the window property, although this is optional. Sometimes, this is done just to clarify the scope of the method you are referring to. For example, the following two lines which open a new window are functionally equivalent: window.op...
...ally invisible. The hidden attribute is used to control whether an element is visible or not. We'll change the progress meter so that its initially hidden. Also, we'll add an id attribute so that we can refer to it in a script to show and hide it. While we're at it, let's also hide the splitter and results tree as we only need to show them after a search is performed. <tree id="results" hidden="true" flex="1"> . . . <splitter id="splitbar" resizeafter="grow" hidden="true"/> <hbox> <progressmeter id="progmeter" value="50%" style="margin: 4px;" hidden="true"/> We've added the hidden attribute and set the value to true. This causes the element to be hidden when it first appears. Next, let's add a function that is called when the Find button is pressed. We'll put scripts in a se...
...to get the flex of an element, you can use the flex property. In this case, the underlying code just returns the value of the attribute. For other properties, XUL will perform more complex calculations. You can manipulate the attributes of an element using any of the following methods: getAttribute ( name ) Return the value of the attribute with the given name. hasAttribute ( name ) Return true if the attribute with the given name has a value. setAttribute ( name , value ) Set the value of the attribute with the given name to the given value. removeAttribute ( name ) Remove the attribute with the given name. These functions allow you to get and change the value of an attribute at any time. For example, to use the value of the flex attribute, you might use code like the following: ...
...t, you can call the properties of that element. For example, to get the hidden property for an element, you can use the syntax element.hidden where 'element' is a reference to the element. You might note that most of the properties listed in the reference correlate to common attributes on elements. There are differences, of course, for example, while getAttribute("hidden") will return the string 'true' for a hidden element, whereas the hidden property returns a boolean true value. In this case, the type conversion is done for you so the property is more convenient. As with each document, there is a different element object for XUL elements as for HTML and XML elements. Every XUL element implements the XULElement (reference broken) interface. A XUL element is any element declared with the XUL ...
More Menu Features - Archive of obsolete content
Notice how the menu bar was added inside the toolbox. The three dots after Open Search and Save Search are the usual way that you indicate to the user that a dialog will open when selecting the command. Access keys have been added for each menu and menu...
...ndicate the type of check, and name to group commands together. The example below creates a menu with a checked item. Example 2 : Source View <toolbox> <menubar id="options-menubar"> <menu id="options_menu" label="Options"> <menupopup> <menuitem id="backups" label="Make Backups" type="checkbox"/> <menuitem id="email" label="Email Administrator" type="checkbox" checked="true"/> </menupopup> </menu> </menubar> </toolbox> The type attribute has been added which is used to make the menu item checkable. By setting its value to checkbox, the menu item can be checked on and off by selecting the menu item. Menu with radios In addition to standard checks, you can create the radio style of checks by setting the type to a value of radio. A radio check is used when...
... put a name attribute on each one to group. Set the value to the same string. ...
...They are grouped together because they all have the same name. The last menu item, Earth, while a radio button, is not part of this group because it has a different name...
Updating Commands - Archive of obsolete content
tbox has the focus and there is something on the clipboard to paste. The command will become enabled whenever a textbox is focused and when the clipboard contents change. A command updater will listen for these situations and code can be executed which enables and disables commands as necessary. A simple command updater looks like this: <commandset id="updatePasteItem" commandupdater="true" events="focus" oncommandupdate="goUpdateCommand('cmd_paste');"/> A command updater is indicated by using the commandupdater attribute, which should be set to true. The events attribute is used to list the events that the command updater listens for. You can specify multiple events by separating them with commas. In the example above, the command updater listens for the f...
...ed text changes. undo: occurs when the undo buffer changes. clipboard: occurs when the contents of the clipboard changes. The following example shows the command updaters used in the Mozilla browser to update the edit menu commands. The functions used can be found in the 'chrome://communicator/content/utilityOverlay.js' script. ...
...ommand updaters used in the Mozilla browser to update the edit menu commands. The functions used can be found in the 'chrome://communicator/content/utilityOverlay.js' script. ...
...lay.js' script. <commandset id="globalEditMenuItems" commandupdater="true" events="focus" oncommandupdate="goUpdateGlobalEditMenuItems()"/> <commandset id="selectEditMenuItems" commandupdater="true" events="select" oncommandupdate="goUpdateSelectEditMenuItems()"/> <commandset id="undoEditMenuItems" commandupdater="true" events="undo" oncommandupdate="goUpdateUndoEditMenuItems()"/> <commandset id="clipboardEditMenuItems" commandupdater="true" events="clipboard" oncommandupdate="goUpdatePasteMenuItems()"/> Next, we'll find out how to use observers. << PreviousNext >> ...
XUL controls - Archive of obsolete content
cument"/> <menuitem label="New Image"/> </menupopup> </button> More information about this type of menu button element. Button Reference Related Elements: menupopup menuitem <checkbox> A control that may be turned on and off, typically used to create options which may be enabled or disabled. <checkbox label="Show Toolbar Labels" checked="true"/> More information about the checkbox element. Checkbox Reference <colorpicker> A control that may be used to select a color. <colorpicker color="#FF0000"/> Colorpicker Reference <colorpicker type="button"> A specialized type of color picker which shows only a button. Pressing the button displays a color picke...
...to create a control with a drop down to select a value. <menulist> <menupopup> <menuitem label="Lions" value="l"/> <menuitem label="Tigers" value="t"/> <menuitem label="Bears" value="b"/> </menupopup> </menulist> More information about the menulist element. ...
...menulist> More information about the menulist element. Menulist Reference Related Elements: menupopup menuitem <menulist editable="true"> An editable menulist is like a standard menulist except that the selected value is displayed in a textbox where it may be modified directly or values not in the popup list may be entered. <menulist editable="true"> <menupopup> <menuitem label="Elephants"/> <menuitem label="Kangaroos"/> <menuitem label="Bats" /> </menupopup> </menulist> More information about the editable menulist element. Menulist Reference Related Elements: menupopup menuitem <progressmeter> A progress meter is used to display the progress of a lengthy task. <progress...
... <tab> Description goes here. <tab label="firefox"/> Tab Reference Related Elements: tabs tabbox tabpanels <textbox> A textbox which allows a single line of text to be entered. <textbox value="firefox"/> More information about the textbox element. Textbox Reference <textbox multiline="true"> A textbox which allows multiple lines of text to be entered. <textbox multiline="true"/> More information about the multiple line textbox element. Textbox Reference <textbox type="autocomplete"> A textbox that provides a dropdown showing matches that would complete what the user types. The user can select one to have it filled into the textbo...
browser - Archive of obsolete content
disablehistory...
... disablehistory Type: boolean Disables both session and global history for the docshell attached to the browser. ...
...scroll will be enabled or depending on the user preference general.autoScroll. disablehistory Type: boolean Disables both session and global history for the docshell attached to the browser. disableglobalhistory Type: boolean Disables global history for the docshell attached to the browser while keeping session history active. disablesecurity Type: boolean Set this attribute to true to disable the security UI for this browser. Omit this attribute off to enable it. droppedLinkHandler Type: function This function is called when links are dropped to the browser element, with the following arguments. droppedLinkHandler(event, uri, name) -- Firefox 51 or older droppedLinkHandler(event, links) -- Firefox 52 or newer event -- drop event, or null if no event is ava...
...fault behaviour): A browser, intended to be used for loading privileged content using a chrome:// URI. Don't use for content from web, as this may cause serious security problems! Properties accessibleType Type: integer A value indicating the type of accessibility object for the element. canGoBack Type: boolean This read-only property is true if there is a page to go back to in the session history and the Back button should be enabled. canGoForward Type: boolean This read-only property is true if there is a page to go forward to in the session history and the Forward button should be enabled. contentDocument Type: document This read-only property contains the document object in the element. contentP...
dialog - Archive of obsolete content
Moreover this hides separator between titlebar and window contents. This only affects Mac OS X. buttonaccesskeyaccept Type: string Th...
...2 Type: string The access key to use for the second extra button. buttonaccesskeyhelp Type: string The access key to use for the "help" button. buttonalign Type: string The value of the align attribute for the box containing the buttons. buttondir Type: string The value of the dir attribute for the box containing the buttons. buttondisabledaccept Type: boolean If true, the accept button is disabled. buttonlabelaccept Type: string The label to appear on the "accept" button. buttonlabelcancel Type: string The label to appear on the "cancel" button. buttonlabeldisclosure Type: string The label to appear on the "disclosure" button. buttonlabelextra1 Type: string The label to appear on the first extra button. buttonlabelextra2 ...
...al button. You can set its label with the buttonlabelextra2 attribute. Note: If you don't want to display any buttons in the dialog box, set the value of this attribute to "," (a single comma). Warning: If the accept and cancel buttons are actually shown is system dependent and is mainly controlled by the value of the boolean preference browser.preferences.instantApply. ...
... defaultButton Type: string Normally this attribute should not be set, but if it is, it specifies the default button in the dialog. Typically, this means that the button will be activated when the Enter key is pressed. ...
listitem - Archive of obsolete content
This should be one of the characters that appears in the label attribute for the element. checked Type: boolean Indicates whether the element is checked or not. Use hasAttribute() to determine whether this attribute is set i...
...and the displayed text is larger than this maximum width, you may be able to use the max-width CSS property (or the maxwidth attribute) to override this size. For example, for a menuitem in a menu you can add the following CSS rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } current Type: boolean This attribute will be set to true if the listitem is the current item. This is typically used by a theme to customize the focus ring. To change the currently selected item in a listbox, use the listbox property selectedItem. disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is ...
.... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...s and sets the value of the current attribute. disabled Type: boolean Gets and sets the value of the disabled attribute. image Type: image URL Gets and sets the value of the image attribute. label Type: string Gets and sets the value of the label attribute. selected Type: boolean This property's value is true if this element is selected, or false if it is not. This property is read only. This property is available for menuitem and menuseparator elements in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the content...
menu - Archive of obsolete content
Archive › Mozilla › XUL › menu
invoke the command. If this value is set, it overrides an assigned key set in the key attribute. This attribute does not apply to menus directly on the menubar. accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. allowevents Type: boolean If true, events are passed to children of the element. Otherwise, events are passed to the element only. crop Type: one of the values below If the label of the element is too big to fit in its given space, the text will be cropped on the side specified by the crop attribute. An ellipsis will be used in place of the cropped text. If the box direction is reversed, the cropping ...
... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...Type: boolean This attribute is set on an item in a menu when it is being hovered over. Typcially, the theme will use this to highlight the item. A DOMMenuItemActive event will be sent to the item when the item is hovered over, and a DOMMenuItemInactive event will be sent to the item when the selection moves away. open Type: boolean For the menu type buttons, the open attribute is set to true when the menu is open. The open attribute is not present if the menu is closed. sizetopopup Type: one of the values below Indicates how the menu width and the menupopup width are determined. If the sizetopopup attribute is left out or set to none, the menu will be its preferred width and the popup may extend outside of this width, unaffected by the maximum width of the menu itself. Otherw...
...menu element Returns the enclosing menu that the item is inside, if any, or null if there is no enclosing menu. itemCount Type: integer Read only property holding the number of child items. menupopup Type: menupopup element A reference to the menupopup used by the menu or menulist. This property is read-only. open Type: boolean This property will be set to true when the menu is open. The menu may be opened by setting the open property to true and closed by setting it to false. parentContainer Type: menu element Read only property that returns the containing menu element, or null if there isn't a containing menu. selected Type: boolean This property's value is true if this element is selected, or false if it is not. This pro...
radio - Archive of obsolete content
Archive › Mozilla › XUL › radio
on is available in the XUL tutorial. Attributes accesskey, command, crop, disabled, focused, group, image, label, selected, tabindex, value Properties accessKey, accessibleType, control, crop, disabled, image, label, radioGroup, selected, tabIndex, value Examples <radiogroup> <radio id="orange" label="Red" accesskey="R"/> <radio id="violet" label="Green" accesskey="G" selected="true"/> <radio id="yellow" label="Blue" accesskey="B" disabled="true"/> </radiogroup> Attributes accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. command Type: id Set to the id of a command element that is being observed by the element. ...
... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
... with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. focused Type: boolean This attribute is true if the element is focused. group Type: string group name Buttons with type="radio" and the same value for their group attribute are put into the same group. Only one button from each group can be checked at a time. If the user selects one the buttons, the others in the group are unchecked. image Type: URI The URI of the image to appear on the element. If this attribute is emp...
...ean Gets and sets the value of the disabled attribute. image Type: image URL Gets and sets the value of the image attribute. label Type: string Gets and sets the value of the label attribute. radioGroup Type: radiogroup element Equivalent to the control property. selected Type: boolean This property's value is true if this element is selected, or false if it is not. This property is read only. This property is available for menuitem and menuseparator elements in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the conte...
radiogroup - Archive of obsolete content
XUL tutorial. Attributes disabled, focused, preference, tabindex, value Properties accessibleType, disabled, focusedItem, itemCount, selectedIndex, selectedItem, tabIndex, value Methods appendItem, checkAdjacentElement, getIndexOfItem, getItemAtIndex, insertItemAt, removeItemAt Examples <radiogroup> <radio id="orange" label="Red"/> <radio id="violet" label="Green" selected="true"/> <radio id="yellow" label="Blue"/> </radiogroup> Attributes disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of for...
... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
... with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. focused Type: boolean This attribute is true if the element is focused. preference Type: id Connects the element to a corresponding preference. This attribute only has any effect when used inside a prefwindow. More information is available in the Preferences System article. tabindex Type: integer The tab order of the element. The tab order is the order in which the focus is moved when the user presses the "tab" key. Elemen...
... appendItem( label, value ) Return type: element Creates a new item and adds it to the end of the existing list of items. You may optionally set a value. The function returns the newly created element. checkAdjacentElement( dir ) Return type: no return value Deselects the currently selected radio button in the group and selects the one adjacent to it. If the argument dir is true, the next radio button is selected. If it is false, the previous radio button is selected. getIndexOfItem( item ) Return type: integer Returns the zero-based position of the specified item. Items are numbered starting at the first item displayed in the list. getItemAtIndex( index ) Return type: element Returns the element that is at the specified index. insertItemAt( index, lab...
richlistbox - Archive of obsolete content
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
... the attribute, as it may need to update additional state. disableKeyNavigation Type: boolean If this attribute is not used, the user can navigate to specific items within the element by pressing keys corresponding to letters in the item's label. This is done incrementally, so typing more letters with select more specific items. This feature may be disabled by setting this attribute to true. preference Type: id Connects the element to a corresponding preference. This attribute only has any effect when used inside a prefwindow. More information is available in the Preferences System article. seltype Type: one of the values below Used to indicate whether multiple selection is allowed. single Only one row may be selected at a time. (Default in listbox and ric...
...l Individual cells can be selected text Rows are selected; however, the selection highlight appears only over the text of the primary column. For richlistbox, this is new in Firefox 3.5. suppressonselect Type: boolean If this attribute is not specified, a select event is fired whenever an item is selected, either by the user or by calling one of the select methods. If set to true, the select event is never fired. tabindex Type: integer The tab order of the element. The tab order is the order in which the focus is moved when the user presses the "tab" key. Elements with a higher tabindex are later in the tab sequence. value Type: string The string attribute allows you to associate a data value with an element. It is not used for any specific purpose, but ...
...urn type: no return value Reverses the selected state of all items. Selected items become deselected, and deselected items become selected. moveByOffset( offset , isSelecting, isSelectingRange) Return type: no return value If offset is positive, adjusts the focused item forward by that many items. If offset is negative, adjusts the focused item backward by that many items. If isSelecting is true, then the selection is also adjusted. If isSelectingRange is also true, then the new item is selected in addition to any currently selected items. If isSelectingRange is false, any existing selection is cleared. Items that are hidden are skipped. removeItemAt( index ) Return type: element Removes the child item in the element at the specified index. The method returns the r...
tabs - Archive of obsolete content
Archive › Mozilla › XUL › tabs
dIndex, tabbox, tabindex, tooltiptextnew, value, Properties accessibleType, disabled, itemCount, selectedIndex, selectedItem, tabIndex, value, Methods advanceSelectedTab, appendItem, getIndexOfItem, getItemAtIndex, insertItemAt, removeItemAt Examples (example needed) Attributes closebutton Obsolete since Gecko 1.9.2 Type: boolean If this attribute is set to true, the tabs row will have a "new tab" button and "close" button on the ends. This feature is used by the tabbrowser to provide the facilities for adding and closing tabs. You can set an image to the "new tab" and "close" buttons by applying them to the tabs-newbutton and tabs-closebutton classes respectively. disableclose Type: boolean If this attribute is true the close button will be dis...
... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
... tab button is clicked. onnewtab Not in Firefox Type: script code This script will be called when the new tab button is clicked. onselect Type: script code This event is sent to the tabs element when this tab is changed. selectedIndex Type: integer Gets and sets the index of the currently selected panel. The first item is at index 0. setfocus Type: boolean If true or omitted, the focus will be given to the first element in the corresponding tabpanel when the tabs are navigated via the keyboard. If this attribute is false, the focus does not change during navigation. tabindex Type: integer The tab order of the element. The tab order is the order in which the focus is moved when the user presses the "tab" key. Elements with a higher tabindex are l...
...(), removeEventListener(), replaceChild(), setAttribute(), setAttributeNode(), setAttributeNodeNS(), setAttributeNS(), setUserData advanceSelectedTab( dir, wrap ) Return type: no return value If the argument dir is set to 1, the currently selected tab changes to the next tab. If the argument dir is set to -1, the currently selected tab changes to the previous tab. If the wrap argument is true, the adjustment will wrap around when the first or last tab is reached. appendItem( label, value ) Return type: element Creates a new item and adds it to the end of the existing list of items. You may optionally set a value. The function returns the newly created element. getIndexOfItem( item ) Return type: integer Returns the zero-based position of the specified item.
timepicker - Archive of obsolete content
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...l respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. hideseconds Type: boolean Indicates whether to show the seconds field. readonly Type: boolean If set to true, then the user cannot change the value of the element. However, the value may still be modified by a script. increment Type: integer Indicates the number of minutes to skip each time the arrows are pressed. This should be used in combination with setting hideseconds to true. tabindex Type: integer The tab order of the element. The tab order is the order in which...
... the value of the increment attribute. is24HourClock Type: boolean A read only value indicating whether a 12-hour or 24-hour clock is used to display times. With a 12-hour clock, an extra field allows the user to pick between AM and PM. This value is determined from the user's locale. isPM Type: boolean If false, the hour is between 0 and 11, and if true, the hour is 12 or greater. minute Type: integer The currently selected minute from 0 to 59. Set this property to change the selected minute. minuteLeadingZero Type: boolean A read only value indicating whether a leading zero should be displayed before the minute when it is less than 10. pmIndicator Type: string The string va...
... minuteLeadingZero Type: boolean A read only value indicating whether a leading zero should be displayed before the minute when it is less than 10. pmIndicator Type: string The string value displayed for hours between noon and midnight, defaulting to PM. This value is determined from the user's locale. readOnly Type: boolean If set to true, then the user cannot modify the value of the element. second Type: integer The currently selected second from 0 to 59. Set this property to change the selected second. secondLeadingZero Type: boolean A read only value indicating whether a leading zero should be displayed before the second when it is less than 10. tabIndex Type: int...
Debugging a XULRunner Application - Archive of obsolete content
to know is displayed on them. See also Debugging JavaScript Prefs Setting the following prefs will make your debugging life much easier! Preferences should be in a .js file in the directory %appname%/defaults/preferences/. It doesn't matter what the file is called (as long as the extension is .js), so debug.js is as good as any! /* debugging prefs */ pref("browser.dom.window.dump.enabled", true); pref("javascript.options.showInConsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); Don't forget to change these preferences back to their defaults when you've finished debugging; leaving them as-is can significantly harm performance and usability. See: Preference reference for more infor...
...Preference reference for more information about these preferences. Console To enable a console on windows, start XULRunner with the -console argument. Note that -console goes after the application.ini argument: e.g. xulrunner.exe /path/to/application.ini -console To output text to the console, use dump("my text here\n");. This will only work if the pref pref("browser.dom.window.dump.enabled", true) is enabled. To output dump calls instead to a file, set browser.dom.window.dump.file to the file destination where the log should be created and restart the application. If you would like the console messages to appear in the console you used to launch the application, you can use the Gecko Console Redirector. Precompiled binaries are available in the zipped archive https://github.com/matthew...
...S console, start XULRunner with the -jsconsole argument. Note: If you are not using the stub executable to launch the application, the -jsconsole argument is after the application.ini argument: e.g. xulrunner.exe /path/to/application.ini -jsconsole By default the JS console only shows errors from web content. To show errors in chrome JavaScript, the pref pref("javascript.options.showInConsole", true) must be set. To log JS errors to disk, set the environment variable XRE_CONSOLE_LOG to the path to the filename. i.e. export XRE_CONSOLE_LOG=/path/to/logfile or set XRE_CONSOLE_LOG=C:\path\to\logfile. To output messages to the JavaScript console There are two ways to output messages to the JS console: Components.utils.reportError(str) will output str as an "error" (i.e. with the red stop i...
... for your app. DebuggerServer.addBrowserActors("myXULRunnerAppWindowType"); } DebuggerServer.openListener(6000); For XULRunner version 37+ the code to enable the debugger has changed: Components.utils.import('resource://gre/modules/devtools/dbg-server.jsm'); if (!DebuggerServer.initialized) { DebuggerServer.init(); DebuggerServer.addBrowserActors(); DebuggerServer.allowChromeProcess = true; } let dbgListener=DebuggerServer.createListener(); dbgListener.portOrPath=6000; dbgListener.open(); Add the following to your prefs.js: (in recent ffox, edit about:config instead) pref("devtools.debugger.remote-enabled", true); In Firefox, go to Tools > Web Developer > Connect... and you should be able to point the debugger to your app. Happy debugging :) Venkman Follow these instruction...
NPClass - Archive of obsolete content
ULL, free() is called isntead. invalidate Called on live objects that belong to a plugin instance that is being destroyed. This call is always followed by a call to the deallocate function, or free(). Any attempt to use an invalidated object will result in undefined behavior. hasMethod Called by NPN_HasMethod() to determine whether or not a specified method exists on a given NPObject. Returns true if the method exists, otherwise returns false. invoke Called by NPN_Invoke() to invoke a specific method on a given NPObject. Returns true if invocation succeeded or false if an error occurred. invokeDefault Called by NPN_InvokeDefault() to invoke the default method (if available) on a given NPObject. Returns true if invocation succeeded or false if an error occurred. hasProperty Called by ...
...e a specific method on a given NPObject. Returns true if invocation succeeded or false if an error occurred. invokeDefault Called by NPN_InvokeDefault() to invoke the default method (if available) on a given NPObject. Returns true if invocation succeeded or false if an error occurred. hasProperty Called by NPN_HasProperty() to check whether a given property exists on a given NPObject. Returns true if the specified property exists, otherwise returns false. getProperty Called by NPN_GetProperty() to get the value of the specified property on a given NPObject. Returns true if the value was successfully retrieved, otherwise returns false. setProperty Called by NPN_SetProperty() to set the value of the specified property on a given NPObject. ...
... enumerate Called by NPN_Enumerate. ...
... enumerate Called by NPN_Enumerate. This field is available only if structVersion is NP_CLASS_STRUCT_VERSION_ENUM (2) or greater. construct Called by NPN_Construct. This field is available only if structVersion is NP_CLASS_STRUCT_VERSION_CTOR (3) or greater. ...
NPN_SetValue - Archive of obsolete content
Syntax #include <npapi.h> NPError NPN_SetValue(NPP instance, NPPVariable variable, void *value); Parameters The function has the following parameters: instance Pointer to the plugin instance setting the variable. ...
...riable, void *value); Parameters The function has the following parameters: instance Pointer to the plugin instance setting the variable. ...
... parameter and FALSE as the value parameter. By default, plugins are windowed. NPPVpluginTransparentBool (Windows and Unix) specifies that a plugin is either opaque or transparent. To specify an opaque mode, the plugin calls NPN_SetValue with NPPVpluginTransparentBool for the variable parameter and FALSE for the value parameter. To specify a transparent mode, the value parameter should be set to TRUE. NPPVjavascriptPushCallerBool sets whether you are pushing or popping the appropriate JSContext off the stack (see the two-way scriptability article on the Mozilla Plugins project page for more details). NPPVpluginKeepLibraryInMemory specifies that the plugin does not want to be unloaded from memory after the page which initiated it has gone. Normally, when the browser navigates away from the p...
...tive, the plugin calls its NP_Shutdown method and the plugin dll gets unloaded from memory. If this is not desired, the plugin can instruct the browser not to unload the dll and not to call NP_Shutdown when the page is left. In such a case all this will be done on the browser shutdown. The plugin calls NPN_SetValue any time with NPPVpluginKeepLibraryInMemory as variable parameter and value set to TRUE. By default, the dll will be unloaded from memory preceded by an NP_Shutdown call. Remarks All four variable values are boolean. Although the function prototype has type of value void *, the actual boolean should be placed there, not a pointer to a boolean. The browser code reads this parameter as follows (NPPVpluginWindowBool as an example): NPError NP_EXPORT _setvalue(NPP npp, NPPVariable va...
Browser Detection and Cross Browser Support - Archive of obsolete content
ight; } else if (document.layers) { // NN4 height = window.innerHeight; } else if (document.getElementById) { // They think this is Gecko // but could be wrong! height = window.innerHeight; } else { // other height = 0; } The approach is incorrect since it assumes that the only other browser besides Internet Explorer 5+ that implements document.getElementById is Gecko. This is not true today and will become even less true as more browsers which support the W3C DOM Standards are introduced in the future. Recommendations Target the standards and not particular browsers While the period from 1994-2000 was dominated by incompatible non-standard browsers from Netscape and Microsoft, today the dominating factor in web development are the standards proposed by the World Wide Web Co...
...les */ /*/*/ /* Advanced CSS rules ignored by Navigator 4 */ </STYLE> DevEdge uses this technique to hide advanced CSS from Navigator 4. Use feature oriented object detection Object detection is a powerful method of providing cross browser support in your web content. Although you can use object detection as just another means of distinguishing between vendor/version the technique shows it's true power when used to detect features rather than browsers. Feature oriented object detection is the testing for the existence of specific objects before attempting to use them in a script. The classic example is: if (document.images) { // code which processes the images } The advantage to feature detection is that it will work regardless of the vendor/version. We can rewrite the earlier examp...
...They use downlevel pages for less capable browsers combined with object based feature detecti...
... 1.0.1 or Netscape 6.2.x/CompuServe 7 // built after August 1, 2002 var rv = geckoGetRv(); var found = false; if (rv >= 0) { // Gecko browser if (navigator.productSub > '20020801') { if (rv >= 1.0001) { found = true; } else if (rv >= 0.0904 && rv < 0.0905) { if (navigator.vendor == 'Netscape6' || navigator.vendor == 'CS 2000 7.0') { found = true; } } } } Example 4 - The International Herald-Tribune This site illustrates many of the techniques described in this article. They use downlevel pages for less capable browsers combined with object based feature detection to produce a compelling and interesting site. Examples From DevEdge * xbDOM * xbMarquee * xbPositionableElement * xbAnimatedElement Conclusion A...
Reference - Archive of obsolete content
most of them at least) say that the browser can use the JS 1.2 engine with the language="JavaScript1.2" tag, but this is no longer possible; language="JavaScript1.x" tags will always use the current version now, i.e. JS 1.6. So while the examples do show what JS 1.2 does, they incorrectly indicate that it's possible to switch to the 1.2 engine. --Maian 05:41, 22 September 2005 (PDT) This is true. The wording should be changed with the Javascript 1.x examples, as well as refer to the versions in the past tense. I also support the use of a deprecated pre box with these examples. Since it's been 9 months since the last comment on this, I think I'll go ahead and change all of the examples. If anyone disagrees, you can always revert. Sevenspade 13:19, 2 July 2006 (PDT) After some though...
...t 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 ... Actual Question so my question is , what the heck is going on here ... IS Function same as Object. is Function an instance of Object or is Object an insta...
...... --Aaike82 18:54, 18 August 2006 (PDT) Actual Answer: Object > (Function, everything else). Everything in JavaScript is descended from Object, including functions. All functions in JavaScript (that is, every object that has an internal [[Call]] or [[Construct]] property) are functions as well as objects (including the Function object itself). The reason Object instanceof Function evaluates to true is because Object can be used as a constructor function. A subset of the "Object > (Function, everything else)" chain could be Object > Function > (Object, Function, Array, String, Boolean, Number, Date, RegExp, Error). Array, for example, as a constructor function is an instance of the Function object, which happens to be an instance of Object; therefore, Array is also an instance of Object. Thi...
... //Function Function.constructor.constructor; //Function . . . Function.constructor.constructor.constructor.constructor.constructor . . . ; //Function Note that Math is not a constructor function, but merely a global object with methods and properties useful to perform various mathematical operations. This is why Math instanceof Object evaluates to true, but Math instanceof Function does not. Compare this to the Date object. Like Math, Date is a global object that contains useful methods (Date.parse() and Date.UTC()). In addition to this, however, Date is also a constructor function: it constructs objects of the class Date, and thus is an instance of both Object and Function, whereas Math is merely an instanceof Object. --Sevenspade 14:23, 17 Ja...
XForms Custom Controls - Archive of obsolete content
// Here we should refresh custom control. </body> </method> <constructor> // We should redirect calls of input's 'refresh' method to custom control 'refresh' method. var control = this; var refreshStub = function() { control.refresh(); } this.ref1.refresh = refreshStub; this.ref2.refresh = refreshStub; </constructor> <property name="ref1" readonly="true" onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref1');"/> <property name="ref2" readonly="true" onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref2');"/> </implementation> New Host Language The Mozilla XForms implementation currently only supports XForms hosted in XHTML or XUL documents. If you need to...
...cessors interface allows access to the value and the state of the instance node that the control is bound to (see extensions/xforms/nsIXFormsAccessors.idl). Currently interface is: interface nsIXFormsAccessors : nsISupports { /** * Return value of instance node. */ DOMString getValue(); /** * Set value of instance node. */ void setValue(in DOMString value); /** * Return true if the instance node is readonly as determined by the MDG. */ boolean isReadonly(); /** * Return true if the instance node is relevant as determined by the MDG. */ boolean isRelevant(); /** * Return true if the instance node is required as determined by the MDG. */ boolean isRequired(); /** * Return true if instance node is valid as determined by the MDG. */ ...
...etermined by the MDG. */ boolean isReadonly(); /** * Return true if the instance node is relevant as determined by the MDG. */ boolean isRelevant(); /** * Return true if the instance node is required as determined by the MDG. */ boolean isRequired(); /** * Return true if instance node is valid as determined by the MDG. */ boolean isValid(); /** * Return true if the control is bound to an instance node. */ boolean hasBoundNode(); /** * Return the bound instance node. */ nsIDOMNode getBoundNode(); /** * Set the content of the instance node. If aForceUpdate is true then the * XForms model will rebuild/recalculate/revalidate/refresh. */ void setContent(in nsIDOMNode aNode, in boolean aForceUpdate); } note: setContent() can...
...ation implements="nsIXFormsUIWidget"> <method name="refresh"> <body> <!-- set the src attribute on the html:img to be the simpleContent of the instance node bound to this control --> var img = document.getAnonymousElementByAttribute(this, "anonid", "content"); img.setAttribute("src", this.stringValue); return true; </body> </method> </implementation> </binding> </bindings> <xf:model> <xf:instance xmlns=""> <data> <curimg></curimg> <img label="Firefox">http://www.mozilla.com/images/firefox-logo-64x64.png</img> <img label="Thunderbird">http://www.mozilla.com/images/thunderbird-logo-64x64.png</img> <img label="Bugzilla">http://www.mozilla.org/images/p-bugz.gif</img> ...
Describing microformats in JavaScript - Archive of obsolete content
of any properties that must be specified. This may be left out if all properties are optional. properties A structure describing the properties of the microformat. Property specifications Each property in the properties structure is specified by its name, and may include additional attributes if the property so requires. Standard attributes are: plural A boolean value indicating that, if true indicates that the property can have multiple values. If a property is plural, it is returned as an array. virtual A boolean value indicating whether or not the property is virtual. If it's virtual, the virtualGetter() method will be called to attempt to create the property if it doesn't exist. virtualGetter A function that is called to get a virtual property's value. This is only used if vir...
...es that the property can have multiple values. If a property is plural, it is returned as an array. virtual A boolean value indicating whether or not the property is virtual. If it's virtual, the virtualGetter() method will be called to attempt to create the property if it doesn't exist. virtualGetter A function that is called to get a virtual property's value. This is only used if virtual is true. value The property's default value. subproperties It's possible for a property to itself include more properties; to do so, include them in a subproperties structure within the property. dataType The type of data contained by the property. Possible values are: dateTime An ISO date anyURI A URI email An email address tel A telephone number HTML HTML including tags float A f...
...at_property A specific property within the microformat specified by microformat. custom Custom data A simple example The hCard microformat for defining contact information makes use of the adr microformat to define an address. The adr microformat is defined as follows: var adr_definition = { mfVersion: 0.8, mfObject: adr, className: "adr", properties: { "type" : { plural: true, types: ["work", "home", "pref", "postal", "dom", "intl", "parcel"] }, "post-office-box" : { }, "street-address" : { plural: true }, "extended-address" : { }, "locality" : { }, "region" : { }, "postal-code" : { }, "country-name" : { } } }; The properties are quite simple here. The type property indicates the type of addre...
...This allows an address to be marked as being, for example, a work address for receiving parcels. The street-address property is plural as well. This allows multiple lines of address information to be contained in the street-address array. ...
RDF in Mozilla FAQ - Archive of obsolete content
emoteDataSource interface has the interfaces // that we need to setup the datasource. var remote = ds.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource); // Be sure that your web server will deliver this as text/xml (recommended) or text/rdf! remote.Init("http://www.mozilla.org/some-rdf-file.rdf"); // Make it load! Note that this will happen asynchronously. By setting // aBlocking to true, we could force it to be synchronous, but this // is generally a bad idea, because your UI will completely lock up! 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. How do I reload an RDF/XML datasource? You c...
... aTruthValue). nsISimpleEnumerator ArcLabelsIn(aTarget). nsISimpleEnumerator ArcLabelsOut(aSource). You can also use the RDF container interfaces to access information contained in RDF containers. How do I change information in the datasource? To use 'Assert' to add one assertion and 'Unassert' to remove one. Refer to Mozilla RDF Back end Architecture ds.Assert(homepage, FV_quality, value, true); ds.Unassert(homepage, FV_quality, value, true); How do I save back changes to an RDF/XML datasource? An RDF/XML datasource can be QueryInterface()'d to nsIRDFRemoteDataSource. This interface has a Flush() method, which will attempt to write the contents of the datasource back to the URL from which they were loaded, using a protocol specific mechanism (e.g., a file: URL just writes the file; ...
...lasses["@mozilla.org/rdf/datasource;1?name=bookmarks"]. getService(Components.interfaces.nsIRDFDataSource); // Now do something interesting with it... if (bookmarks.HasAssertion( RDF.GetResource("http://home.netscape.com/NC-rdf#BookmarksRoot"), RDF.GetResource("http://home.netscape.com/NC-rdf#child"), RDF.GetResource("http://home.netscape.com/NC-rdf#PersonalToolbarFolder"), true) { // ... } Alternatively, some datasources have "special" RDF-friendly ContractIDs that make it easy to instantiate the datasource using either the nsIRDFSerivce's GetDataSource() method or the datasources attribute on a XUL template. These ContractIDs are of the form @mozilla.org/rdf/datasource;1?name=name And are accessable via GetDataSource() and the datasources attribute using the sho...
...ipts, and are runnable from HTTP directly. See also duplicates.rdf (for live RDF feed from Mozilla) alongside duplicates.xul. Note that for these to work, you have to relax Mozilla's security model. To do this, add the following line to your preferences file. (Shut down Mozilla first since it overwrites your preferences file when you quit.) user_pref("signed.applets.codebase_principal_support", true); Mozilla will ask you if you want to grant the scripts in duplicates.xul permission to access XPConnect; respond in the affirmative. Currently, Mozilla does not allow unprivileged access to the RDF interfaces and services; see bug 122846 for details. Please mail danbri, mozilla-rdf or waterson with URLs if you are aware of other examples to which we ought to link! Notes See also W3C RDF ...
Common causes of memory leaks in extensions - Extensions
Loaded", 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. However, while this is still true, the window.setInterval() in the example originates from the outer chrome window (browser.xul) and not from the content window. Hence the interval will only be destroyed when the outer window is unloaded (i.e. when the user closes the whole browser window) but not when the content window unloads (i.e. when the user closes the tab). The interval function in the example would still hold a reference...
...is unloaded. If the window in question is browser.xul or some long-lived web app such as Gmail, the leaked compartment might survive for quite some time. function leakref() {} function main(window) { // This is a potential leak, as the window (e.g. browser.xul) will hold on to // the leakref function and the enclosing compartment via the listener. ...
...It is part of Edward Lee's restartless boilerplate. ...
..." : "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. To avoid this problem explicitly call nsIObserverService.removeObserver() in an unload event listener. You may also specify ownsWeak = true in the call to nsIObserverService.addObserver(), but that might require you to properly implement weak references as well. In overlay code you may use an unload event listener: addEventListener("unload", function() { Services.obs.removeObserver(myObserver, "private-browsing"); }, false); In bootstrap.js (restartless add-ons) unregister your observer in your shutdown function: function shut...
Paddle and keyboard controls - Game development
et up two event listeners. 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. ...
...eys on your keyboard (when they are pressed), the keyDownHandler() function will be executed. The same pattern is true for the second listener: keyup events will fire the keyUpHandler() function (when the keys stop being pressed). Add these to your code now, below the addEventListener() lines: function keyDownHandler(e) { if(e.key == "Right" || e.key == "ArrowRight") { rightPressed = true; } else if(e.key == "Left" || e.key == "ArrowLeft") { leftPressed = true; } } function keyUpHandler(e) { if(e.key == "Right" || e.key == "ArrowRight") { rightPressed = false; } else if(e.key == "Left" || e.key == "ArrowLeft") { leftPressed = false; } } When we press a key down, this information is stored in a variable. The relevant variable in...
...When the key is released, the variable is set back to false. Both functions take an event as a parameter, represented by the e variable. From that you can get useful information: the key holds the information about the key that was pressed. ...
...unctions take an event as a parameter, represented by the e variable. From that you can get useful information: the key holds the information about the key that was pressed. Most browsers use ArrowRight and ArrowLeft for the left/right cursor keys, but we need to also include Right and Left checks to support IE/Edge browsers. If the left cursor is pressed, then the leftPressed variable is set to true, and when it is released, the leftPressed variable is set to false. The same pattern follows with the right cursor and the rightPressed variable. The paddle moving logic We've now set up the variables for storing the info about the pressed keys, event listeners, and relevant functions. Next we'll get into the code to use all of the things we just set up and to move the paddle on the screen. Ins...
Visual typescript game engine - Game development
untsSystem: boolean = false; Networking is disabled by default. Find configuration at ./src/lib/client-config.ts /** * Addson * All addson are ansync loaded scripts. * - Cache is based on webWorkers. * - hackerTimer is for better performace also based on webWorkers. * - dragging is script for dragging dom elements. */ private addson: Addson = [ { name: "cache", enabled: true, scriptPath: "externals/cacheInit.ts", }, { name: "hackerTimer", enabled: true, scriptPath: "externals/hack-timer.js", }, { name: "dragging", enabled: true, scriptPath: "externals/drag.ts", }, ]; /** * @description This is main coordinary types of positions * Can be "diametric-fullscreen" or "frame". * @property drawRefer...
...to connect multimedia server MultiRTC3. * I will use it for explicit video chat multiplatform support. * Default value is 9001 */ private broadcasterPort: number = 9001; /** * @description Important note for this property: if you * disable (false) you cant use Account system or any other * network. Use 'false' if you wanna make single player game. * In other way keep it 'true'. */ private appUseNetwork = false; /** * appUseAccountsSystem If you don't want to use session * in your application just setup this variable to the false. */ private appUseAccountsSystem: boolean = false; /** * appUseBroadcaster Disable or enable broadcaster for * video chats. */ private appUseBroadcaster: boolean = false; /** * Possible variant by default...
...able or enable broadcaster for * video chats. */ private appUseBroadcaster: boolean = false; /** * Possible variant by default : * "register", "login" */ private startUpHtmlForm: string = "register"; private gameList: any[]; /** * Implement default gamePlay variable's */ private defaultGamePlayLevelName: string = "level1"; private autoStartGamePlay: boolean = true; Start the dependency system from app.ts The first game template is Platformer. This is high-level programming in this software. Class GamePlay extends Platformer, it good for start. Class Starter is base class for my canvas part and matter.ts (matter.js) implementation. It is injected to the Platformer to make full operated work. gamesList args for IOC constructor is for now just symbolic f...
...l networking config: Config property defined in constructor from ServerConfig class. this.networkDeepLogs = false; this.rtcServerPort = 12034; this.rtc3ServerPort = 12034; this.connectorPort = 1234; this.domain = "192.168.0.14"; this.masterServerKey = "multi-platformer-sever1.maximum"; this.protocol = "http"; this.isSecure = false; this.appUseAccountsSystem = true; this.appUseVideoChat = true; this.databaseName = "masterdatabase"; this.databaseRoot = "mongodb://localhost:27017"; - The running server is easy : npm run rtc With this cmd: npm run rtc we run server.js and connector.ts WebSocket. A connector is our account session used for login, register etc. Implemented video chat based on webRTC protocol. - Running rtc3 server is also e...
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. For example, in JavaScript, Boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops). Below is some JavaScript pseudocode (it's not truly executable code) demonstrating this concept. ...
...only the values true or false. For example, in JavaScript, Boolean conditionals are often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops). Below is some JavaScript pseudocode (it's not truly executable code) demonstrating this concept. ...
...e often used to decide which sections of code to execute (such as in if statements) or repeat (such as in for loops). Below is some JavaScript pseudocode (it's not truly executable code) demonstrating this concept. ...
...pt. /* 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. Learn more General knowledge Boolean on Wikipedia Technical reference The JavaScript global object: Boolean JavaScript data types and data structures ...
Video and Audio APIs - Learn web development
splay: flex), to make things easier. Next, let's look at our button icons: @font-face { font-family: 'HeydingsControlsRegular'; src: url('fonts/heydings_controls-webfont.eot'); src: url('fonts/heydings_controls-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/heydings_controls-webfont.woff') format('woff'), url('fonts/heydings_controls-webfont.ttf') format('truetype'); font-weight: normal; font-style: normal; } button:before { font-family: HeydingsControlsRegular; font-size: 20px; position: relative; content: attr(data-icon); color: #aaa; text-shadow: 1px 1px 0px black; } First of all, at the top of the CSS we use a @font-face block to import a custom web font. This is an icon font -- all the characters of the alphabet equate to commo...
...dia); Now to define playPauseMedia() -- add the following, again at the bottom of your code: function playPauseMedia() { if(media.paused) { play.setAttribute('data-icon','u'); media.play(); } else { play.setAttribute('data-icon','P'); media.pause(); } } Here we use an if statement to check whether the video is paused. The HTMLMediaElement.paused property returns true if the media is paused, which is any time the video is not playing, including when it is set at 0 duration after it first loads. If it is paused, we set the data-icon attribute value on the play button to "u", which is a "paused" icon, and invoke the HTMLMediaElement.play() method to play the media. On the second click, the button will be toggled back again -- the "play" icon will be shown aga...
...hether the active class has been set on the rwd button, indicating that it has already been pressed. The classList is a rather handy property that exists on every element -- it contains a list of all the classes set on the element, as well as methods for adding/removing classes, etc. We use the classList.contains() method to check whether the list contains the active class. This returns a boolean true/false result. If active has been set on the rwd button, we remove it using classList.remove(), clear the interval that has been set when the button was first pressed (see below for more explanation), and use HTMLMediaElement.play() to cancel the rewind and start the video playing normally. If it hasn't yet been set, we add the active class to the rwd button using classList.add(), pause the ...
... hour long or more (well, it won't display hours; just minutes and seconds). Can you figure out how to change the example to make it display hours? Because <audio> elements have the same HTMLMediaElement functionality available to them, you could easily get this player to work for an <audio> element too. Try doing so. Can you work out a way to turn the timer inner <div> element into a true seek bar/scrobbler -- i.e., when you click somewhere on the bar, it jumps to that relative position in the video playback? As a hint, you can find out the X and Y values of the element's left/right and top/bottom sides via the getBoundingClientRect() method, and you can find the coordinates of a mouse click via the event object of the click event, called on the Document object. For example: do...
Basic math in JavaScript — numbers and operators - Learn web development
To gain familiarity with the basics of math in JavaScript. Everybody loves math Okay, maybe not. Some of us like math, some of us have hated math ever since we had to learn multiplication tables and long division in school, and some of us sit somewhere in between the two. But none of us can deny that math is a fundamental part of life that we can't get very far without. This is especially true when we are learning to program JavaScript (or any other language for that matter) -- so much of what we do relies on processing numerical data, calculating new values, and so on, that you won't be surprised to learn that JavaScript has a full-featured set of math functions available. This article discusses only the basic parts that you need to know now. Types of numbers In programming, even t...
...itself. The following will return an error: 3++; So, you can only increment an existing variable. Try this: let num1 = 4; num1++; Okay, strangeness number 2! When you do this, you'll see a value of 4 returned -- this is because the browser returns the current value, then increments the variable. You can see that it's been incremented if you return the variable value again: num1; The same is true of -- : try the following let num2 = 6; num2--; num2; Note: You can make the browser do it the other way round -- increment/decrement the variable then return the value -- by putting the operator at the start of the variable instead of the end. Try the above examples again, but this time use ++num1 and --num2. Assignment operators Assignment operators are operators that assign a value to a ...
...culated using the numbers 50 and 3, the multiplication operator, and the addition assignment operator. Don't worry if you totally mess the code up. You can always press the Reset button to get things working again. After you've answered all the above questions correctly, feel free to play with the code some more or create your own challenges. 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. Operator Name Purpose Example === Strict equality Tests whether the left and right values are identical to one another 5 === 2 + 4 !== Strict-non-equality Tests whether the left and right values are not identical to one another 5 ...
...pt, but they differ from ===/!==. The former versions test whether the values are the same but not whether the values' datatypes are the same. The latter, strict versions test the equality of both the values and their datatypes. The strict versions tend to result in fewer errors, so we recommend you use them. 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. These are very useful, as they allow us to make decisions in our code, and they are used every time we want to make a choice of some kind. For example, booleans can be used to: Display the correct text label on a button depending on whether a feature is turned on or off Display a game over message if a game is over or a victory ...
React interactivity: Editing, filtering, conditional rendering - Learn web development
operator. In the case of our <Todo /> component, our condition is "Is this task being edited?" Change the return statement inside Todo() so that it reads like so: return <li className="todo">{isEditing ? editingTemplate : viewTemplate}</li>; Your browser should render all your tasks just like before. 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! Toggling the <Todo /> templates At long last, we are ready to make our final core feature interactive. To start with, we want to call setEditing() with a value of true when a user presses the "Edit" button in our viewTemplate, so that we can switch templates. Update the "Edit" button in the viewTempla...
...the next section! Toggling the <Todo /> templates At long last, we are ready to make our final core feature interactive. To start with, we want to call setEditing() with a value of true when a user presses the "Edit" button in our viewTemplate, so that we can switch templates. Update the "Edit" button in the viewTemplate like so: <button type="button" className="btn" onClick={() => setEditing(true)}> Edit <span className="visually-hidden">{props.name}</span> </button> Now we'll add the same onClick handler to the "Cancel" button in the editingTemplate, but this time we'll set isEditing to false so that it switches us back to the view template. Update the "Cancel" button in the editTemplate like so: <button type="button" className="btn todo-cancel" onClick={() => setEditing(false...
...d: Each filter should have a unique name. Each filter should have a unique behavior. A JavaScript object would be a great way to relate names to behaviors: each key is the name of a filter; each property is the behavior associated with that name. At the top of App.js, beneath our imports but above our App() function, let's add an object called FILTER_MAP: const FILTER_MAP = { All: () => true, Active: task => !task.completed, Completed: task => task.completed }; The values of FILTER_MAP are functions that we will use to filter the tasks data array: The All filter shows all tasks, so we return true for all tasks. The Active filter shows tasks whose completed prop is false. The Completed filter shows tasks whose completed prop is true. Beneath our previous addition, add the ...
...mpleted={task.completed} key={task.id} toggleTaskCompleted={toggleTaskCompleted} deleteTask={deleteTask} editTask={editTask} /> )); In order to decide which callback function to use in Array.prototype.filter(), we access the value in FILTER_MAP that corresponds to the key of our filter state. When filter is All, for example, FILTER_MAP[filter] will evaluate to () => true. Choosing a filter in your browser will now remove the tasks that do not meet its criteria. The count in the heading above the list will also change to reflect the list! Summary So that's it -- our app is now functionally complete. However, now that we've implemented all of our features, we can make a few improvements to ensure that a wider range of users can use our app. Our next article ro...
TypeScript support in Svelte - Learn web development
ns of your code base. Type inference: Enables you to take advantage of many TypeScript features even without declaring variable types. Availability of new and future JavaScript features: TypeScript transpiles many recent ES6 features to plain old-school JavaScript, allowing you to use them even on user-agents that don't support them natively yet. TypeScript also has some disadvantages: Not true static typing: Types are only checked at compile time, and they are removed from the generated code. Steep learning curve: Even though TypeScript is a superset of JavaScript and not a completely new language, there is a considerable learning curve, especially if you have no experience at all with static languages like Java or C#. More code: You have to write and maintain more code. No replacem...
...de. Steep learning curve: Even though TypeScript is a superset of JavaScript and not a completely new language, there is a considerable learning curve, especially if you have no experience at all with static languages like Java or C#. More code: You have to write and maintain more code. No replacement for automatic tests: Even though types might help you catch several bugs, TypeScript is not a true replacement for a comprehensive suite of automated tests. Boiler plate code: Working with types, classes, interfaces, and generics can lead to over-engineered code bases. There seems to be a broad consensus that TypeScript is particularly well suited for large-scale projects, with many developers working on the same code base. And it is indeed being used by several large-scale projects, like A...
... Set the type of our initialTodos array to TodoType[]. This is how the contents will end up: // stores.ts import { writable } from 'svelte/store' import { localStore } from './localStore.js' import type { TodoType } from './types/todo.type' export const alert = writable('Welcome to the To-Do list app!') const initialTodos: TodoType[] = [ { id: 1, name: 'Visit MDN web docs', completed: true }, { id: 2, name: 'Complete the Svelte Tutorial', completed: false }, ] export const todos = localStore('mdn-svelte-todo', initialTodos) Remember to update the import statements in App.svelte, Alert.svelte, and Todos.svelte. Just remove the .js extension, like this: import { todos } from '../stores' Now onto localStore.js. Update the import statement in stores.ts, like so: impor...
... The code so far Git To see the state of the code as it should be at the end of this article, access your copy of our repo like this: cd mdn-svelte-tutorial/08-next-steps Or directly dow...
Componentizing our Svelte app - Learn web development
e // restores name to its initial value and editing = false // and exit editing mode } function onSave() { update({ name: name }) // updates todo name editing = false // and exit editing mode } function onRemove() { dispatch('remove', todo) // emit remove event } function onEdit() { editing = true // enter editing mode } function onToggle() { update({ completed: !todo.completed}) // updates todo status } Updating the markup Now we need to update our Todo component's markup to call the above functions when the appropriate actions are taken. To handle the the editing mode we are using the editing variable, which is a boolean. When it's true, it should display ...
...n it's not in editing mode it will display the checkbox, the todo name and the buttons to edit and delete the todo. To achieve this we will use an if block. The if block conditionally renders some markup. Take into account that it won't just show or hide the markup based on the condition -- it will dynamically add and remove the elements from the DOM, depending on the condition. 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. Thanks to Svelte reactivity, assigning the value of the editing variable will be enough to display the correct HTML elements. The following gives you an idea of what the basic if block structure looks like: <div class="stack-small"> {#if editing} <!-- markup for editing tod...
...ass="btn" on:click={onEdit}> Edit<span class="visually-hidden"> {todo.name}</span> </button> <button type="button" class="btn btn__danger" on:click={onRemove}> Delete<span class="visually-hidden"> {todo.name}</span> </button> </div> {/if} </div> It is worth noting that: When the user presses the Edit button we execute onEdit(), which just sets the editing variable to true. When the user clicks on the checkbox we call the onToggle() function, which executes update(), passing an object with the new completed value as a parameter. The update() function emits the update event, passing as additional information a copy of the original todo with the changes applied. Finally, the onRemove() function emits the remove event, passing the todo to be deleted as additional d...
... 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 ...
Working with Svelte stores - Learn web development
Update the <script> section of your Alert.svelte component like so: <script> import { onDestroy } from 'svelte' import { alert } from '../stores.js' export let ms = 3000 let visible let timeout const onMessageChange = (message, ms) => { clearTimeout(timeout) if (!message) { // hide Alert if message is empty visible = false } else { visible = true // show alert if (ms > 0) timeout = setTimeout(() => visible = false, ms) // and hide it after ms milliseconds } } $: onMessageChange($alert, ms) // whenever the alert store or the ms props changes run onMessageChange onDestroy(()=> clearTimeout(timeout)) // make sure we clean-up the timeout </script> And update t...
...unction that will take care of controlling whether the Alert is visible or not. With $: onMessageChange($alert, ms) we tell Svelte to run this function whenever the $alert store or the ms prop changes. Whenever the $alert store changes, we'll clean up any pending timeout. If $alert is empty, we set visible to false and the Alert will be removed from the DOM. If it is not empty, we set visible to true and use the setTimeout() function to clear the alert after ms milliseconds. Finally, with the onDestroy() lifecycle function, we make sure to call the clearTimeout() function. We also added an SVG icon above the alert paragraph, to make it look a bit nicer. Try it out again, and you should see the changes. Making our Alert component accessible Our Alert component is working fine, but it's not...
...import the store and use it in App.svelte. Just remember that to access the todos now we have to use the $todos reactive $store syntax. Update your App.svelte file like this: <script> import Todos from './components/Todos.svelte' import Alert from './components/Alert.svelte' import { todos } from './stores.js' $todos = [ { id: 1, name: 'Create a Svelte starter app', completed: true }, { id: 2, name: 'Create your first component', completed: true }, { id: 3, name: 'Complete the rest of the tutorial', completed: false } ] </script> <Alert /> <Todos bind:todos={$todos} /> Try it out; everything should work. Next we'll see how to define our own custom stores. How to implement a store contract: The theory You can create your own stores without relying on s...
... is mostly initializing and converting stuff. Now we will use our local store from stores.js to create our locally persisted todos store. Update stores.js like so: import { writable } from 'svelte/store' import { localStore } from './localStore.js' export const alert = writable('Welcome to the To-Do list app!') const initialTodos = [ { id: 1, name: 'Visit MDN web docs', completed: true }, { id: 2, name: 'Complete the Svelte Tutorial', completed: false }, ] export const todos = localStore('mdn-svelte-todo', initialTodos) Using localStore('mdn-svelte-todo', initialTodos), we are configuring the store to save the data in web storage under the key mdn-svelte-todo. We also set a couple of todos as initial values. Now let's get rid of the hardcoded todos in App.svelte. Up...
Vue conditional rendering: editing existing todos - Learn web development
"button" class="btn" @click="onCancel"> Cancel <span class="visually-hidden">editing {{label}}</span> </button> <button type="submit" class="btn btn__primary"> Save <span class="visually-hidden">edit for {{label}}</span> </button> </div> </form> </template> <script> export default { props: { label: { type: String, required: true }, id: { type: String, required: true } }, data() { return { newLabel: this.label }; }, methods: { onSubmit() { if (this.newLabel && this.newLabel !== this.label) { this.$emit("item-edited", this.newLabel); } }, onCancel() { this.$emit("edit-cancelled"); } } }; </script> <style scoped> .edit-label { font-f...
... </button> </div> </div> </template> We've added a wrapper <div> around the whole template for layout purposes. We've also added "Edit" and "Delete" buttons: The "Edit" button, when clicked, will toggle displaying the ToDoItemEditForm component so we can use it to edit our todo item, via an event handler function called toggleToItemEditForm(). This handler will set an isEditing flag to true. To do that, we'll need to first define it inside our data() property. The "Delete" button, when clicked, will delete the todo item via an event handler function called deleteToDo(). In this handler we'll emit an item-deleted event to our parent component so the list can be updated. Let's define our click handlers, and the necessary isEditing flag. Add isEditing below your existing isDone dat...
...Let's define our click handlers, and the necessary isEditing flag. 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). If isEditing is true, we want to use that flag to display our ToDoItemEditForm instead of the checkbox. To do that, we'll use another Vue directive: v-if. The v-if directive will only render a block if the value passed to it is trut...
...istened for inside App.vue, see above), and finally clears the new label <input>. ToDoItem.vue checkbox <input> listens for change event. Result: checkbox-changed event emitted when the checkbox is checked/unchecked (which is then listened for inside App.vue; see above). "Edit" <button> listens for click event. Result: toggleToItemEditForm() method is invoked, which toggles this.isEditing to true, which in turn displays the todo item's edit form on re-render. "Delete" <button> listens for click event. Result: deleteToDo() method is invoked, which emits the item-deleted event (which is then listened for inside App.vue; see above) <to-do-item-edit-form> listens for: item-edited event emitted by the onSubmit() method inside the ToDoItemEditForm component when the form is successfully s...
Setting up your own test automation environment - Learn web development
ed from automation dashboard or profile section const KEY = '{accessKey}'; // gridUrl: gridUrl can be found at automation dashboard const GRID_HOST = 'hub.lambdatest.com/wd/hub'; function searchTextOnGoogle() { // Setup Input capabilities const capabilities = { platform: 'windows 10', browserName: 'chrome', version: '67.0', resolution: '1280x800', network: true, visual: true, console: true, video: true, name: 'Test 1', // name of the test build: 'NodeJS build' // name of the build }; // URL: https://{username}:{accessToken}@hub.lambdatest.com/wd/hub const gridUrl = 'https://' + USERNAME + ':' + KEY + '@' + GRID_HOST; // setup and build selenium driver object const driver = new webdriver.Builder() .usi...
... usingServer('http://hub-cloud.browserstack.com/wd/hub'). withCapabilities(capabilities). build(); driver.get('http://www.google.com'); driver.findElement(By.name('q')).sendKeys('webdriver'); driver.sleep(1000).then(function() { driver.findElement(By.name('q')).sendKeys(webdriver.Key.TAB); }); driver.findElement(By.n...
... next code block): driver.getSession().then(function (sessionid){ driver.sessionID = sessionid.id_; }); Finally, replace the driver.sleep(2000) ... ...
...en(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. If you now go back to your Sauce Labs Automated Test dashboard page, you should see your new job now has the updated data attached to it: Your own remote server If you don't want to use a service like Sauce Labs or BrowserStack, you can always set up your own remote...
Gecko info for Windows accessibility vendors
up, and m represents the number of objects in that group. For example, "3 of 5" indicates the 3rd object out of 5. For outline item, more information is provided, in a format that reads "L#, n of m with c" where # represents the level that the outline item is at, and c represents the number of children. The n of m position relates to the position within the current outline level. Finally, true descriptions are now exposed with the text "Description: " prepending the description. This makes it clear that the description is truly intended to be read. Neither "Description:" or "of" in the above strings is ever localized, so they should be parsed out. DHTML Accessibility is Supported This means that you may encounter roles that are not typically in HTML content. Be prepared for...
...dia type (usually screen), or a set of alternative media types specified in nsISimpleDOMDocument::set_alternateViewMediaType(mediaTypeString) . See the W3C's website for a list of official media type name. Unfortunately, at this time the argument useAlternateView is ignored. ...
...ich lets turns the styleProperties array into an [in] parameter, letting you specify only those style properties you're interested in. This helps minimize the cost of marshalling for those times in which you're interested in only a few style properties per node. ...
...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. ...
Debugging JavaScript
a web page; open the Web console using the Web Console option in the Web Developer menu. This shows any JavaScript errors in your app, as well as any logging calls from the console API. Browser Console The Browser Console lets you see all JavaScript errors and logging in the browser, including from Firefox code. To enable it, go to about:config in the url bar and set devtools.chrome.enabled to true, or set the "Enable chrome and add-on debugging" option in the developer tool settings. Activate it through with the menu Tools > Web Developer > Browser Console. You can also start the Browser Console when you launch Firefox, by launching Firefox from the command line and passing --jsconsole as a flag: /path/to/firefox --jsconsole Log to the Browser Console using the standard console API afte...
...sole.jsm", {})).console; console.log("Hello from Firefox code"); Error Console This is obsolete and is no longer enabled in Firefox by default. Use the Web Console or the Browser Console instead. Browser Debugger (Built-in) On Firefox 19 or later, it's possible to use the built-in JS debugger on the browser itself. Go to about:config and set the following two prefs: devtools.chrome.enabled: true devtools.debugger.remote-enabled: true After you restart the browser, you can access the Browser Debugger through Tools > Web Developer > Browser Toolbox. (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.debugg...
...ut: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. (Note that before Firefox 28, only the script debugger was available.) The use of these tools are the same as the Built-in Tools. Strict code checking If you set the pref javascript.options.strict to true, the JavaScript engine gives you more types of warnings on the Error Console, most of which hint at code bugs that are easy to oversee or even bad syntax. (The pref also warns on common JavaScript idioms that are not errors). Console.log in Browser Console You can dump variables in the Browser Console from addon code, by adding this line to import the console utility: const { console } = Compo...
...: const { console } = Components.utils.import("resource://gre/modules/devtools/Console.jsm", {}); This has an advantage over dump in that you can list out properties of an object logged with console.log. dump() The dump() function allows you to print text on the native console. Use \n to output a newline at the end. To see anything, you need to set the pref browser.dom.window.dump.enabled to true, e.g. in about:config (add new pref, it doesn't exist per default). Under Microsoft Windows you additionally need to start Firefox via the following command to have a native console : firefox.exe -console Using normal JavaScript object inspection, you can write a function that dumps a whole object, similar to this ddumpObject(). Log.jsm (formerly log4moz) This is a partial implementation of...
Embedding Tips
happens? Implement the nsIURIContentListener interface, and register it with the appropriate web browser object via the nsIWebBrowser::parentURIContentListener attribute. Watch for changes in nsIURIContentListener::OnStartURIOpen(). You can abort the URI load at this point if you don't want it to proceed. If necessary you may also implement the nsIURIContentListener::IsPreferred(), returning PR_TRUE to ensure you are always the preferred URI handler and are called no matter what the content type. How do I copy items to the clipboard? Obtain the nsIClipboardCommands interface from the appropriate web browser object via nsIServiceProvider::GetInterface (or the do_GetInterface() helper method). How do I save a document or data to disk? Query for the nsIWebBrowserPersist interface implemente...
... If you want to create your component multiple times within the browser window, you can use a JavaScript constructor instead of a JavaScript property: catman->AddCategoryEntry("JavaScript global construct...
... If you want to create your component multiple times within the browser window, you can use a JavaScript constructor instead of a JavaScript property: catman->AddCategoryEntry("JavaScript global constructor", ...
...ontract_id to be lazily created when the my_prop_name is resolved in any JavaScript window scope. If you want to create your component multiple times within the browser window, you can use a JavaScript constructor instead of a JavaScript property: catman->AddCategoryEntry("JavaScript global constructor", "my_prop_name", "my_prop_contract_id", PR_TRUE, PR_TRUE, getter_Copies(previous)); That way you will be able to do: var my_comp = new my_prop_name(); This was taken from WeirdAl's excellent "Burning Chrome" article. How do I specify alternate locations for profiles? Specify a profile directory in your implementation of nsIDirectoryServiceProvider passed to XRE_InitEmbedding. Use XRE_NotifyProfile to make gecko actually use a profile loc...
Addon
n, in string platformVersion) Overview of optional methods void uninstall() void cancelUninstall() boolean hasResource(in string path) nsIURI getResourceURI(in string path) void getDataDirectory(in DataDirectoryCallback callback) Required properties Attribute Type Description appDisabled Read only boolean True if this add-on cannot be used in the application based on version compatibility, dependencies, and blocklisting. blocklistState Read only integer The current blocklist state of this add-on; see nsIBlocklistService for possible values. creator Read only AddonAuthor The creator of the add-on. foreignInstall Read only boolean True or false depending on...
...ocklistService for possible values. creator Read only AddonAuthor The creator of the add-on. foreignInstall Read only boolean True or false depending on whether the add-on is a third party add-on installation or not. id Read only string The ID of the add-on. No other installed add-on will have the same ID. isActive Read only boolean True if the add-on is currently functional. For some add-ons this will change immediately based on the appDisabled and userDisabled properties; for others it will only change after an application restart. isCompatible Read only boolean True or false depending on whether the add-on is compatible with the current application version and platform version. isPlatformCompatible Rea...
... name Read only string The name of the add-on. ...
... integer A bitfield holding all the the operations that can be performed on this add-on. Operations my be restricted based on system policies (e.g., the system administrator may not allow certain add-ons to be uninstalled), add-on type (e.g., themes may not be disabled), or add-on state (e.g., an incompatible add-on cannot be enabled). providesUpdatesSecurely Read only boolean True if the add-on has a secure means of updating or cannot be updated at all. scope Read only integer Indicates what scope the add-on is installed in, per profile, user, system, or application. type Read only string The type of the add-on. userDisabled boolean True if the user wants this add-on to be disabled. version Read only string The...
AddonListener
boolean needsRestart) void onUninstalled(in Addon addon) void onOperationCancelled(in Addon addon) void onPropertyChanged(in Addon addon, in string properties[]) Methods onEnabling() Called when an add-on is about to be enabled. void onEnabling( in Addon addon, in boolean needsRestart ) Parameters addon The Addon that is being enabled needsRestart True if an application restart is necessary for the change to take effect onEnabled() Called when an add-on has been enabled. void onEnabled( in Addon addon, ) Parameters addon The Addon that has been enabled onDisabling() Called when an add-on is about to be disabled. void onDisabling( in Addon addon, in boolean needsRestart ) Parameters addon The Addon that is being disabled ...
...ion restart is necessary for the change to take effect onEnabled() Called when an add-on has been enabled. void onEnabled( in Addon addon, ) Parameters addon The Addon that has been enabled onDisabling() Called when an add-on is about to be disabled. void onDisabling( in Addon addon, in boolean needsRestart ) Parameters addon The Addon that is being disabled needsRestart True if an application restart is necessary for the change to take effect onDisabled() Called when an add-on has been disabled. void onDisabled( in Addon addon, ) Parameters addon The Addon that has been disabled onInstalling() Called when an add-on is about to be installed. void onInstalling( in Addon addon, in boolean needsRestart ) Parameters addon The Addon that is being in...
...art is necessary for the change to take effect onDisabled() Called when an add-on has been disabled. void onDisabled( in Addon addon, ) Parameters addon The Addon that has been disabled onInstalling() Called when an add-on is about to be installed. void onInstalling( in Addon addon, in boolean needsRestart ) Parameters addon The Addon that is being installed needsRestart True if an application restart is necessary for the change to take effect onInstalled() Called when an add-on has been installed. void onInstalled( in Addon addon, ) Parameters addon The Addon that has been installed onUninstalling() Called when an add-on is about to be uninstalled. void onUninstalling( in Addon addon, in boolean needsRestart ) Parameters addon The Addon that i...
...sary for the change to take effect onInstalled() Called when an add-on has been installed. void onInstalled( in Addon addon, ) Parameters addon The Addon that has been installed onUninstalling() Called when an add-on is about to be uninstalled. void onUninstalling( in Addon addon, in boolean needsRestart ) Parameters addon The Addon that is being uninstalled needsRestart True if an application restart is necessary for the change to take effect onUninstalled() Called when an add-on has been uninstalled. void onUninstalled( in Addon addon, ) Parameters addon The Addon that has been uninstalled onOperationCancelled() Called when a pending operation for an add-on is cancelled. void onOperationCancelled( in Addon addon, ) Parameters addon The Addon th...
PromiseWorker.jsm
possible, as of Firefox 40, to cause the promise on the main thread catch. Any developer errors on the worker side, such as syntax errors, type errors, and so forth, will cause the promise to reject. A catch will trigger if there is a developer error in the main thread resolve or reject callbacks. 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. Worker file myWorker.js importScripts('resource://gre/modules/workers/require.js'); let PromiseWorker = require('resource://gre/modules/workers/PromiseWorker.js'); let worker = new PromiseWorker.AbstractWorker(); worker.dispatch = function(method, args = []) { ...
...nction() { self.close(); }; worker.log = function(...args) { dump('Worker: ' + args.join(' ') + '\n'); }; self.addEventListener('message', msg => worker.handleMessage(msg)); // start - my functionalities function resolveTest(shouldResolve) { if (shouldResolve) { return 'You sent to PromiseWorker argument of: `' + shouldResolve + '`'; } else { throw new Error('You passed in a non-true value for shouldResolve argument and therefore this will reject the main thread promise'); } } Main thread file bootstrap.js const { utils: Cu } = Components; const { BasePromiseWorker } = Cu.import('resource://gre/modules/PromiseWorker.jsm', {}); var myWorker = new BasePromiseWorker('chrome://path/to/content/myWorker.js'); var promise_doMyFuncTrue = myWorker.post('resolveTest', [true]); ...
...dResolve argument and therefore this will reject the main thread promise'); } } Main thread file bootstrap.js const { utils: Cu } = Components; const { BasePromiseWorker } = Cu.import('resource://gre/modules/PromiseWorker.jsm', {}); var myWorker = new BasePromiseWorker('chrome://path/to/content/myWorker.js'); var promise_doMyFuncTrue = 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_doMyFuncFals...
... 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 exa...
NSS Sample Code sample3
ut << "DigestBegin failed" << endl; goto done; } s = PK11_DigestOp(context, data, sizeof data); if (s != SECSuccess) { cout << "DigestUpdate failed" << endl; goto done; } s = PK11_DigestFinal(context, digest, &len, sizeof digest); if (s != SECSuccess) { cout << "DigestFinal failed" << endl; goto done; } /* Print digest */ printDigest(digest, len); PK11_DestroyContext(context, PR_TRUE); context = 0; /* * Part 2 - Hashing with included secret key */ cout << "Part 2 -- Hashing with included secret key" << endl; /* Initialize data */ memset(data, 0xbc, sizeof data); /* Create a Key */ key = PK11_KeyGen(slot, CKM_GENERIC_SECRET_KEY_GEN, 0, 128, 0); if (!key) { cout << "Create key failed" << endl; goto done; } cout << (void *)key << endl; /* Create p...
...cout << "DigestKey failed" << endl; goto done; } s = PK11_DigestOp(context, data, sizeof data); if (s != SECSuccess) { cout << "DigestUpdate failed" << endl; goto done; } s = PK11_DigestFinal(context, digest, &len, sizeof digest); if (s != SECSuccess) { cout << "DigestFinal failed" << endl; goto done; } /* Print digest */ printDigest(digest, len); PK11_DestroyContext(context, PR_TRUE); context = 0; /* * Part 3 - MAC (with secret key) */ cout << "Part 3 -- MAC (with secret key)" << endl; /* Initialize data */ memset(data, 0xbc, sizeof data); context = PK11_CreateContextBySymKey(CKM_MD5_HMAC, CKA_SIGN, key, &noParams); if (!context) { cout << "CreateContextBySymKey failed" << endl; goto done; } s = PK11_DigestBegin(context); if (s != SECSuccess) { c...
...*/ if (key) PK11_FreeSymKey(key); if (slot) PK11_FreeSlot(slot); return status; } ...
...*/ if (key) PK11_FreeSymKey(key); if (slot) PK11_FreeSlot(slot); return status; } ...
NSS PKCS11 Functions
ot. Do not try to free the string yourself. PK11_IsHW Finds out whether a slot is implemented in hardware or software. Syntax #include <pk11pub.h> #include <prtypes.h> PRBool PK11_IsHW(PK11SlotInfo *slot); Parameters This function has the following parameter: slot A pointer to a slot info structure. Returns The function returns one of these values: If the slot is implemented in hardware, PR_TRUE. If the slot is implemented in software, PR_FALSE. PK11_IsPresent Finds out whether the token for a slot is available. Syntax #include <pk11pub.h> #include <prtypes.h> PRBool PK11_IsPresent(PK11SlotInfo *slot); Parameters This function has the following parameter: slot A pointer to a slot info structure. Returns The function returns one of these values: If token is available, PR_TRUE. If t...
...Otherwise, PR_FALSE. PK11_SetPasswordFunc Defines a callback function used by the NSS libraries whenever information protected by a password needs to be retrieved from the key or certificate databases. ...
...tion. The callback function is identified in a call to PK11_SetPasswordFunc that takes place during NSS initialization. The callback function set up by PK11_SetPasswordFunc has the following prototype: typedef char *(*PK11PasswordFunc)( PK11SlotInfo *slot, PRBool retry, void *arg); This callback function has the following parameters: slot A pointer to a slot info structure. retry Set to PR_TRUE if this is a retry. This implies that the callback has previously returned the wrong password. arg A pointer supplied by the application that can be used to pass state information. Can be NULL. This callback function returns one of these values: If successful, a pointer to the password. This memory must have been allocated with PR_Malloc or PL_strdup. If unsuccessful, returns NULL. Many tokens ...
...d to pass state information. Can be NULL. This callback function returns one of these values: If successful, a pointer to the password. This memory must have been allocated with PR_Malloc or PL_strdup. If unsuccessful, returns NULL. Many tokens keep track of the number of attempts to enter a password and do not allow further attempts after a certain point. Therefore, if the retry argument is PR_TRUE, indicating that the password was tried and is wrong, the callback function should return NULL to indicate that it is unsuccessful, rather than attempting to return the same password again. Failing to terminate when the retry argument is PR_TRUE can result in an endless loop. Several functions in the NSS libraries use the password callback function to obtain the password before performing operati...
JSAPI User Guide
an array of those arguments. The arguments do not have native C++ types like int and float; rather, they are jsvals, JavaScript values. The native function uses JS_ConvertArguments to convert the arguments to C++ types and store them in local variables. The native function uses JS_SET_RVAL(cx, vp, val) to store its JavaScript return value. On success, a JSNative must call JS_SET_RVAL and return true. The value passed to JS_SET_RVAL is returned to the JavaScript caller. On failure, a JSNative calls an error-reporting function, in this case JS_ReportError, and returns false. This causes a JavaScript exception to be thrown. The caller can catch the exception using a JavaScript try/catch statement. To make native functions callable from JavaScript, declare a table of JSFunctionSpecs describing...
...ect *obj, jsval id, jsval *vp) { if (JSVAL_IS_INT(id)) { switch (JSVAL_TO_INT(id)) { case MY_COLOR: *vp = . . .; break; case MY_HEIGHT: *vp = . . .; break; case MY_WIDTH: *vp = . . .; break; case MY_FUNNY: *vp = . . .; break; case MY_ARRAY: *vp = . . .; break; case MY_RDONLY: *vp = . . .; break; } } return true; } Defining classes This pulls together the above API elements by defining a constructor function, a prototype object, and properties of the prototype and of the constructor, all with one API call. Initialize a class by defining its constructor function, prototype, and per-instance and per-class properties. The latter are called "static" below by analogy to Java. They are defined in the const...
...at an application provides to scripts largely determines what those scripts can do. For example, the Firefox browser uses its own global object, window. To change the global object for your application, call JS_SetGlobalObject. Creating and initializing custom objects In addition to using the engine's built-in objects, you will create, initialize, and use your own JS objects. This is especially true if you are using the JS engine with scripts to automate your application. Custom JS objects can provide direct program services, or they can serve as interfaces to your program's services. For example, a custom JS object that provides direct service might be one that handles all of an application's network access, or might serve as an intermediary broker of database services. Or a JS object that ...
...gs in the engine to attack your application. Note that the kind of attack we're talking about here is where a hacker uses JavaScript to attack the C++ code of the engine itself (or your embedding). The rest of the items in this list talk about security issues that arise within JavaScript itself, even if the engine is working properly. Block simple denial-of-service attacks - A program like while(true){} should not hang your application. To stop execution of scripts that run too long, use JS_SetOperationCallback. Likewise, a function like function f(){f();} should not crash your application with a stack overflow. To block that, use JS_SetNativeStackQuota. Control access to sensitive data - Your application might expose data to some scripts that other scripts should not be able to see. For exa...
JSPropertyOp
n active request on cx. The callback does not need to call JS_BeginRequest()). obj JS::HandleObject The object whose properties are being accessed. id JS::HandleId The name or index of the property being accessed. This is either a string (Unicode property identifier) or an integer (element index). strict bool (JSStrictPropertyOp only) If strict is true, treating the assignment as strict mode code. vp JS::MutableHandleValue In/out parameter. Points to a JS::Value variable. The meaning of this variable is different for each of the hooks; see below. Description JSPropertyOp and JSStrictPropertyOp callbacks are hooks that applications may install to be called at some point during property access. A JSPropertyOp may be install...
...yOp callbacks are hooks that applications may install to be called at some point during property access. A JSPropertyOp may be installed on an individual property as a getter or setter; or it may be installed on a JSClass to hook property gets, sets, or adds. These different cases are described in more detail in the sections below. If a JSPropertyOp or JSStrictPropertyOp does nothing and returns true, then property get, set, or add is unaffected. It proceeds as normal. Each of these callbacks may veto the ongoing property operation by optionally reporting an error or raising an exception and then returning false. The operation then fails, and the error is propagated to the caller. Otherwise the callback must return true, and the property operation proceeds. Getters and setters When a JSAPI...
...avaScript code accesses the property's value using the syntax obj.prop or obj[propname]. It is also called when the property's value is accessed via JSAPI functions such as JS_GetProperty or (less obviously) JS_CallFunctionName. On entry, *vp contains the property's stored value or undefined if the property doesn't have a stored value. The callback may modify *vp. On success, the callback returns true and the value left in *vp is returned to the script or JSAPI caller. Setters. The setter callback is called each time JavaScript code assigns to the property using any assignment operator (=, +=, etc.) or the ++ or -- operators. It is also called when the property is set via JSAPI functions such as JS_SetProperty. On entry, *vp contains the value being assigned to the property. The callback may ...
... script or JSAPI caller. Setters. The setter callback is called each time JavaScript code assigns to the property using any assignment operator (=, +=, etc.) or the ++ or -- operators. It is also called when the property is set via JSAPI functions such as JS_SetProperty. On entry, *vp contains the value being assigned to the property. The callback may modify *vp. On success, the callback returns true. If the property has a stored value, it is then updated to the value left in *vp after the callback. As of SpiderMonkey 1.7, the value of a property assignment expression, like (a.length = x), is the value of *vp after the setter is called. This is typically the value of the left-hand side after assignment, as opposed to the value of the right-hand side, as required by ECMA 262-3 ?11.13. This EC...
JS_ExecuteRegExp
l object. reobj JS::HandleObject A pointer to a RegExp object. chars const char16_t * A pointer to the string contains a input string. length size_t The length of bytes or chars, in characters. indexp size_t * In/Out parameter. A pointer to the lastIndex for the execution, and received the updated lastIndex. test bool Pass true to avoid creating match result array and store boolean value to rval. rval JS::MutableHandleValue Out parameter. Receives the result match result array or boolean value. Description JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics execute the RegExp object, reobj, to the specified input string, chars, from *indexp index. If test is false, JS_ExecuteRegExp and JS_NewRegExpObj...
...alue Out parameter. Receives the result match result array or boolean value. Description JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics execute the RegExp object, reobj, to the specified input string, chars, from *indexp index. If test is false, JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics store the match result array to *rval if matches, otherwise stores null to *rval. ...
... Description JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics execute the RegExp object, reobj, to the specified input string, chars, from *indexp index. If test is false, JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics store the match result array to *rval if matches, otherwise stores null to *rval. If test is true, JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics store the boolean value true to *rval if matches, otherwise stores null to *rval. ...
...d JS_NewRegExpObjectNoStatics store the match result array to *rval if matches, otherwise stores null to *rval. If test is true, JS_ExecuteRegExp and JS_NewRegExpObjectNoStatics store the boolean value true to *rval if matches, otherwise stores null to *rval. JS_ExecuteRegExp updates the built-in RegExp object's properties. ...
JS_PropertyStub
they are convenient stand-ins anywhere the JSAPI requires callbacks of certain types. Examples at JSClass illustrate how stub functions can be used. JS_PropertyStub is of type JSPropertyOp, the type of getter callback. It can be used in JSClass.addProperty, and JSClass.getProperty. It behaves exactly like a property callback that accepts the default property behavior: it does nothing and returns true. JS_StrictPropertyStub is of type JSStrictPropertyOp, the type of setter callback. It can be used in JSClass.setProperty. It behaves exactly like a property callback that accepts the default property behavior: it does nothing and returns true. JS_DeletePropertyStub is of type JSDeletePropertyOp, the type of setter callback. It can be used in JSClass.delProperty. It behaves exactly like a proper...
... JS_ConvertStub is a stub for JSClass.convert. ...
... JS_ConvertStub is a stub for JSClass.convert. Its behavior is the same as the default conversion behavior for Objects. ...
... JS_ConvertStub is a stub for JSClass.convert. Its behavior is the same as the default conversion behavior for Objects. ...
A Web PKI x509 certificate primer
rsa_keygen_bits:4096" 4096 is considered secure for the next 15 years. Generate csr "openssl req -new -key rootkey.pem -days 5480 -extensions v3_ca -batch -out root.csr -utf8 -subj '/C=US/O=Orgname/OU=SomeInternalName' Make a new Certificate Signing Request (CSR) that will be valid for 15 years. ...
...en_bits: 3072" A 3072 bit key is considered secure for the next 8 years. Generate csr "openssl req -new -key intkey.pem -days 2922 -extensions v3_ca -batch -out int.csr - utf8 -subj '/C=US/O=Orgname/OU=SomeInternalName2' Make a new Certificate Signing Request (CSR) that will be valid for 8 years. ...
...e What It Means What Can I Do SEC_ERROR_BAD_DER A certificate is not properly encoded according to ASN.1 (DER) encoding Re-generate the improperly-encoded certificate SEC_ERROR_CA_CERT_INVALID An end-entity certificate is being used to issue another certificate Ensure that any certificate intended to issue certificates has a basic constraints extension with cA: TRUE SEC_ERROR_BAD_SIGNATURE A signature on a certificate is improperly formatted or the certificate has been tampered with Re-issue the certificate with the bad signature SEC_ERROR_CERT_BAD_ACCESS_LOCATION The OCSP URI in the authorityInformationAccess extension is improperly formed Re-generate the certificate with a well-formed OCSP URI SEC_ERROR_CERT_NOT_IN_NA...
... Import the root certificate into Firefox or have the server send the intermediate SEC_ERROR_INVALID_KEY SEC_ERROR_UNSUPPORTED_KEYALG SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE An issuer certificate is too old Re-issue the issuer certificate MOZILLA_PKIX_ERROR_CA_CERT_USED_AS_END_ENTITY A certificate with a basic constraints extension with cA:TRUE is being used as an end-entity certificate Re-generate the end-entity certificate without the basic constraints extension MOZILLA_PKIX_ERROR_INADEQUATE_KEY_SIZE A certificate has a key that is too small to be secure Re-generate a larger key and issue a certificate using that key ...
Components.isSuccessCode
Syntax var succeeded = Components.isSuccessCode(returnCode); Parameters returnCode The return code (of type nsresult) to be checked. Description Components.isSuccessCode() may be used to determine whether an XPCOM return code (an nsresult) indicates success or failure. An XPCOM return code indicates success if its high-order bit is 0, and it indicates failure if its high-order bit is 1. ...
...an parameters if you're using Gecko 1.9.1 and earlier. ...
...nProgress = false; function copyBufferedStream(inStream, outStream) { var copyObserver = { onStartRequest: function(request, context) { copyInProgress = true; }, onStopRequest: function(request, context, statusCode) { copyInProgress = false; // did the copy fail? ...
...ed = true; }, QueryInterface: function(aIID) { if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports)) return this; throw Cr.NS_ERROR_NO_INTERFACE; } }; var copier = Cc["@mozilla.org/network/async-stream-copier;1"] .createInstance(Ci.nsIAsyncStreamCopier); copier.init(inStream, outStream, null, true, false, 8192, true, true); copier.asyncCopy(copyObserver, null); } ...
mozIStorageConnection
e last SQL INSERT operation. Read only. Note: This is not reliable if you are using asynchronous statements or if you are using the connection on multiple threads. schemaVersion long The schema version of the database. This should not be used until the database is ready. The version will be reported as 0 if it is not set. transactionInProgress boolean Returns true if there is a transaction in progress on the database. Otherwise returns false. Read only. Constants Transaction execution time constants. Constant Value Description TRANSACTION_DEFERRED 0 No database lock is obtained until the first statement is run. TRANSACTION_IMMEDIATE 1 A reserved lock is obtained on the database. TRANSACTION_EXC...
...dy read-only, you will get a read-only clone. Note: Due to a bug in SQLite, if you use the shared cache (by calling mozIStorageService.openDatabase()), the cloned connection's access privileges will be the same as the original connection, regardless of the value you specify for the aReadOnly parameter. mozIStorageConnection clone( in boolean aReadOnly Optional ); Parameters aReadOnly If true, the returned database connection is in read only mode. This is false by default. Return value A new mozIStorageConnection object representing the cloned connection. Exceptions thrown NS_ERROR_UNEXPECTED The connection is to a memory database. close() Closes a database connection. Before closing the connection, you need to finalize all statements created for the connection. Note: You ...
.... As a result, this method of modifying the database is strongly discouraged! void executeSimpleSQL( in AUTF8String aSQLStatement ); Parameters aSQLStatement The SQL statement to execute. indexExists() This method determines whether or not the given index exists. boolean indexExists( in AUTF8String aIndexName ); Parameters aIndexName The index to check. Return value true if the index exists, false otherwise. preload() Obsolete since Gecko 1.9 (Firefox 3) This is used to preload the database cache. It loads pages from the start of the database file until the memory cache (specified by "PRAGMA cache_size=") is full or the entire file is read. The cache MUST be active on the database for this to work. This means that you must have a tran...
...ler The mozIStorageProgressHandler instance that is being registered. Return value Returns the previous registered handler, or null if none was previously registered. tableExists() Determines if there exists a table with the given name. boolean tableExists( in AUTF8String aTableName ); Parameters aTableName The SQL table whose existence should be checked. Return value Returns true if the table exists, false otherwise. See also Storage mozStorage introduction and how-to article mozIStorageStatement Create and execute SQL statements on a SQLite database. mozIStorageValueArray Wraps an array of SQL values, such as a result row. mozIStorageFunction Create a new SQLite function. mozIStorageAggregateFunction Create a new SQLite aggregate function. mozIStorageProgressHan...
nsIAlertsService
dentifying the image to display in the notification alert. title The title for the alert. text The text to display in the alert, explaining the alert condition. The text must not be too long, otherwise it might be truncated to a platform-specific length. If the text is too long, try to use line returns in the text to have it split and displayed over multiple lines. textClickable Optional If true, if the user clicks on it, the listener is notified; when hovered the notification background becomes lighter and the cursor turns to a pointer. Prior to Gecko 32 the text was made to look like a link. cookie Optional A blind cookie the alert passes back to the consumer during alert listener callbacks. alertListener Optional An object to receive callbacks from the alert; may be null if you d...
... lang Optional Language of title and text of the alert. Only available on supported platforms. data Optional The value of the cookie parameter passed to showAlertNotification. principal Optional The principal of the page that created the alert. Used for IPC security checks, and to determine whether the alert is actionable. inPrivateBrowsing Optional Controls the image loading behavior. If true, the image URL will be loaded in private browsing mode. Exceptions thrown NS_ERROR_NOT_AVAILABLE Unable to display the notification; this may happen, for example, on Mac OS X if Growl is not installed. Example Simple usage The following code was used to display the above notification. var alertsService = Components.classes["@mozilla.org/alerts-service;1"]. getServ...
... observe: function(subject, topic, data) { alert("subject=" + subject + ", topic=" + topic + ", data=" + data); } } var alertsService = Components.classes["@mozilla.org/alerts-service;1"]. ...
... fireox and then focus the tab'); } else if (aTopic == 'alertshow') { console.log('just showed notification'); } else if (aTopic == 'alertfinished') { console.log('just alertfinished') } } }; as.showAlertNotification('chrome://branding/content/icon64.png', 'StackOverflow - New Messages', 'There are ## new messages. Click here to focus the tab', true, null, notifListener, 'StackOverflow Notifier'); closeAlert() Closes alerts created by the service. void closeAlert( in AString name, Optional in nsIPrincipal principal Optional ); Parameters name The name of the notification to close. If no name is provided then only a notification created with no name (if any) will be closed. principal The title for the alert. See also Al...
nsIAnnotationService
on which the annotation is set. count Optional Count of annotations name available. result Returns the name of all annotations. pageHasAnnotation() This method tests for annotation existance for given URI. boolean pageHasAnnotation( in nsIURI aURI, in AUTF8String aName ); Parameters aURI The URI on which the annotation is set. aName The annotation name. ...
... removePageAnnotation() This method removes a specific annotation for given URI. Succeeds even if the annotation is not found. void removePageAnnotation( in nsIURI aURI, in AUTF8String aName ); Parameters aURI The URI on which the annotation is set. ...
...l be preferred. All the source annotations will stay as-is. If you don't want them any more, use removePageAnnotations() on that URI. void copyPageAnnotations( in nsIURI aSourceURI, in nsIURI aDestURI, in boolean aOverwriteDest ); Parameters aSourceItemId Source item. aDestItemId Destination item. aOverwriteDest If you want to overwrite existing annotation, set this parameter to true, or else set it to false. copyItemAnnotations() This method copies all annotations from the source to the destination item. If the destination already has an annotation with the same name as one on the source, it will be overwritten if aOverwriteDest is set. Otherwise, the destination URIs will be preferred. All the source annotations will stay as-is. If you don't want them any more, use remo...
...ed. All the source annotations will stay as-is. If you don't want them any more, use removePageAnnotations() on that URI. void copyItemAnnotations( in long long aSourceItemId, in long long aDestItemId, in boolean aOverwriteDest ); Parameters aSourceItemId Source item. aDestItemId Destination item. aOverwriteDest If you want to overwrite existing annotation, set this parameter to true or else false. addObserver() This method adds an annotation observer. The annotation service will keep an owning reference to the observer object. void addObserver( in nsIAnnotationObserver aObserver ); Parameters aObserver Annotation observer. removeObserver() This method removes an annotaton observer previously registered by addObserver() method. void removeObserver( in nsIAnn...
nsIApplicationUpdateService
in boolean background); void pauseDownload(); void removeDownloadListener(in nsIRequestObserver listener); nsIUpdate selectUpdate([array, size_is(updateCount)] in nsIUpdate updates, in unsigned long updateCount); Attributes Attribute Type Description backgroundChecker nsIUpdateChecker The update checker being used for background update checking. Read only. ...
...updates, in unsigned long updateCount); Attributes Attribute Type Description backgroundChecker nsIUpdateChecker The update checker being used for background update checking. Read only. canApplyUpdates boolean true if the Update Service can download and install updates. Indicates if the current user has access privileges to the install directory. Read only. canCheckForUpdates boolean true if the Update Service can check for updates. Application updates might be disabled by the application and the platform the application is running on. Read only. canUpdate boolean true if the update service is able to download and install updates. This depends on whether or not the current user has the necessary access privileges for the install directory. Read only. Obsolete since Gecko 1.9.1.
...Read only. Methods addDownloadListener() Adds a listener that receives progress and state information about the update that is currently being downloaded. ...
...meters listener An object implementing nsIRequestObserver and optionally nsIProgressEventSink that will be notified of state and progress information as the update is downloaded. downloadUpdate() Starts downloading a software update. AString downloadUpdate( in nsIUpdate update, in boolean background ); Parameters update An nsIUpdate object indicating the update to download. background true to download the update in the background or false to download it in the foreground. Return value A string indicating the status of the update upon return: "downloading" The update is being downloaded. "pending" The update is ready to be applied. "applying" The update is in the process of being applied. "succeeded" The update has been installed successfully. "download-failed" The update failed t...
nsIAutoCompleteInput
Attributes Attribute Type Description completeDefaultIndex boolean If a search result has its defaultIndex set, this will optionally try to complete the text in the textbox to the entire text of the result at the default index as the user types. This means that auto-fill is enabled. completeSelectedIndex boolean If true, the text in the text field will be autocompleted as the user selects from the popup list. consumeRollupEvent boolean If true, the event that rolls up the popup should be consumed by the popup itself. If false, the rollup event will be dispatched. Read only. controller nsIAutoCompleteController The controller. Read only. di...
...utocompleted as the user selects from the popup list. consumeRollupEvent boolean If true, the event that rolls up the popup should be consumed by the popup itself. If false, the rollup event will be dispatched. Read only. controller nsIAutoCompleteController The controller. Read only. disableAutoComplete boolean true if auto-complete is currently disabled; otherwise false. forceComplete boolean If true, the text field automatically completes to the default result whenever the user hits the enter key or the text field loses focus. maxRows unsigned long The maximum number of rows to display in the autocomplete suggestion popup. minResultsFo...
... searchParam AString An additional parameter used for configuring searches. selectionEnd long The ending index of the current selection in the text field. Read only. selectionStart long The starting index of the current selection in the text field. Read only. showCommentColumn boolean If true, a column is added to the popup, showing the comment for each autocomplete result. showImageColumn boolean If true, a column is added to the popup, showing an additional image for each autocomplete result. textValue AString The value of the text in the autocomplete text field. timeout unsigned long The number of ...
... to be returned. Return value The name of the specified object. onSearchBegin() Called when the search starts. void onSearchBegin(); Parameters None. onSearchComplete() Called when the search ends successfully. void onSearchComplete(); Parameters None. onTextEntered() Called when the user selects and presses enter on a result item. boolean onTextEntered(); Parameters None. Return value Return true to prevent handling the selection. onTextReverted() Called when the user cancels the autocomplete session. boolean onTextReverted(); Parameters None. Return value Return true to prevent the reversion. selectTextRange() Selects a range of text in the autocomplete text field. void selectTextRange( in long startIndex, in long endIndex ); Parameters startIndex The index to the fi...
nsIClipboardDragDropHooks
ferable trans); boolean onPasteOrDrop(in nsIDOMEvent event, in nsITransferable trans); Methods allowDrop() Tells gecko whether a drop is allowed on this content area. boolean allowDrop( in nsIDOMEvent event, in nsIDragSession session ); Parameters event The DOM event (drag gesture). session The drag session from which client can get the flavors present or the actual data. ...
...Otherwise, false to show the drag is canceled (Does not go to Operating System). onCopyOrDrag() Alters the flavors or data presented to the OS. Used for drag and copy actions. Because this can be called many times, it is highly recommended that the implementation be very efficient so user feedback is not negatively impacted. ...
...s. Because this can be called many times, it is highly recommended that the implementation be very efficient so user feedback is not negatively impacted. boolean onCopyOrDrag( in nsIDOMEvent aEvent, in nsITransferable trans ); Parameters aEvent The DOM event (drag drop). null if triggered by copy. trans The transferable holding the list of flavors and the data for each flavor. Return value true to indicate that copy/drag can proceed. Otherwise, false to indicate that the copy/drag is canceled, does not go to Operating System. onPasteOrDrop() Provide an alternative action to the built-in behavior when something is dropped on the browser or in an editor. boolean onPasteOrDrop( in nsIDOMEvent event, in nsITransferable trans ); Parameters event The DOM event (drag drop); null if trigg...
... go to Operating System. onPasteOrDrop() Provide an alternative action to the built-in behavior when something is dropped on the browser or in an editor. boolean onPasteOrDrop( in nsIDOMEvent event, in nsITransferable trans ); Parameters event The DOM event (drag drop); null if triggered by paste. trans The transferable holding the list of flavors and the data for each flavor. Return value true to indicate the action was handled, do not perform built-in behavior. Otherwise, false to indicate the action was not overridden, do built-in behavior. See also nsIClipboard ...
nsIFrameScriptLoader
pt() is called. If this function is called on a ChromeMessageBroadcaster (for example, a global frame message manager or a window message manager) then: loadFrameScript() will load the frame script independently into each applicable frame: every open frame in the given window for the window message manager, or every frame in every window for the global message manager if aAllowDelayedLoad is true, then the script will also be loaded into any applicable new frames opened after the loadFrameScript() call. Otherwise it will only be loaded into frames that exist at the time of the call. If this function is called on a ChromeMessageSender: it will load the frame script only into this ChromeMessageSender's frame aAllowDelayedLoad should always be true. It's possible that the frame for thi...
...As the user opens new tabs in this window, copies of the script will be loaded into these new tabs, as well. ...
...navigates. If you want a frame script to do something whenever a new document is loaded, you can listen for the document-element-inserted notification. Parameters Name Type Description aURL String URL for the script to load. aURL must be the absolute URL. data: URLs are also supported. For example data:,dump("foo\n"); aAllowDelayedLoad Boolean If true, this flag means that the frame script will be loaded into any new frames opened after the loadFrameScript() call, until removeDelayedFrameScript() is called for that script. aRunInGlobalScope Boolean Optional, defaults to false. By default, frame scripts each have their own scope, so they can declare global variables without causing conflicts with any other frame scripts...
...he frame script will be loaded into any new frames opened after the loadFrameScript() call, until removeDelayedFrameScript() is called for that script. aRunInGlobalScope Boolean Optional, defaults to false. By default, frame scripts each have their own scope, so they can declare global variables without causing conflicts with any other frame scripts. If present and set to true, this flag switches off that behavior, meaning that the script's scope is shared with any other frame scripts in the same frame that have also set the flag. removeDelayedFrameScript() Removes aURL from the list of scripts which support delayed load. This cancels the effect of the aAllowDelayedLoad flag, meaning that the loader will no longer load the script into new frames. If you us...
nsILocalFileMac
ze() Read only. fileType OSType File type and creator attributes. Native code only! Constants Constant Value Description CURRENT_PROCESS_CREATOR 0x8000000 Use with SetFileType() to specify the signature of current process. Obsolete since Gecko 2.0 Methods Native code only!getCFURL Note: Observes the state of the followLinks attribute. If the file object is an alias and followLinks is true, returns the target of the alias. If followLinks is false, returns the unresolved alias file. Note: Supported only for XP_MACOSX. CFURLRef getCFURL(); Parameters None. Return value The CFURLRef of the file object. The caller is responsible for calling CFRelease() on it. Native code only!getFSRef Note: Observes the state of the followLinks attribute. If the file object is an alias and followLinks...
...turns the target of the alias. If followLinks is false, returns the unresolved alias file. Note: Supported only for XP_MACOSX. CFURLRef getCFURL(); Parameters None. Return value The CFURLRef of the file object. The caller is responsible for calling CFRelease() on it. Native code only!getFSRef Note: Observes the state of the followLinks attribute. If the file object is an alias and followLinks is true, returns the target of the alias. If followLinks is false, returns the unresolved alias file. Note: Supported only for XP_MACOSX. FSRef getFSRef(); Parameters None. Return value The FSRef of the file object. Native code only!getFSSpec Note: Observes the state of the followLinks attribute. If the file object is an alias and followLinks is true, returns the target of the alias. If followLinks is f...
....0)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Init this object with an FSSpec Legacy method - leaving in place for now. void initWithFSSpec( [const] in FSSpecPtr aFileSpec ); Parameters aFileSpec The native file spec. isPackage() boolean isPackage(); Parameters None. Return value true if a directory is determined to be a package under Mac OS 9/X. launchWithDoc() Launch the application that this file points to with a document. void launchWithDoc( in nsILocalFile aDocToLoad, in boolean aLaunchInBackground ); Parameters aDocToLoad Must not be null. If no document, use nsILocalFile::launch. aLaunchInBackground true if the application should not come to the front. openDocWit...
... application should not come to the front. openDocWithApp() Open the document that this file points to with the given application. void openDocWithApp( in nsILocalFile aAppToOpenWith, in boolean aLaunchInBackground ); Parameters aAppToOpenWith The application with which to open the document. If null, the creator code of the document is used to determine the application. aLaunchInBackground true if the application should not come to the front. setFileTypeAndCreatorFromExtension() Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Sets the file type and creator code from a file extension Internet Config is used to determine the mapping. void setFileTypeAndCreatorFromExtension( in string aExtension ); Parameters aExtension setF...
nsINavBookmarksService
R 3 This is an index for type "Separator". TYPE_DYNAMIC_CONTAINER 4 This is an index for type "Dynamic Container". Dynamic containers were removed in Gecko 11, but the type index remains to prevent reuse. Methods addObserver() This method adds a bookmark observer. If ownsWeak is false, the bookmark service will keep an owning reference to the observer. If ownsWeak is true, then aObserver must implement nsISupportsWeakReference, and the bookmark service will keep a weak reference to the observer. void addObserver( in nsINavBookmarkObserver observer, in boolean ownsWeak ); Parameters observer The bookmark observer to be added. ownsWeak The owning reference state (boolean). beginUpdateBatch() Obsolete since Gecko 1.9 (Firefox 3) ...
...st, 0 is returned. getFolderIdForItem() This method retrieves the parent folder's ID for an item. long long getFolderIdForItem( in long long aItemId ); Parameters aItemId The item whose parent folder's ID is to retrieved. Return value Returns the parent folder's ID for the given item. getFolderReadonly() This method checks whether a folder is marked as read-only. If this is set to true, UI will not allow the user to add, remove, or reorder children in this folder. The default for all folders is false. Note: This does not restrict API calls, only UI actions. boolean getFolderReadonly( in long long aItemId ); Parameters aItemId The item ID of the folder. Return value Returns true if the folder is marked as read-only, otherwise returns false. getFolderTitle(...
...ppend to the end of the list. Return value The ID of the new separator. isBookmarked() This method checks whether or not the given URI is in any bookmark folder. If you want the results to be redirect-aware, use getBookmarkedURIFor() boolean isBookmarked( in nsIURI aURI ); Parameters aURI The URI whose existence in any bookmark folder is needed to be checked. Return value Returns true if the given URI is in any bookmark folder, otherwise returns false. moveFolder() Obsolete since Gecko 1.9 (Firefox 3) Note: moveItem() provides an alternative for this method. Moves a folder to a different container, preserving its contents. void moveFolder( in PRInt64 folder, in PRInt64 newParent, in PRInt32 index ); Parameters folder The folder to move...
...nUpdateBatch() and nsINavBookmarkObserver.onEndUpdateBatch(). void runInBatchMode( in nsINavHistoryBatchCallback aCallback, in nsISupports aUserData ); Parameters aCallback nsINavHistoryBatchCallback interface to call. aUserData Opaque parameter passed to nsINavBookmarksBatchCallback. setFolderReadonly() This method sets or unsets the readonly flag from a folder. If this is set to true, UI will not allow the user to add, remove, or reorder children in this folder. The default for all folders is false. Note: This does not restrict API calls, only UI actions. void setFolderReadonly( in long long aFolder, in boolean aReadOnly ); Parameters aFolder The item-id of the folder. aReadOnly The read-only state. setFolderTitle() Obsolete since Gecko 1.9 (F...
nsINavHistoryContainerResultNode
); 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. Read only. 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. Read-only. This is false for bookmark folder nodes unless the setFolderReadOnly() method has been called to specifically make the folder read-only. It's true for non-folder nodes. If this container is a remote container, this flag may be redefined by the remote container provider. Read-only. containerOpen boolean Set th...
...When closed, attempting to call getChild() or access childCount results in an error. ...
...isn't a dynamic container. Read only. hasChildren boolean Indicates whether or not the node can have children, and may be used whether the container is open or closed. When the container is closed, the result is an exact answer if the node can be populated easily (for example, for bookmark folders). If it can't be populated easily (for complex history queries, for example), the result is always true. When the container is open, the result is always accurate. This value is intended to be used to see if the "+" should be drawn next to a tree item, indicating that the item can be opened. Read-only. remoteContainerType Obsolete since Gecko 1.9 AUTF8String A string representing the remote container service API that is responsible for this container. If there is no such API, this value is an em...
...TATE_OPENED 2 The container is open. Methods findNodeByDetails() Returns a node matching specified details. nsINavHistoryResultNode findNodeByDetails( in AUTF8String aURIString, in PRTime aTime, in long long aItemId, in boolean recursive ); Parameters aURIString The URI attribute value to match on. aTime The time attribute to match on. aItemId The item ID to match on. aRecursive If true, the search will recurse through all child containers of the current container; if false, only direct children of the container are searched. Return value An nsINavHistoryResultNode of a node matching the specified details or null if no match is found. Exceptions thrown NS_ERROR_NOT_AVAILABLE The container is not open. getChild() Returns the child node at the specified index. nsINavHistoryRes...
nsIParentalControlsService
in boolean aFlag, in nsIURI aSource, [optional] in nsIFile aTarget); boolean requestURIOverride(in nsIURI aTarget, [optional] in nsIInterfaceRequestor aWindowContext); boolean requestURIOverrides(in nsIArray aTargets, [optional] in nsIInterfaceRequestor aWindowContext); Attributes Attribute Type Description blockFileDownloadsEnabled boolean true if the current user account's parental controls restrictions include the blocking of all file downloads. Read only. loggingEnabled boolean true if the current user account has parental controls logging enabled. If this is true, applications should log relevant events using log() method. Read only. parentalControlsEnabled boolean true if the current user account has p...
...n access to web content. ePCLog_FileDownload 2 This log entry type represents a file download. Methods log() Logs an application specific parental controls event. void log( in short aEntryType, in boolean aFlag, in nsIURI aSource, in nsIFile aTarget Optional ); Parameters aEntryType The type of event to log. See the constants for allowed values. aFlag Pass true if the event was blocked or false if it was allowed. aSource The URI source of the subject content. aTarget Optional The location to which the content was saved if it was not blocked. requestURIOverride() Requests that a blocked URI be allowed through parental control filters. This method may block while the operating system presents user interface to handle the override request (such as ...
...rs. This method may block while the operating system presents user interface to handle the override request (such as an "enter an administrator's password" dialog box). boolean requestURIOverride( in nsIURI aTarget, in nsIInterfaceRequestor aWindowContext Optional ); Parameters aTarget The URI to be overridden. aWindowContext Optional The window generating the event. Return value true if the block was successfully overridden, otherwise false. requestURIOverrides() Requests that a set of URIs be allowed through the parental control filters. This method may block while the operating system presents user interface to handle the override request (such as an "enter an administrator's password" dialog box). boolean requestURIOverrides( in nsIArray aTargets, in nsIInterfaceRe...
... ...
nsIPrincipal
he load is allowed this function does nothing. If the load is not allowed the function throws NS_ERROR_DOM_BAD_URI. Note: Other policies might override this, such as the Access-Control specification. Note: The 'domain' attribute has no effect on the behaviour of this function. void checkMayLoad( in nsIURI uri, in boolean report ); Parameters uri Missing Description report If true, will report a warning to the console service if the load is not allowed. Exceptions thrown NS_ERROR_DOM_BAD_URI The load is not permitted. Native code only!disableCapability void disableCapability( in string capability, inout voidPtr annotation ); Parameters capability Missing Description annotation Missing Description Native code only!enableCapability void enab...
... Missing Description annotation Missing Description equals() Returns whether the other principal is equivalent to this principal. Principals are considered equal if they are the same principal, they have the same origin, or have the same certificate fingerprint ID. boolean equals( in nsIPrincipal other ); Parameters other The other principal to compare against. Return value true if the two principals are equivalent; otherwise false. Native code only!getJSPrincipals Returns the JS equivalent of the principal. JSPrincipals getJSPrincipals( in JSContext cx ); Parameters cx Missing Description Return value Missing Description getPreferences() Returns the security preferences associated with this principal. void getPreferences( out string prefBranch, out st...
... A semi-unique ID relating to either the fingerprint or the origin. subjectName A name identifying the entity the principal represents; this may be an empty string. grantedList Space-delineated list of capabilities which are explicitly granted by a preference. deniedList Space-delineated list of capabilities which are explicitly denied by a preference. isTrusted true if the certificate is a codebase trusted one. Native code only!isCapabilityEnabled boolean isCapabilityEnabled( in string capability, in voidPtr annotation ); Parameters capability Missing Description annotation Missing Description Return value Missing Description Exceptions thrown Missing Exception Missing Description Native code only!revertCapability void rever...
...bz except see bug 147145! Note: For the future: Perhaps we should consider a certificate principal for a given URI subsuming a codebase principal for the same URI? Not sure what the immediate benefit would be, but I think the setup could make some code (e.g. MaybeDowngradeToCodebase) clearer. boolean subsumes( in nsIPrincipal other ); Parameters other Missing Description Return value true if this principal subsumes the specified principal; otherwise false. ...
nsIUpdatePrompt
Update update); void showUpdateHistory(in nsIDOMWindow parent); void showUpdateInstalled(); Methods checkForUpdates() Presents a user interface that checks for and displays the available updates. void checkForUpdates(); Parameters None. showUpdateAvailable() Shows a message advising the user that an update is available to be downloaded and installed. ...
...ent preference is true or the user interface is already displayed the call will be a no-op. void showUpdateAvailable( in nsIUpdate update ); Parameters update An nsIUpdate describing the update that's available. showUpdateDownloaded() Shows a message advising the user that an update has been downloaded, and that the user should restart the application in order to install it. If background is true (for example the download was not user initiated) and the app.update.silent preference is true the call will be a no-op. void showUpdateDownloaded( in nsIUpdate update, in boolean background Optional ); Parameters update An nsIUpdate describing the update that was downloaded. ...
...ation in order to install it. If background is true (for example the download was not user initiated) and the app.update.silent preference is true the call will be a no-op. void showUpdateDownloaded( in nsIUpdate update, in boolean background Optional ); Parameters update An nsIUpdate describing the update that was downloaded. background Optional An optional parameter that, if provided and true, presents a less-obtrusive, non-modal notification alert. showUpdateError() Displays an error message telling the user about an update failure, such as a failure to successfully apply a patch. If the app.update.silent preference is true the call will be a no-op. void showUpdateError( in nsIUpdate update ); Parameters update An nsIUpdate describing the update that failed to install. The nsIUp...
.... showUpdateHistory() Shows a list of all updates that have been installed to date. void showUpdateHistory( in nsIDOMWindow parent ); Parameters parent An nsIDOMWindow indicating the parent window to which to anchor the update list window. This can be null. showUpdateInstalled() Shows a message detailing the update that was just installed successfully. 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. void showUpdateInstalled( in nsIUpdate update Obsolete since Gecko 1.9.1 ); Parameters update Obsolete since Gecko 1.9.1 An nsIUpdate describing the update that was installed. See also nsIUpdate nsIUpdateCheckListener nsIUpdateChecker nsIUpdatePatch nsIApplicationUpdateS...
nsIWebContentHandlerRegistrar
be of either the http or https schemes. title The title of the handler presented to the user as a string. contentWindow The DOM content window from which the method has been called. Note: Script must execute from same domain as uri or else it will throw permission error. Can bypass this by opening about:config and setting preference of gecko.handlerService.allowRegisterFromDifferentHost to true. Examples Register a webmail service as mailto handler The following code aims to add "Outlook.com Live Mail" to list of webservice handlers. In the image below "Gmail" and "Yahoo! Mail" already exist as webservice handlers. Cu.import('resource://gre/modules/Services.jsm'); var nsiwchr = Cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"] .getService(Ci...
...tocol handler'Permission denied to add http://mail.live.com/secure/start?action=compose&to=%s as a content or protocol handler' when calling method: [nsIWebContentHandlerRegistrar::registerProtocolHandler] If the host names do match then a confirmation like this will be seen: This domain check can be bypassed by setting the preference of gecko.handlerService.allowRegisterFromDifferentHost to true as in this code here: var {classes: Cc, interfaces: Ci, utils: Cu} = Components; Cu.import("resource://gre/modules/Services.jsm"); var nsiwchr = Cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"] .getService(Ci.nsIWebContentHandlerRegistrar); var allowRegisterFromDifferentHost = Services.prefs.getBoolPref('gecko.handlerService.allowRegisterFromDifferentHost'...
...jsm"); var nsiwchr = Cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"] .getService(Ci.nsIWebContentHandlerRegistrar); var allowRegisterFromDifferentHost = Services.prefs.getBoolPref('gecko.handlerService.allowRegisterFromDifferentHost'); if (!allowRegisterFromDifferentHost) { Services.prefs.setBoolPref('gecko.handlerService.allowRegisterFromDifferentHost', true); } var htmlContentWindow = Services.wm.getMostRecentWindow('navigator:browser'); //because we set the preference to true above, we need any window that has a browser, just pass the DOMWindow and the registerProtocolHandler will get the contentWindow from it nsiwchr.registerProtocolHandler("mailto", "http://mail.live.com/secure/start?action=compose&to=%s", "Outlook.com Live Mail", htmlContentWi...
...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. ...
nsIAbCard/Thunderbird3
ose members are all nsIProperty objects. firstName AString Shorthand for getProperty and setProperty. lastName AString Shorthand for getProperty and setProperty. displayName AString Shorthand for getProperty and setProperty. primaryEmail AString Shorthand for getProperty and setProperty. isMailList boolean If isMailList is true then mailListURI will contain the URI of the associated mail list. This will be removed from the interface at a later date. mailListURI string If isMailList is true then mailListURI will contain the URI of the associated mail list. This will be removed from the interface at a later date. Methods getProperty() Returns a property for the given name. nsIVari...
... [noscript] AUTF8String getPropertyAsAUTF8String(in string name); [noscript] PRUint32 getPropertyAsUint32(in string name); [noscript] boolean getPropertyAsBool(in string name); Returns a property for the given name. These functions convert values in the same manner as the default implementation of nsIVariant. Of particular note is that boolean variables are converted to integers as in C/C++ (true is a non-zero value), so that false will be converted to a string of 0 and not false<code>. These functions are marked <code>[noscript] since XPCconnect performs automatic type conversion on nsIVariant such that they are not needed for scripts, only for C++ callers. Parameters name The case-sensitive name of the property to get. Return value The value of the attribute asked for. Exc...
...n AUTF8String aType); Parameters aType The type of item to translate the card into. Return value A string containing the translated card. Exceptions Thrown NS_ERROR_ILLEGAL_VALUE Type not recognized. copy() This function will copy all values from one card to another. void copy(in nsIAbCard srcCard) Parameters srcCard The source card to copy values from. equals() Returns true if this card is equal to the other card. The default implementation defines equal as this card pointing to the same object as aCard. Another implementation defines it as equality of properties and values. The exact nature of equality is still undefined, and actual results may not match theoretical results. Most notably, the code a.equals(b) == b.equals(a) might not return true. In particular, ca...
...ies and values. The exact nature of equality is still undefined, and actual results may not match theoretical results. Most notably, the code a.equals(b) == b.equals(a) might not return true. In particular, calling equals on cards from different address books may return inaccurate results. boolean equals(in nsIAbCard card) Parameters card The card you are comparing with. Return value true if the cards are the same. generatePhoneticName() Generate a phonetic name from the card, using the firstName and lastName values. AString generatePhoneticName(in boolean aLastNameFirst) Parameters aLastNameFirst Set to true to put the last name before the first. Return value A string containing the generated phonetic name. ...
nsMsgNavigationType
tionType interface contains constants used for message navigation in Thunderbird. For example to move forward a message, you would call: // assuming gDBView is a global nsIMsgDBView var resultId = new Object(); var resultIndex = new Object(); var threadIndex = new Object(); gDBView.viewNavigate(Components.interfaces.nsMsgNavigationType.nextMessage, resultId, resultIndex, threadIndex, true); The nsMsgNavigationType interface is defined as a global variable in Thunderbird: var nsMsgViewCommandType = Components.interfaces.nsMsgViewCommandType; mailnews/base/public/nsIMsgDBView.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Constants Name Value Description firstMessage 1 Go to the first message in the view. nextMessage 2 ...
...ird: var nsMsgViewCommandType = Components.interfaces.nsMsgViewCommandType; mailnews/base/public/nsIMsgDBView.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Constants Name Value Description firstMessage 1 Go to the first message in the view. nextMessage 2 Go to the next message in the view. Will wrap around if the wrap flag is set to true. previousMessage 3 Go to the previous message in the view. Will wrap around if the wrap flag is set to true. lastMessage 4 Go to the last message in the view. toggleThreadKilled 5 Must match nsMsgViewCommandType toggleThreadKilled. firstUnreadMessage 6 Go to the first unread message in the view. nextUnreadMessage 7 Go to the next unread message in the view. Will wrap around if the ...
... lastUnreadMessage 9 Go to the last unread message in the view. ...
... lastUnreadMessage 9 Go to the last unread message in the view. ...
Styling the Folder Pane
d by code in folderPane.js. Since Thunderbird 3, the folder pane is designed in a more modular and extensible fashion. It is now possible to place non-mail entities in the folder pane. Treeview row/cell properties CSS Property Equivalent call Explanation folderNameCol -- A property for indicating that a column is the folder name column. hasUnreadMessages-true aFolder.getNumUnread(false) > 0 Indicates that the folder (but not subfolders) has unread messages. isServer-true aFolder.isServer Indicates that the folder is a root folder (one that represents a server). serverType-server aFolder.server.type Returns the type of the server. For example, IMAP servers are "imap". specialFolder-folderType aFolder.flag...
...map". specialFolder-folderType aFolder.flags & nsMsgFolderFlags.<name> Returns the folder type if it is a special folder (or "none" if it is a regular folder). For example, if the Inbox flag is set, this will be "Inbox". biffState-biffState aFolder.biffState == nsIMsgFolder.nsMsgBiffState_<name> Indicates whether or not the folder has new messages. ...
...r (or "none" if it is a regular folder). For example, if the Inbox flag is set, this will be "Inbox". biffState-biffState aFolder.biffState == nsIMsgFolder.nsMsgBiffState_<name> Indicates whether or not the folder has new messages. isSecure-{true, false} aFolder.server.isSecure Indicates whether or not the connection to the server will be secure. ...
... set, this will be "Inbox". biffState-biffState aFolder.biffState == nsIMsgFolder.nsMsgBiffState_<name> Indicates whether or not the folder has new 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. noSelect-{true, false} aFolder.noSelect Indicates whether or not the folder is selectable. imapShared-{true, false} aFolder.imapShared Indicates whether or not the folder is a shared folder. specialFolder-Smart -- Indicates that the ...
Debugger.Memory - Firefox Developer Tools
he dbg.memory object is an instance of Debugger.Memory; its inherited accesors and methods are described below. Allocation Site Tracking The JavaScript engine marks each new object with the call stack at which it was allocated, if: the object is allocated in the scope of a global object that is a debuggee of some Debugger instancedbg; and dbg.memory.trackingAllocationSites is set to true. A Bernoulli trial succeeds, with probability equal to the maximum of d.memory.allocationSamplingProbability of all Debugger instances d that are observing the global that this object is allocated within the scope of. Given a Debugger.Object instancedobj referring to some object, dobj.allocationSite returns a saved call stack indicating wheredobj's referent was allocated. Allocation Lo...
...allocationSamplingProbability of all Debugger instances d that are observing the global that this object is allocated within the scope of. Given a Debugger.Object instancedobj referring to some object, dobj.allocationSite returns a saved call stack indicating wheredobj's referent was allocated. Allocation Logging Ifdbg is a Debugger instance, and dbg.memory.trackingAllocationSites is set to true, then the JavaScript engine logs each object allocated bydbg's debuggee code. You can retrieve the current log by calling dbg.memory.drainAllocationsLog. You can control the limit on the log's size by setting dbg.memory.maxAllocationsLogLength. Censuses A census is a complete traversal of the graph of all reachable memory items belonging to a particular Debugger's debuggees. It produces a count...
...y instance, which inherits the following accessor properties from its prototype: trackingAllocationSites A boolean value indicating whether this Debugger.Memory instance is capturing the JavaScript execution stack when each Object is allocated. This accessor property has both a getter and setter: assigning to it enables or disables the allocation site tracking. Reading the accessor produces true if the Debugger is capturing stacks for Object allocations, and false otherwise. Allocation site tracking is initially disabled in a new Debugger. Assignment is fallible: if the Debugger cannot track allocation sites, it throws an Error instance. You can retrieve the allocation site for a given object with the Debugger.Object.prototype.allocationSite accessor property. allocationSamplingPr...
...n the presence of multiple Debugger instances observing the same allocations within a global's scope, the maximum allocationSamplingProbability of all the Debuggers is used. maxAllocationsLogLength The maximum number of allocation sites to accumulate in the allocations log at a time. This accessor can be both fetched and stored to. Its default value is 5000. allocationsLogOverflowed Returns true if there have been more than [maxAllocationsLogLength][#max-alloc-log] allocations since the last time [drainAllocationsLog][#drain-alloc-log] was called and some data has been lost. Returns false otherwise. Debugger.Memory Handler Functions Similar to Debugger's handler functions, Debugger.Memory inherits accessor properties that store handler functions for SpiderMonkey to call when given eve...
Debugger.Script - Firefox Developer Tools
ext will be split into two sections, headed by "if the instance refers to a JSScript" and "if the instance refers to WebAssembly code", respectively. If the behavior does not differ, no such emphasized headings will appear. Accessor Properties of the Debugger.Script Prototype Object A Debugger.Script instance inherits the following accessor properties from its prototype: isGeneratorFunction True if this instance refers to a JSScript for a function defined with a function* expression or statement. False otherwise. isAsyncFunction True if this instance refers to a JSScript for an async function, defined with an async function expression or statement. False otherwise. displayName If the instance refers to a JSScript, this is the script's display name, if it has one. If the script has ...
...ed is empty. getOffsetLocation(offset) If the instance refers to a JSScript, return an object describing the source code location responsible for the bytecode atoffset in this script. 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. getOffsetsCoverage(): If the instance refers to a JSScript, return null or an array which contains informations about the coverage of all opcodes. The elements of the array are objects, each of which describes a single opcode, and contains the following properties: lineNumber...
...lumnNumber: the column number of the current opcode. offset: the bytecode instruction offset of the current opcode. count: the number of times the current opcode got executed. If this script has no coverage, or if it is not instrumented, then this function will return null. To ensure that the debuggee is instrumented, the flag Debugger.collectCoverageInfo should be set to true. If the instance refers to WebAssembly code, throw a TypeError. getChildScripts() If the instance refers to a JSScript, return a new array whose elements are Debugger.Script objects for each function in this script. Only direct children are included; nested children can be reached by walking the tree. If the instance refers to WebAssembly code, throw a TypeError. setBreakpoint(offset...
...t at the same location(s) ashandler, they remain in place. clearAllBreakpoints([offset]) If the instance refers to a JSScript, remove all breakpoints set in this script. Ifoffset is present, remove all breakpoints set at that offset in this script; ifoffset is not a valid bytecode offset in this script, throw an error. 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. If the instance refers to WebAssembly code, throw a TypeError. Source Metadata Generated from file: js/src/doc/Debugger/Debugger.Script.md Watermark: sha256:8816a4e8617be32c4ce7f3ae54970fe9c8a7d248175d215a8990ccff23e6efa9 Changeset: 5572465c08a9+ ...
Background Tasks API - Web APIs
didTimeout set to false and a timeRemaining() method which is implemented to give the callback 50 milliseconds of time to begin with. Each time timeRemaining() is called, it subtracts the elapsed time from the original 50 milliseconds to determine the amount of time left. As a result, while our shim doesn't constrain itself to the amount of idle time left in the current event loop pass like the true requestIdleCallback(), it does at least limit the callback to no more than 50 milliseconds of run time per pass. The implementation of our shim for cancelIdleCallback() is much simpler: window.cancelIdleCallback = window.cancelIdleCallback || function(id) { clearTimeout(id); } If cancelIdleCallback() isn't defined, this creates one which simply passes the specified callback ID through to cle...
... For each task in the queue that we have time to execute, we do the following: We remove the task object from the queue. We increment currentTaskNumber to track how many tasks we've executed. We call the task's handler, task.handler, passing into it the task's data object (task.data). We call a function, scheduleStatusRefresh(), to handle s...
... the DOM from within an idle callback. Instead, we'll use requestAnimationFrame() to ask the browser to call us when it's safe to update the display. Scheduling display updates DOM changes are scheduled by calling the scheduleStatusRefresh() function. function scheduleStatusRefresh() { if (!statusRefreshScheduled) { requestAnimationFrame(updateDisplay); statusRefreshScheduled = true; } } This is a simple function. It checks to see if we've already scheduled a display refresh by checking the value of statusRefreshScheduled. If it's false, we call requestAnimationFrame() to schedule a refresh, providing the updateDisplay() function to be called to handle that work. Updating the display The updateDisplay() function is responsible for drawing the contents of the progress b...
...We'll use that to determine if we should update the scroll position to ensure that the log stays at the end when we're done adding content to it. Next, we update the progress and status information if any tasks have been enqueued. If the current maximum value of the progress bar is different from the current total ...
BluetoothCharacteristicProperties - Web APIs
The BluetoothCharacteristicProperties interface of the the Web Bluetooth API provides the operations that are valid on the given BluetoothRemoteGATTCharacteristic. This interface is returned by calling BluetoothRemoteGATTCharacteristic.properties. Properties authenticatedSignedWritesRead only Returns a boolean that is true if signed writing to the characteristic value is permitted. ...
...nterface of the the Web Bluetooth API provides the operations that are valid on the given BluetoothRemoteGATTCharacteristic. This interface is returned by calling BluetoothRemoteGATTCharacteristic.properties. Properties authenticatedSignedWritesRead only Returns a boolean that is true if signed writing to the characteristic value is permitted. broadcastRead only Returns a boolean that is true if the broadcast of the characteristic value is permitted using the Server Characteristic Configuration Descriptor. indicateRead only Returns a boolean that is true if indications of the characteristic value with acknowledgement is permitted. notifyRead only Returns a boolean that is true if notifications of the characteristic value without acknowledgement is permitted. readRead only Ret...
...e characteristic value is permitted using the Server Characteristic Configuration Descriptor. indicateRead only Returns a boolean that is true if indications of the characteristic value with acknowledgement is permitted. notifyRead only Returns a boolean that is true if notifications of the characteristic value without acknowledgement is permitted. readRead only Returns a boolean that is true if the reading of the characteristic value is permitted. reliableWriteRead only Returns a boolean that is true if reliable writes to the characteristic is permitted. ...
...ead only Returns a boolean that is true if notifications of the characteristic value without acknowledgement is permitted. readRead only Returns a boolean that is true if the reading of the characteristic value is permitted. reliableWriteRead only Returns a boolean that is true if reliable writes to the characteristic is permitted. writableAuxiliariesRead only Returns a boolean that is true if reliable writes to the characteristic descriptor is permitted. writeRead only Returns a boolean that is true if the writing to the characteristic with response is permitted. writeWithoutResponseRead only Returns a boolean that is true if the writing to the characteristic without response is permitted. Examples The following example shows how tell if a GATT characteristic supports valu...
Applying styles and colors - Web APIs
nstead of squares. function draw() { var ctx = document.getElementById('canvas').getContext('2d'); for (var i = 0; i < 6; i++) { for (var j = 0; j < 6; j++) { ctx.strokeStyle = 'rgb(0, ' + Math.floor(255 - 42.5 * i) + ', ' + Math.floor(255 - 42.5 * j) + ')'; ctx.beginPath(); ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true); ctx.stroke(); } } } <canvas id="canvas" width="150" height="150"></canvas> draw(); The result looks like this: ScreenshotLive sample Transparency In addition to drawing opaque shapes to the canvas, we can also draw semi-transparent (or translucent) shapes. This is done by either setting the globalAlpha property or by assigning a semi-transparent color to the stroke ...
...Using rgba() gives you a little more control and flexibility because we can set the fil...
...s filled or not. This is useful when a path intersects itself or is nested. Two values are possible: "nonzero": The non-zero winding rule, which is the default rule. "evenodd": The even-odd winding rule. ...
...ntersects itself or is nested. Two values are possible: "nonzero": The non-zero winding rule, which is the default rule. "evenodd": The even-odd winding rule. ...
DirectoryEntrySync - Web APIs
ncludes parent directories that do not exist yet, you get an error. So create the hierarchy by recursively adding a new path after creating the parent directory. Example The getFile() method returns a FileEntrySync, which represents a file in the file system. The following creates an empty file called seekrits.txt in the root directory. ...
... system. The following creates an empty file called seekrits.txt in the root directory. var fileEntry = fs.root.getFile('seekrits.txt', {create: true}); The getDirectory() method returns a DirectoryEntrySync, which represents a file in the file system. The following creates a new directory called superseekrit in the root directory. ...
...); Parameter path Either an absolute path or a relative path from the directory to the file to be looked up or created. You cannot create a file whose immediate parent does not exist. Create the parent directory first. options An object literal describing the behavior of the method. If the file does not exist, it is created. Object literal Condition Result create: true exclusive: true Path already exists An error is thrown. create: true exclusive: false Path doesn't exist and no other error occurs A file is created. If a file already exists, no error is thrown. create: false (exclusive is ignored) Path exists The file is returned. create: false (exclusive is ignored) Path doesn't exist An error ...
...s (FileException); Parameter path Either an absolute path or a relative path from the directory to the file to be looked up or created. You cannot create a file whose immediate parent does not exist. Create the parent directory first. options An object literal describing the behavior of the method if the file does not exist. Object literal Condition Result create: true exclusive: true Path already exists An error is thrown. create: true exclusive: false Path doesn't exist and no other error occurs A directory is created. If a file already exists, no error is thrown. create: false (exclusive is ignored) Path exists The directory is returned. create: false (exclusive is ignored) Path doesn't exist ...
Document.execCommand() - Web APIs
ocument's selection (bold, italics, etc.), while others insert new elements (adding a link), or affect an entire line (indenting). When using contentEditable, execCommand() affects the currently active editable element. Syntax document.execCommand(aCommandName, aShowDefaultUI, aValueArgument) Return value A Boolean that is false if the command is unsupported or disabled. Note: Only returns true if part of a user interaction. Don't try using the return value to verify browser support before calling a command. Parameters aCommandName A DOMString specifying the name of the command to execute. See Commands for a list of possible commands. aShowDefaultUI A Boolean indicating whether the default user interface should be shown. This is not implemented in Mozilla. aValueArgument For c...
...s a value argument. Note that Internet Explorer uses this to set the text background color. bold Toggles bold on/off for the selection or at the insertion point. Internet Explorer uses the <strong> tag instead of <b>. ClearAuthenticationCache Clears all authentication credentials from the cache. contentReadOnly Makes the content document either read-only or editable. This requires a boolean true/false as the value argument. (Not supported by Internet Explorer.) copy Copies the current selection to the clipboard. Conditions of having this behavior enabled vary from one browser to another, and have evolved over time. Check the compatibility table to determine if you can use it in your case. createLink Creates an hyperlink from the selection, but only if there is a selection. Requires a...
...al to hitting the Delete key on a Windows keyboard. heading Adds a heading element around a selection or insertion point line. Requires the tag-name string as a value argument (i.e. "H1", "H6"). (Not supported by Internet Explorer and Safari.) hiliteColor Changes the background color for the selection or at the insertion point. Requires a color value string as a value argument. useCSS must be true for this to function. (Not supported by Internet Explorer.) increaseFontSize Adds a <big> tag around the selection or at the insertion point. (Not supported by Internet Explorer.) indent Indents the line containing the selection or insertion point. In Firefox, if the selection spans multiple lines at different levels of indentation, only the least indented lines in the selection will be inden...
...election or at the insertion point. superscript Toggles superscript on/off for the selection or at the insertion point. underline Toggles underline on/off for the selection or at the insertion point. undo Undoes the last executed command. unlink Removes the anchor element from a selected hyperlink. useCSS Toggles the use of HTML tags or CSS for the generated markup. Requires a boolean true/false as a value argument. NOTE: This argument is logically backwards (i.e. use false to use CSS, true to use HTML) and unsupported by Internet Explorer. This has been deprecated in favor of styleWithCSS. styleWithCSS Replaces the useCSS command. true modifies/generates style attributes in markup, false generates presentational elements. Example An example of how to use it on CodePen. Spec...
FileSystemDirectoryEntry.getDirectory() - Web APIs
an error occurs and an errorCallback was specified, it gets called with a single parameter: a FileError object describing the error. The FileError.code specifies what type of error occurred, as follows: FileError.NOT_FOUND_ERR The create option was not specified (or was specified as false), and the directory doesn't exist. FileError.PATH_EXISTS_ERR The create and exclusive options were both true, indicating that the directory should be created but must not already exist, but the directory does in fact already exist. FileError.SECURITY_ERR The request to access the directory was denied for security reasons. FileError.TYPE_MISMATCH_ERR The path specified is not a directory; it's probably a file, but might be an unsupported file descriptor such as a pipe; this depends on the user agent ...
...th specified is not a directory; it's probably a file, but might be an unsupported file descriptor such as a pipe; this depends on the user agent to some extent. FileSystemFlags The options parameter is an object which is based on the FileSystemFlags dictionary; it provides flags which make it possible to adjust the behavior of the getDirectory() method. create Optional If this property is true, and the requested file or directory doesn't exist, the user agent should create it. The default is false. The parent directory must already exist. exclusive Optional If true, and the create option is also true, the file must not exist prior to issuing the call. Instead, it must be possible for it to be created newly at call time. The default is false. Values and results The table below desc...
...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. true false Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. ...
...lse Path exists The existing file or directory is removed and replaced with a new one, then the successCallback is called with a FileSystemFileEntry or a FileSystemDirectoryEntry, as appropriate. true false Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. true true Path exists The errorCallback is called with an appropriate error, such as FileError.PATH_EXISTS_ERR. true true Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. [1] When create is false, the value of exclusive is irrelevant and ignored. Example In...
FileSystemDirectoryEntry.getFile() - Web APIs
occurs and an errorCallback was specified, it gets called with a single parameter: a FileError object describing the error. The {domxref("FileError.code")}} specifies what type of error occurred, as follows: FileError.NOT_FOUND_ERR The create option was not specified (or was specified as false), and the file doesn't exist. FileError.PATH_EXISTS_ERR The create and exclusive options were both true, indicating that the file should be created but must not already exist, but the file does in fact already exist. FileError.SECURITY_ERR The request to access the file was denied for security reasons. FileError.TYPE_MISMATCH_ERR The path specified is not a file; it's probably a directory, but might be an unsupported file descriptor such as a pipe; this depends on the user agent to some extent.
...he path specified is not a file; it's probably a directory, but might be an unsupported file descriptor such as a pipe; this depends on the user agent to some extent. FileSystemFlags The options parameter is an object which is based on the FileSystemFlags dictionary; it provides flags which make it possible to adjust the behavior of the getFile() method. create Optional If this property is true, and the requested file or directory doesn't exist, the user agent should create it. The default is false. The parent directory must already exist. exclusive Optional If true, and the create option is also true, the file must not exist prior to issuing the call. Instead, it must be possible for it to be created newly at call time. The default is false. Values and results The table below desc...
...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. true false Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. ...
...lse Path exists The existing file or directory is removed and replaced with a new one, then the successCallback is called with a FileSystemFileEntry or a FileSystemDirectoryEntry, as appropriate. true false Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. true true Path exists The errorCallback is called with an appropriate error, such as FileError.PATH_EXISTS_ERR. true true Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. [1] When create is false, the value of exclusive is irrelevant and ignored. Example In...
Guide to the Fullscreen API - Web APIs
To change preferences in Firefox, visit about:config. No support 9 -- 65Alternate Name Alternate Name Uses the non-standard name: mozFullScreenIE No support NoOpera Full support 58 Full support 58 Full support ...
...To change preferences in Firefox, visit about:config. No support 9 -- 65Alternate Name Alternate Name Uses the non-standard name: mozFullScreenOpera Android Full support 50 Full support 50 Full support 14Alternate Name Alternate Name Us...
...To change preferences in Firefox, visit about:config. No support 10 -- 65Alternate Name Alternate Name Uses the non-standard name: mozFullScreenEnabledIE Full support 11Alternate Name Full support 11Alternate Name Alternate Name Uses the non-standard name: msFullScreenEnabledOper...
...To change preferences in Firefox, visit about:config. No support 10 -- 65Alternate Name Alternate Name Uses the non-standard name: mozFullScreenEnabledOpera Android Full support YesSafari iOS ? Samsung Internet Android Full support 5.0 ...
HTMLSlotElement.name - Web APIs
To change preferences in Firefox, visit about:config.IE No supp...
...-- 63Disabled Disabled From version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config. No support ? -- 59Disabled Disabled Until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to true) and the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 40Safari Full support 10.1WebView Android Full support ...
...To change preferences in Firefox, visit about:config.Opera Android ...
...-- 63Disabled Disabled From version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config. No support ? -- 59Disabled Disabled Until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to true) and the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.Opera Android Full support 41Safari iOS Full support 10.3Samsung Internet Android Full support 6.0Legend ...
HTMLVideoElement.msZoom - Web APIs
be large incompatibilities between implementations and the behavior may change in the future. msZoom is a read/write property which gets or sets whether the video frame is trimmed, on the top and bottom or left and right, to fit the video display. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax HTMLVideoElement.msZoom; Value Boolean value set to true trims the video frame to the display space. Set to false the video frame uses letter box or pillarbox to display video. If the native aspect ratio of a video frame, which is defined by the videoWidth and videoHeight attributes, does not match the aspect ratio of the Video tag, which is defined by the width and height attributes, the video is rendered with letterbox or pillarbox format. Letterbox...
...of a video frame, which is defined by the videoWidth and videoHeight attributes, does not match the aspect ratio of the Video tag, which is defined by the width and height attributes, the video is rendered with letterbox or pillarbox format. Letterbox and pillarbox are the black bars on either the left and right of the video or the top and bottom of the video. When the msZoom attribute is set to true, the rendered video is trimmed to fit the dimensions of the video object. Either the top and bottom of the video is trimmed or the left and right of the video is trimmed. For instance, if the layout space for the video tag is a 4:3 aspect ratio, but the stream coming in is in 16:9 aspect ratio, the msZoom option can be used to render the 16:9 video in 4:3 aspect ratio. The rendered video will th...
...d or the left and right of the video is trimmed. ...
... the video tag is a 4:3 aspect ratio, but the stream coming in is in 16:9 aspect ratio, the msZoom option can be used to render the 16:9 video in 4:3 aspect ratio. ...
IDBKeyRange.lowerOpen - Web APIs
The lowerOpen read-only property of the IDBKeyRange interface returns a boolean indicating whether the lower-bound value is included in the key range. Note: This feature is available in Web Workers. Syntax var lowerOpen = myKeyRange.lowerOpen Value A boolean: Value Indication true The lower-bound value is not included in the key range. false The lower-bound value is included in the key range. Example The following example illustrates how you'd use a key range. Here we declare keyRangeValue = IDBKeyRange.upperBound("F", "W", true, true); -- a range that includes everything between "F" and "W" but not including them -- since both the upper and lower bounds have been declared as open (true). We open a transaction (using IDBTransaction...
...between "F" and "W" but not including them -- since both the upper and lower bounds have been declared as open (true). We open a transaction (using IDBTransaction) and an object store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. After declaring the key range, we log its lowerOpen property value to the console, which should appear as "true": the lower bound is open, so won't be included in the range. ...
...er declaring the key range, we log its lowerOpen property value to the console, which should appear as "true": the lower bound is open, so won't be included in the range. ...
...laring the key range, we log its lowerOpen property value to the console, which should appear as "true": the lower bound is open, so won't be included in the range. ...
IDBKeyRange.upperOpen - Web APIs
The upperOpen read-only property of the IDBKeyRange interface returns a boolean indicating whether the upper-bound value is included in the key range. Note: This feature is available in Web Workers. Syntax var upperOpen = myKeyRange.upperOpen Value A boolean: Value Indication true The upper-bound value is not included in the key range. false The upper-bound value is included in the key range. Example The following example illustrates how you'd use a key range. Here we declare keyRangeValue = IDBKeyRange.upperBound("F", "W", true, true); -- a range that includes everything between "F" and "W" but not including them -- since both the upper and lower bounds have been declared as open (true). We open a transaction (using IDBTransaction...
...between "F" and "W" but not including them -- since both the upper and lower bounds have been declared as open (true). We open a transaction (using IDBTransaction) and an object store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. After declaring the key range, we log its upperOpen property value to the console, which should appear as "true": the upper bound is open, so won't be included in the range. ...
...er declaring the key range, we log its upperOpen property value to the console, which should appear as "true": the upper bound is open, so won't be included in the range. ...
...laring the key range, we log its upperOpen property value to the console, which should appear as "true": the upper bound is open, so won't be included in the range. ...
IDBKeyRange - Web APIs
and lower bounds, then it is bounded; if it has no bounds, it is unbounded. A bounded key range can either be open (the endpoints are excluded) or closed (the endpoints are included). ...
... open (the endpoints are excluded) or closed (the endpoints are included). ...
... you can use the following code constructs: Range Code All keys >= x IDBKeyRange.lowerBound(x) All keys > x IDBKeyRange.lowerBound(x, true) All keys <= y IDBKeyRange.upperBound(y) All keys < y IDBKeyRange.upperBound(y, true) All keys >= x && <= y IDBKeyRange.bound(x, y) All keys > x &&< y IDBKeyRange.bound(x, y, true, true) All keys > x && <= y IDBKeyRange.bound(x, y, true, false) All keys >= x &&< y IDBKeyRange.bound(x, y, false, true) The key = z IDBKeyRange.only(z) A key is in a key range if the following conditions are true: The lower value of the key range is one of the following: undefined Less than key value Equal to key value if lowerOpen is fa...
...F". We open a transaction (using IDBTransaction) and an object store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. This means that the cursor will only retrieve records with keys inside that range. This range includes the values "A" and "F", as we haven't declared that they should be open bounds. If we used IDBKeyRange.bound("A", "F", true, true);, then the range would not include "A" and "F", only the values between them. Note: For a more complete example allowing you to experiment with key range, have a look at our IDBKeyRange-example repo (view the example live too.) function displayData() { var keyRangeValue = IDBKeyRange.bound("A", "F"); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = tr...
Intersection Observer API - Web APIs
the target must be a descendant of the root element. How intersection is calculated All areas considered by the Intersection Observer API are rectangles; elements which are irregularly shaped are considered as occupying the smallest rectangle which encloses all of the element's parts. Similarly, if the visible portion of an element is not rectangular, the element's intersection rectangle is construed to be the smallest rectangle that contains all the visible portions of the element. It's useful to understand a bit about how the various properties provided by IntersectionObserverEntry describe an intersection. The intersection root and root margin Before we can track the intersection of an element with a container, we need to know what that container is. That container is the intersection ...
...server. When the callback is invoked, it receives a list of IntersectionObserverEntry objects, one for each observed target which has had the degree to which it intersects the root change such that the amount exposed crosses over one of the thresholds, in either direction. You can see if the target currently intersects the root by looking at the entry's isIntersecting property; if its value is true, the target is at least partially intersecting the root element or document. This lets you determine whether the entry represents a transition from the elements intersecting to no longer intersecting or a transition from not intersecting to intersecting. Note that it's possible to have a non-zero intersection rectangle, which can happen if the intersection is exactly along the boundary between t...
...r each percentage // point). ...
....25, 0.5, 0.75, 1.0] ]; for (let i=0; i<=1.0; i+= 0.01) { thresholdSets[0].push(i); } // Add each box, creating a new observer for each for (let i=0; i<4; i++) { let template = document.querySelector("#boxTemplate").content.cloneNode(true); let boxID = "box" + (i+1); template.querySelector(".sampleBox").id = boxID; wrapper.appendChild(document.importNode(template, true)); // Set up the observer for this box observerOptions.threshold = thresholdSets[i]; observers[i] = new IntersectionObserver(intersectionCallback, observerOptions); observers[i].observe(document.querySelector("#" + boxID)); } // Scroll to the starting position document.scrollingElement.scrollTop = wrapper.firstElementChild.getBoundingClientRect().top + window.scrollY; ...
KeyboardEvent.getModifierState() - Web APIs
The KeyboardEvent.getModifierState() method returns the current state of the specified modifier key: true if the modifier is active (that is the modifier key is pressed or locked), otherwise, false. Syntax var active = event.getModifierState(keyArg); Returns A Boolean Parameters keyArg A modifier key value. The value must be one of the KeyboardEvent.key values which represent modifier keys, or the string "Accel" . This is case-sensitive. Modifier keys on Internet Explorer IE9 uses "Scroll" for "ScrollLock" and "Win" for "OS". ...
...x var active = event.getModifierState(keyArg); Returns A Boolean Parameters keyArg A modifier key value. The value must be one of the KeyboardEvent.key values which represent modifier keys, or the string "Accel" . This is case-sensitive. Modifier keys on Internet Explorer IE9 uses "Scroll" for "ScrollLock" and "Win" for "OS". ...
...hich are defined after Gecko implements this) are always supported for untrusted events on Gecko. This doesn't depend on the platform. "Accel" virtual modifier Note: The "Accel" virtual modifier has been effectively deprecated in current drafts of the DOM3 Events specification. getModifierState() also accepts a deprecated virtual modifier named "Accel". event.getModifierState("Accel") returns true when at least one of KeyboardEvent.ctrlKey or KeyboardEvent.metaKey is true. In old implementations and outdated specifications, it returned true when a modifier which is the typical modifier key for the shortcut key is pressed. For example, on Windows, pressing Ctrl key may make it return true. However, on Mac, pressing ? Command key may make it return true. Note that which modifier key makes i...
...For example, Firefox users can customize this with a pref, "ui.key.accelKey". Example // Ignore if following modifier is active. ...
MediaStreamConstraints.audio - Web APIs
The MediaStreamConstraints dictionary's audio property is used to indicate what kind of audio track, if any, should be included in the MediaStream returned by a call to getUserMedia(). To learn more about how constraints work, see Capabilities, constraints, and settings. Syntax var audioConstraints = true | false | MediaTrackConstraints; Value The value of the audio property can be specified as either of two types: Boolean If a Boolean value is specified, it simply indicates whether or not an audio track should be included in the 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. MediaTrackConstraints A constr...
...ues for the track's constrainable properties. If you specify constraints, an audio track meeting the constraints is required. Examples For browsers with Feature Policy enabled, the samples below need the microphone feature enabled. See Security in MediaDevices.getUserMedia() for details and examples on how to configure this. Using a Boolean value In this example, we provide a simple value of true for the audio property. This tells getUserMedia() that we require an audio track, but we don't care about any specifics beyond that. HTML content <p>Click the start button below to begin the demonstration.</p> <div id="startButton" class="button"> Start </div> <audio id="audio" autoplay controls></audio><br> <div id="log"></div> CSS content body { font: 14px "Open Sans", "Arial", sans-se...
... Result Using a MediaTrackConstraints object Now let's ...
...e; background-color: darkgreen; } JavaScript content let audioElement = document.getElementById("audio"); let logElement = document.getElementById("log"); function log(msg) { logElement.innerHTML += msg + "<br>"; } document.getElementById("startButton").addEventListener("click", function() { navigator.mediaDevices.getUserMedia({ audio: { sampleSize: 8, echoCancellation: true } }).then(stream => audioElement.srcObject = stream) .catch(err => log(err.name + ": " + err.message)); }, false); Here we see an event handler for a click event which calls getUserMedia(), specifying a set of audio constraints requesting that echo cancellation be enabled and that, if possible, the sample rate be 8 bits per sample instead of the more common 16 bits (possibly as a bandw...
MediaTrackSettings - Web APIs
ice. The microphone on a headset would have a different ID, though. This value is specific to the source of the track's data and is not usable for setting constraints; it can, however, be used for initially selecting media when calling MediaDevices.getUserMedia(). 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. channelCount A long integer value indicating the current value of the channelCount property, specifying the number of audio channels present on the track (therefore indicating how many audio samples exist in each audio frame). This is 1 for mono, 2 for stereo, and so forth. echoCancellation A Boolean indicating the current value of ...
...is false otherwise. channelCount A long integer value indicating the current value of the channelCount property, specifying the number of audio channels present on the track (therefore indicating how many audio samples exist in each audio frame). This is 1 for mono, 2 for stereo, and so forth. echoCancellation A Boolean indicating the current value of the echoCancellation property, specifying true if echo cancellation is enabled, otherwise false. latency A double-precision floating point value indicating the current value of the latency property, specifying the audio latency, in seconds. Latency is the amount of time which elapses between the start of processing the audio and the data being available to the next stop in the audio utilization process. This value is a target value; actual ...
...cifying the audio latency, in seconds. Latency is the amount of time which elapses between the start of processing the audio and the data being available to the next stop in the audio utilization process. This value is a target value; actual latency may vary to some extent for various reasons. noiseSuppression A Boolean which indicates the current value of the noiseSupression property, which is true if noise suppression is enabled and is false otherwise. sampleRate A long integer value indicating the current value of the sampleRate property, specifying the sample rate in samples per second of the audio data. Standard CD-quality audio, for example, has a sample rate of 41,000 samples per second. sampleSize A long integer value indicating the current value of the sampleSize property, sp...
...ows of the application chosen by the user rendered into the one video track. browser The stream contains the contents of a single browser tab selected by the user. monitor The stream's video track contains the entire contents of one or more of the user's screens. window The stream contains a single window selected by the user for sharing. logicalSurface A Boolean value which, if true, indicates that the video contained in the stream's video track contains a background rendering context, rather than a user-visible one. This is false if the video being captured is coming from a foreground (user-visible) source. Specifications Specification Status Comment Screen CaptureThe definition of 'MediaTrackSettings' in that specification. Working Draft In...
MutationObserverInit.attributes - Web APIs
The MutationObserverInit dictionary's optional attributes property is used to specify whether or not to watch for attribute value changes on the node or nodes being observed. 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. If true, the callback specified when observe() was used to start observing the node or subtree will be called any time one or more attributes have changed on observed nodes. You can expand the capabilities of attribute mutation monitoring using other options: attributeFilter lets you specify specific attribute names to monitor instead of monitoring all attributes. attributeOldV...
...te mutation monitoring using other options: attributeFilter lets you specify specific attribute names to monitor instead of monitoring all attributes. attributeOldValue lets you specify whether or not you want the previous value of changed attributes to be included in the MutationRecord's oldValue property. subtree lets you specify whether to watch the target node and all of its descendants (true), or just the target node (false). If you set either attributeFilter or attributeOldValue to true, attributes is automatically assumed to be true, even if you don't expressly set it as such. Example In this example, a Mutation Observer is set up to watch for changes to the status and username attributes in any elements contained within a subtree that displays the names of users in a chat room...
...For any items representing an attribute change (which can be detected by the value of MutationRecord.type being "attributes"), a function called notifyUser() is used to tell the user the name of the attribute ...
...For any items representing an attribute change (which can be detected by the value of MutationRecord.type being "attributes"), a function called notifyUser() is used to tell the user the name of the attribute that changed as well as the...
Node.getRootNode() - Web APIs
Web › API › Node › getRootNode
e returns the context object's root, which optionally includes the shadow root if it is available. Syntax var root = node.getRootNode(options); Parameters options Optional An object that sets options for getting the root node. The available options are: composed: A Boolean that indicates whether the shadow root should be returned (false, the default), or a root node beyond shadow root (true). Returns An object inheriting from Node. This will differ in exact form depending on where you called getRootNode(); for example: Calling it on an element inside a standard web page will return an HTMLDocument object representing the entire page. Calling it on an element inside a shadow DOM will return the associated ShadowRoot. Examples The first simple example returns a reference...
... Living Standard Initial definition. ...
... Living Standard Initial definition. ...
... Living Standard Initial definition. ...
PaymentResponse.shippingAddress - Web APIs
urns a PaymentAddress object containing the shipping address provided by the user. Syntax var shippingAddress = PaymentRequest.shippingAddress; Value A PaymentAddress object providing details comprising the shipping address provided by the user. Example Generally, the user agent will fill the shippingAddress property for you. You can trigger this by setting PaymentOptions.requestShipping to true when calling the PaymentRequest constructor. In the example below, the cost of shipping varies by geography. When the PaymentRequest.onshippingaddresschange is called, updateDetails() is called to update the details of the PaymentRequest, using shippingAddress to set the correct shipping cost. // Initialization of PaymentRequest arguments are excerpted for brevity. var payment = new PaymentReq...
...ntResponse) { // Processing of paymentResponse exerpted for the same of brevity. ...
...To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support YesWebView Android No support NoChrome Android Full support 56 ...
...eds to be set to Enabled). To change preferences in Chrome, visit chrome://flags.Firefox Android Full support 56Notes Disabled Full support 56Notes Disabled Notes Available only in nightly builds.Disabled From version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support YesSamsung Internet Android Full support 6.0Legend Full support Full support ...
PaymentResponse.shippingOption - Web APIs
Syntax var shippingOption = PaymentRequest.shippingOption; Example In the example below, the PaymentRequest.onshippingaoptionchange event is called. It calls updateDetails() to toggle the shipping method between "standard" and "express". ...
... Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to...
...To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support YesWebView Android No support NoChrome Android Full support 56 ...
...eds to be set to Enabled). To change preferences in Chrome, visit chrome://flags.Firefox Android Full support 56Notes Disabled Full support 56Notes Disabled Notes Available only in nightly builds.Disabled From version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support YesSamsung Internet Android Full support 6.0Legend Full support Full support ...
Using the Payment Request API - Web APIs
}) } }) PaymentRequest.abort() can be used to abort the payment request if required. Detecting availability of the Payment Request API You can effectively detect support for the Payment Request API by checking if the user's browser supports PaymentRequest, i.e. if (window.PaymentRequest). In the following snippet, a merchant page performs this check, and if it returns true updates the checkout button to use PaymentRequest instead of legacy web forms. const checkoutButton = document.getElementById('checkout-button'); if (window.PaymentRequest) { let request = new PaymentRequest(buildSupportedPaymentMethodNames(), buildShoppingCartDetails()); checkoutButton.addEventListener('click', function() { request.show().then(function(paymentResponse) { // ...
...ctionality in their // privacy settings. The website does not know whether they can make // a fast payment, so pick a generic title. checkoutButton.innerText = "Checkout with W3C"; }); } Note: See our Customizing the payment button demo for the full code. Checking before all prices are known If the checkout flow needs to know whether PaymentRequest.canMakePayment() will return true even before all line items and their prices are known, you can instantiate PaymentRequest with dummy data and pre-query .canMakePayment(). If you call .canMakePayment() multiple times, keep in mind that the first parameter to the PaymentRequest constructor should contain the same method names and data. // The page has loaded. Should the page use PaymentRequest? // If PaymentRequest fails, should...
...ry .canMakePayment(). If you call .canMakePayment() multiple times, keep in mind that the first parameter to the PaymentRequest constructor should contain the same method names and data. // The page has loaded. Should the page use PaymentRequest? // If PaymentRequest fails, should the page fallback to manual // web form checkout? const supportedPaymentMethods = ... 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. // Let's use PaymentRe...
... {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. // Let's use PaymentRequest by default and fallback to legacy // web form based checkout. shouldCallPaymentRequest = true; fallbackToLegacyOnPaymentRequestFailure = true; }); // User has clicked on the checkout button. We know // what's in the cart, but we don't have a `Checkout` object. function onCheckoutButtonClicked(lineItems) { callServerToRetrieveCheckoutDetails(lineItems); } // The server has constructed the `Checkout` object. Now we know // all of the prices and shipping options. function onServerCheck...
RTCPeerConnection.addTrack() - Web APIs
ight as well just let the transceiver handle it for you. Here's an example showing a function that uses getUserMedia() to obtain a stream from a user's camera and microphone, then adds each track from the stream to the peer connection, without specifying a stream for each track: async openCall(pc) { const gumStream = await navigator.mediaDevices.getUserMedia( {video: true, audio: true}); for (const track of gumStream.getTracks()) { pc.addTrack(track); } } The result is a set of tracks being sent to the remote peer, with no stream associations. The handler for the track event on the remote peer will be responsible for determining what stream to add each track to, even if that means simply adding them all to the same stream. The ontrack handler might look l...
.... This includes things like changes to the transceiver's direction and tracks being halted using removeTrack(). For example, consider this function that an application might use to begin streaming a device's camera and microphone input over an RTCPeerConnection to a remote peer: async openCall(pc) { const gumStream = await navigator.mediaDevices.getUserMedia( {video: true, audio: true}); for (const track of gumStream.getTracks()) { pc.addTrack(track, gumStream); } } The remote peer might then use a track event handler that looks like this: pc.ontrack = ({streams: [stream]} => videoElem.srcObject = stream; This sets the video element's current stream to the one that contains the track that's been added to the connection. Reused senders This method may ...
... is set to "sendrecv". The new transceiver is added to the RTCPeerConnection's set of transceivers. Example This example is drawn from the code presented in the article Signaling and video calling and its corresponding sample code. It comes from the handleVideoOfferMsg() method there, which is called when an offer message is received from the remote peer. ...
... to the RTCPeerConnection's set of transceivers. Example This example is drawn from the code presented in the article Signaling and video calling and its corresponding sample code. It comes from the handleVideoOfferMsg() method there, which is called when an offer message is received from the remote peer. ...
RTCPeerConnection.createDataChannel() - Web APIs
maxPacketLifeTime Optional The maximum number of milliseconds that attempts to transfer a message may take in unreliable mode. While this value is a 16-bit unsigned number, each user agent may clamp it to whatever maximum it deems appropriate. Default: null. maxRetransmits Optional The maximum number of times the user agen...
...ides the following fields, any of which may be included in the object passed as the options parameter in order to configure the data channel to suit your needs: ordered Optional Indicates whether or not messages sent on the RTCDataChannel are required to arrive at their destination in the same order in which they were sent (true), or if they're allowed to arrive out-of-order (false). Default: true. maxPacketLifeTime Optional The maximum number of milliseconds that attempts to transfer a message may take in unreliable mode. While this value is a 16-bit unsigned number, each user agent may clamp it to whatever maximum it deems appropriate. Default: null. maxRetransmits Optional The maximum number of times the user agent should attempt to retransmit a message which fails the first time in...
...sub-protocol being used on the RTCDataChannel, if any; otherwise, the empty string (""). Default: empty string, "". This string may not be longer than 65,535 bytes. 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 . Alternatively (true), they can be negotiated out of-band, where both sides call createDataChannel with an agreed-upon id. Default: false. id Optional An 16-bit numeric ID for the channel; permitted values are 0-65534. If you don't include this option, the user agent will select an ID for you. The options which can be configured using the RTCDataChannelInit dictionary represent the script-settable subset of the ...
... Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of '...
Using the Screen Capture API - Web APIs
The possible values are: always The mouse cursor should always be captured in the generated stream. motion The cursor should only be visible while moving, and, at the discretion of the user agent, for a brief time before after moving. Then the cursor is removed from the stream. never The cursor should never be visible in the generated stream. logicalSurface A Boolean which if true indicates that the capture should include offscreen areas of the source, if there are any. None of the constraints are applied in any way until after the content to capture has been selected. The contraints alter what you see in the resulting stream. For example, if you specify a width constraint for the video, it's applied by scaling the video after the user selects the area to share. It does...
...ve). Before starting a project that will require sharing of audio, be sure to check the Browser compatibility in MediaDevices.getDisplayMedia() to see if the browsers you wish compaibility with have support for audio in captured screen streams. ...
...arting a project that will require sharing of audio, be sure to check the Browser compatibility in MediaDevices.getDisplayMedia() to see if the browsers you wish compaibility with have support for audio in captured screen streams. ...
... getDisplayMedia() might look like this: const gdmOptions = { video: true, audio: true } This allows the user total freedom to select whatever they want, within the limits of what the user agent supports. This could be refined further by specifying additional information for each of audio and video: const gdmOptions = { video: { cursor: "always" }, audio: { echoCancellation: true, noiseSuppression: true, sampleRate: 44100 } } In this example the cursor will always be visible in the capture, and the audio track should ideally have noise suppression and echo cancellation features enabled, as well as an ideal audio sample rate of 44.1kHz. Capturing audio is always optional, and even when web content requests a stream with both audio and video, the returned Media...
Slottable: assignedSlot - Web APIs
To change preferences in Firefox, visit about:config.IE No supp...
...-- 63Disabled Disabled From version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config. No support ? -- 59Disabled Disabled Until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to true) and the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 40Safari Full support 10.1WebView Android Full support ...
...To change preferences in Firefox, visit about:config.Opera Android ...
...-- 63Disabled Disabled From version 59 until version 63 (exclusive): this feature is behind the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config. No support ? -- 59Disabled Disabled Until version 59 (exclusive): this feature is behind the dom.webcomponents.enabled preference (needs to be set to true) and the dom.webcomponents.shadowdom.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.Opera Android Full support 41Safari iOS Full support 10.3Samsung Internet Android Full support 6.0Legend ...
Using readable streams - Web APIs
he 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 }. If the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. If the stream becomes errored, the promise will be rejected with the relevant error. Next, we check whether done is true. If so, there are no more chunks to read (the value is undefined) so we return out of the function and close the custom stream with ReadableStreamDefaultController.close(): if (done) { controller.close(); return; } Note: close() is part of the new custom stream, no...
.... If so, there are no more chunks to read (the value is undefined) so we return out of the function and close the custom stream with ReadableStreamDefaultController.close(): if (done) { controller.close(); return; } Note: close() is part of the new custom stream, not the original stream we are discussing here. We'll explain more about the custom stream in the next section. If done is not true, we process the new chunk we've read (contained in the value property of the results object) and then call the pump() function again to read the next chunk. // Enqueue the next data chunk into our target stream controller.enqueue(value); return pump(); This is the standard pattern you'll see when using stream readers: You write a function that starts off by reading the stream. If there is n...
... function readStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properti...
...e process if so, and reading the next chunk and processing it if not, before running the read() method again. function readStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = result; return; } charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Read ' + charsReceived + ' characters so f...
SubtleCrypto.unwrapKey() - Web APIs
ed to derive the key. // In this example it's supplied as a constant "saltBytes". const saltBuffer = bytesToArrayBuffer(saltBytes); // 3 derive the key from key material and salt return window.crypto.subtle.deriveKey( { "name": "PBKDF2", salt: saltBuffer, "iterations": 100000, "hash": "SHA-256" }, keyMaterial, { "name": "AES-KW", "length": 256}, true, [ "wrapKey", "unwrapKey" ] ); } /* Unwrap an AES secret key from an ArrayBuffer containing the raw bytes. Takes an array containing the bytes, and returns a Promise that will resolve to a CryptoKey representing the secret key. */ async function unwrapSecretKey(wrappedKey) { // 1. get the unwrapping key const unwrappingKey = await getUnwrappingKey(); // 2. initialize the wrapped key ...
...y); // 3. unwrap the key return window.crypto.subtle.unwrapKey( "raw", // import format wrappedKeyBuffer, // ArrayBuffer representing key to unwrap unwrappingKey, // CryptoKey representing key encryption key "AES-KW", // algorithm identifier for key encryption key "AES-GCM", // algorithm identifier for key to unwrap true, // extractability of key to unwrap ["encrypt", "decrypt"] // key usages for key to unwrap ); } Unwrapping a "pkcs8" key In this example we unwrap an RSA-PSS private signing key. The key was exported in "pkcs8" format and encrypted using the AES-GCM algorithm, with a key derived from a password. To unwrap, we ask the user for the password and use PBKDF2 and some salt to ...
...d to derive the key. // In this example it's supplied as a constant "saltBytes". const saltBuffer = bytesToArrayBuffer(saltBytes); // 3 derive the key from key material and salt return window.crypto.subtle.deriveKey( { "name": "PBKDF2", salt: saltBuffer, "iterations": 100000, "hash": "SHA-256" }, keyMaterial, { "name": "AES-GCM", "length": 256}, true, [ "wrapKey", "unwrapKey" ] ); } /* Unwrap an RSA-PSS private signing key from an ArrayBuffer containing the raw bytes. Takes an array containing the bytes, and returns a Promise that will resolve to a CryptoKey representing the private key. */ async function unwrapPrivateKey(wrappedKey) { // 1. get the unwrapping key const unwrappingKey = await getUnwrappingKey(); // 2. initialize t...
... Recommendation Initial definition. ...
WebGLRenderingContext.getContextAttributes() - Web APIs
ctual context parameters, or null if the context is lost. ...
...eters, or null if the context is lost. ...
...if the context is lost. ...
... Specifications Specification...
WebGL best practices - Web APIs
ithout having to split into multiple draw calls. Another important method for batching is texture atlasing, where multiple images are placed into a single texture, often like a checkerboard. Since you need to split draw call batches to change textures, texture atlasing lets you combine more draw calls into fewer, bigger batches. Shaders, Programs, and GLSL Avoid "#ifdef GL_ES", which is always true You should never use #ifdef GL_ES in your WebGL shaders; although some early examples used this, it's not necessary, since this condition is always true in WebGL shaders. Prefer doing more work in vertex (not fragment) shaders Do as much as you can in the vertex shader, rather than in the fragment shader. This is because per draw call, fragment shaders generally run many more times than vertex...
...y the answer to this problem, rarely moving work from the vertex to the fragment shader. Compile Shaders and Link Programs in parallel It's tempting to compile shaders and link programs serially, but many browsers can compile and link in parallel on background threads. ...
... gl.linkProgram(prog); if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) { console.error('Link failed: ' + gl.getProgramInfoLog(prog)); console.error('vs info-log: ' + gl.getShaderInfoLog(vs)); console.error('fs info-log: ' + gl.getShaderInfoLog(fs)); } } Consider: function compileOnce(gl, shader) { if (shader.compiled) return; gl.compileShader(shader); shader.compiled = true; } for (const [vs, fs, prog] of programs) { compileOnce(gl, vs); compileOnce(gl, fs); } for (const [vs, fs, prog] of programs) { gl.linkProgram(prog); } for (const [vs, fs, prog] of programs) { if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) { console.error('Link failed: ' + gl.getProgramInfoLog(prog)); console.error('vs info-log: ' + gl.getShaderInfoLog(vs)); console.error...
...nstead, we can use non-integer values for CSS's top/bottom/left/right to fairly reliably 'pre-snap' our canvas to whole integer device coordinates. Demo: https://jdashg.github.io/misc/webgl/device-pixel-presnap.html ResizeObserver and 'device-pixel-content-box' On supporting browsers (Chromium?), ResizeObserver can be used with 'device-pixel-content-box' to request a callback that includes the true device pixel size of an element. This can be used to build an async-but-accurate function: window.getDevicePixelSize = window.getDevicePixelSize || async function(elem) { await new Promise(fn_resolve => { const observer = new ResizeObserver(entries => { for (const cur of entries) { const dev_size = cur.devicePixelContentBoxSize; const ret = { ...
Signaling and video calling - Web APIs
s using this same server, instead of needing a separate server. Let's take a look which changes we need to make to the chat server support WebRTC signaling. This is in the file chatserver.js. First up is the addition of the function sendToOneUser(). As the name suggests, this sends a stringified JSON message to a particular username. function sendToOneUser(target, msgString) { var isUnique = true; var i; for (i=0; i<connectionArray.length; i++) { if (connectionArray[i].username === target) { connectionArray[i].send(msgString); break; } } } This function iterates over the list of connected users until it finds one matching the specified username, then sends the message to that user. The parameter msgString is a stringified JSON object. We could have made it rece...
...for the click event on the list item, that clicking on a user name calls our invite() method, which we'll look at in the next section. Finally, we append the new item to the <ul> that contains all of the user names. Starting a call When the user clicks on a username they want to call, the invite() function is invoked as the event handler for that click event: var mediaConstraints = { audio: true, // We want an audio track video: true // ...and we want a video track }; function invite(evt) { if (myPeerConnection) { alert("You can't start a call because you already have one open!"); } else { var clickedUsername = evt.target.textContent; if (clickedUsername === myUsername) { alert("I'm afraid I can't let you talk to yourself. That would be weird."); return; ...
...This prevents stray event handlers from being triggered while the connection is in the process of closing, potentially causing errors. For both remote and local video streams,...
...et myPeerConnection to null, ensuring our code learns there's no ongoing call; this is useful when the user clicks a name in the user list. Then for both the incoming and outgoing <video> elements, we remove their src and srcobject attributes using their removeAttribute() methods. This completes the disassociation of the streams from the video elements. Finally, we set the disabled property to true on the "Hang Up" button, making it unclickable while there is no call underway; then we set targetUsername to null since we're no longer talking to anyone. This allows the user to call another user, or to receive an incoming call. Dealing with state changes There are a number of additional events you can set listeners for which notifying your code of a variety of state changes. We use three of ...
Writing a WebSocket server in C# - Web APIs
); Console.WriteLine("A client connected."); } } TcpClient Methods: System.Net.Sockets.NetworkStream GetStream() Gets the stream which is the communication channel. Both sides of the channel have reading and writing capability. Properties: int Available This Property indicates how many bytes of data have been sent. The value is zero until NetworkStream.DataAvailable is true. NetworkStream Methods: Write(Byte[] buffer, int offset, int size) Writes bytes from buffer, offset and size determine length of message. Read(Byte[] buffer, int offset, int size) Reads bytes to buffer. offset and size determine the length of the message. Let us extend our example. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("A client connected."); NetworkStream...
...d size determine length of message. Read(Byte[] buffer, int offset, int size) Reads bytes to buffer. offset and size determine the length of the message. Let us extend our example. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("A client connected."); NetworkStream stream = client.GetStream(); //enter to an infinite cycle to be able to handle every change in stream while (true) { while (!stream.DataAvailable); Byte[] bytes = new Byte[client.Available]; stream.Read(bytes, 0, bytes.Length); } Handshaking When a client connects to a server, it sends a GET request to upgrade the connection to a WebSocket from a simple HTTP request. This is known as handshaking. This sample code can detect a GET from the client. Note that this will block until the first 3 b...
...ess.Parse(ip), port); server.Start(); Console.WriteLine("Server has started on {0}:{1}, Waiting for a connection...", ip, port); TcpClient client = server.AcceptTcpClient(); Console.WriteLine("A client connected."); NetworkStream stream = client.GetStream(); // enter to an infinite cycle to be able to handle every change in stream while (true) { while (!stream.DataAvailable); while (client.Available < 3); // match against "get" byte[] bytes = new byte[client.Available]; stream.Read(bytes, 0, client.Available); string s = Encoding.UTF8.GetString(bytes); if (Regex.IsMatch(s, "^GET", RegexOptions.IgnoreCase)) { Console.WriteLine("=====Handshaking fr...
...ing Protocols\r\n" + "Connection: Upgrade\r\n" + "Upgrade: websocket\r\n" + "Sec-WebSocket-Accept: " + swkaSha1Base64 + "\r\n\r\n"); stream.Write(response, 0, response.Length); } else { bool fin = (bytes[0] & 0b10000000) != 0, mask = (bytes[1] & 0b10000000) != 0; // must be true, "All messages from the client to the server have this bit set" int opcode = bytes[0] & 0b00001111, // expecting 1 - text message msglen = bytes[1] - 128, // & 0111 1111 offset = 2; if (msglen == 126) { // was ToUInt16(bytes, offset) but the result is incorrect msglen = BitConverter.T...
Advanced techniques: Creating and sequencing audio - Web APIs
e for the notes that are to be played, and the functionality to play them using the functions we've previously created: const notesInQueue = []; function scheduleNote(beatNumber, time) { // push the note on the queue, even if we're not playing. ...
...t notesInQueue = []; function scheduleNote(beatNumber, time) { // push the note on the queue, even if we're not playing. ...
.... notesInQueue.push({ note: beatNumber, time: time }); if (pads[0].querySelectorAll('button')[currentNote].getAttribute('aria-checked') === 'true') { playSweep() } if (pads[1].querySelectorAll('button')[currentNote].getAttribute('aria-checked') === 'true') { playPulse() } if (pads[2].querySelectorAll('button')[currentNote].getAttribute('aria-checked') === 'true') { playNoise() } if (pads[3].querySelectorAll('button')[currentNote].getAttribute('aria-checked') === 'true') { playSourceNode(audioCtx, sample); } } Here we look at the current time and compare it to the time for the next note; when the two match it will call the previous two functions. function scheduler() { // while there are notes that will need to play befo...
... ...
Sending and Receiving Binary Data - Web APIs
n ArrayBuffer, Blob, Document, JSON, or string. This is null if the request is not complete or was not successful. This example reads an image as a binary file and creates an 8-bit unsigned integer array from the raw bytes. Note that this will not decode the image and read the pixels. You will need a png decoding library for that. ...
... not oReq.responseText if (arrayBuffer) { var byteArray = new Uint8Array(arrayBuffer); for (var i = 0; i < byteArray.byteLength; i++) { // do something with each byte in the array } } }; oReq.send(null); You can also read a binary file as a Blob by setting the string "blob" to the responseType property. var oReq = new XMLHttpRequest(); oReq.open("GET", "/myfile.png", true); oReq.responseType = "blob"; oReq.onload = function(oEvent) { var blob = oReq.response; // ... }; oReq.send(); Receiving binary data in older browsers The load_binary_resource() function shown below loads binary data from the specified URL, returning it to the caller. function load_binary_resource(url) { var req = new XMLHttpRequest(); req.open('GET', url, false); //XHR binary cha...
... method of the XMLHttpRequest has been extended to enable easy transmission of binary data by accepting an ArrayBuffer, Blob, or File object. The following example creates a text file on-the-fly and uses the POST method to send the "file" to the server. This example uses plain text, but you can imagine the data being a binary file instead. var oReq = new XMLHttpRequest(); oReq.open("POST", url, true); oReq.onload = function (oEvent) { // Uploaded. }; var blob = new Blob(['abc123'], {type: 'text/plain'}); oReq.send(blob); Sending typed arrays as binary data You can send JavaScript typed arrays as binary data as well. var myArray = new ArrayBuffer(512); var longInt8View = new Uint8Array(myArray); // generate some data for (var i=0; i< longInt8View.length; i++) { longInt8View[i] = i ...
...uest was added to Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6). Add information about other browsers' support here. Submitting forms and uploading files Please, read this paragraph. Firefox-specific examples This example transmits binary content asynchronously, using the POST method, and Firefox's non-standard sendAsBinary(). var req = new XMLHttpRequest(); req.open("POST", url, true); // set headers and mime-type appropriately req.setRequestHeader("Content-Length", 741); req.sendAsBinary(aBody); Line 4 sets the Content-Length header to 741, indicating that the data is 741 bytes long. Obviously you need to change this value based on the actual size of the data being sent. Line 5 uses the sendAsBinary() method to initiate the request. Note: This non-standard sendAsBinary ...
Synchronous and asynchronous requests - Web APIs
sponsive user experience. Asynchronous request If you use an asynchronous XMLHttpRequest, you receive a callback when the data has been received. This lets the browser continue to work as normal while your request is being handled. Example: send a file to the console log This is the simplest usage of asynchronous XMLHttpRequest. var xhr = new XMLHttpRequest(); xhr.open("GET", "/bar/foo.txt", true); xhr.onload = function (e) { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.error(xhr.statusText); } } }; xhr.onerror = function (e) { console.error(xhr.statusText); }; xhr.send(null); Line 2 specifies true for its third parameter to indicate that the request should be handled asynchronously. Line 3 creates a...
...hrSuccess() { this.callback.apply(this, this.arguments); } function xhrError() { console.error(this.statusText); } function loadFile(url, callback /*, opt_arg1, opt_arg2, ... ...
...operty. Line 12 slices the arguments array given to the invocation of loadFile. Starting with the third argument, all remaining arguments are collected, assigned to the arguments property of the variable xhr, passed to the success callback function xhrSuccess., and ultimately supplied to the callback function (in this case, showMessage) which is invoked by function xhrSuccess. Line 15 specifies true for its third parameter to indicate that the request should be handled asynchronously. Line 16 actually initiates the request. Example: using a timeout You can use a timeout to prevent your code from hanging while waiting for a read to finish. This is done by setting the value of the timeout property on the XMLHttpRequest object, as shown in the code below: function loadFile(url, timeout, cal...
... Usage: function showMessage (message) { console.log(message + this.responseText); } loadFile("message.txt", 2000, showMessage, "New message!\n"); Here, we're specifying a timeout of 2000 ms. Note: Support for timeout was added in Gecko 12.0. ...
Using XMLHttpRequest - Web APIs
uest(); oReq.addEventListener("load", reqListener); oReq.open("GET", "http://www.example.org/example.txt"); oReq.send(); Types of requests A request made via XMLHttpRequest can fetch the data in one of two ways, asynchronously or synchronously. The type of request is dictated by the optional async argument (the third argument) that is set on the XMLHttpRequest.open() method. If this argument is true or not specified, the XMLHttpRequest is processed asynchronously, otherwise the process is handled synchronously. A detailed discussion and demonstrations of these two types of requests can be found on the synchronous and asynchronous requests page. Do not use synchronous requests outside Web Workers. Note: Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous ...
...s.submittedData)); */ } function submitData (oData) { /* the AJAX request... ...
...pRequest(); oAjaxReq.submittedData = oData; oAjaxReq.onload = ajaxSuccess; if (oData.technique === 0) { /* method is GET */ oAjaxReq.open("get", oData.receiver.replace(/(?:\?.*)?$/, oData.segments.length > 0 ? ...
... 0; nFile < oField.files.length; sSearch += "&" + escape(oField.name) + "=" + escape(oField.files[nFile++].name)); } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) { sSearch += "&" + escape(oField.name) + "=" + escape(oField.value); } } oReq.open("get", oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&/, "?")), true); oReq.send(null); } } </script> </head> <body> <h1>Sending forms with FormData</h1> <h2>Using the GET method</h2> <form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;"> <fieldset> <legend>Registration example</legend> <p> First name: <input type="text" name="firstname" /><br /> Last name: <input type="text" name="lastname" /> </p> ...
XMLHttpRequest.withCredentials - Web APIs
s should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests. In addition, this flag is also used to indicate when cookies are to be ignored in the response. The default is false. XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request. The third-party cookies obtained by setting withCredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers. Note: This never affects same-site requests. Note: XMLHttpRequest responses from a different domain cannot set cookie values for their own domain unless withC...
...quest. The third-party cookies obtained by setting withCredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers. Note: This never affects same-site requests. Note: XMLHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request, regardless of Access-Control- header values. ...
...cript through document.cookie or from response headers. Note: This never affects same-site requests. Note: XMLHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request, regardless of Access-Control- header values. ...
... or from response headers. Note: This never affects same-site requests. Note: XMLHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request, regardless of Access-Control- header values. ...
XRWebGLLayerInit - Web APIs
Device API's XRWebGLLayerInit dictionary is used to provide configuration options when creating a new XRWebGLLayer object with the XRWebGLLayer() constructor. The constructor's optional layerInit parameter takes an object which must conform to this dictionary. Properties alpha Optional The frame buffer's color buffer will be established with an alpha channel if the alpha Boolean property is true. Otherwise, the color buffer will not have an alpha channel. The default value is true. antialias Optional A Boolean value which is true if anti-aliasing is to be used when rendering in the context; otherwise false. The browser selects the anti-aliasing method to use; there is no support for requesting a specific mode yet. The default value is true. depth Optional A Boolean value which, if t...
... framebufferScaleFactor Optional A floating-point value which is used to scale the image during compositing, with a value of 1.0 represents the default pixel size for the frame buffer. ...
...amebufferScaleFactor() returns the scale that would result in a 1:1 pixel ratio, thereby ensuring that the rendering is occurring at the device's native resolution. The default is 1.0. ignoreDepthValues Optional A Boolean value which indicates whether or not to ignore the contents of the depth buffer while compositing the scene. The default is false. stencil Optional A Boolean value which, if true, requests that the new layer include a stencil buffer. Otherwise, no stencil buffer is allocated. The default is false. Examples Given an XRSession, xrSession, and a WebGL rendering context, gl, this snippet sets the rendering layer for the session, specifying the ignoreDepthValues option, indicating that the depth buffer should not be used (or should not exist at all), and that the only sourc...
... Working Draft Initial definition. ...
ARIA live regions - Accessibility
The Paciello Group has some information about the state of the support of Live Regions (2014). Paul J. Adam has researched the support of Aria-Atomic and Aria-Relevant in particular. aria-atomic: The aria-atomic=BOOLEAN is used to set whether or not the screen reader should always present the live region as a whole, even if only part of the region changes. The possible settings are: false or true. The default setting is false. aria-relevant: The aria-relevant=[LIST_OF_CHANGES] is used to set what types of changes are relevant to a live region. The possible settings are one or more of: additions, removals, text, all. The default setting is: additions text. aria-labelledby: The aria-labelledby=[IDLIST] is used to associate a region with its labels, similar to aria-controls but instead ass...
...ontent will be announced. For instance, when the clock changes from "17:33" to "17:34", assistive technologies will only announce "4", which won't be very useful to users. One way around this would be to first clear the contents of the live region, and then inject the new content. However, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates. aria-atomic="true" ensures that each time the live region is updated, the entirety of the content is announced in full (e.g. "Time: 17:34"). <div id="clock" role="timer" aria-live="polite" aria-atomic="true"></div> Note: As observed, setting/updating the innerHTML again would cause the whole text to be read again, whether or not you set aria-atomic="true", so the above Clock example does not work as expected. ...
...Display a list of users where a user's log-in and log-out status will be reflected dynamically (without a page reload). <ul id="roster" aria-live="polite"...
...lite"> The set year is: <span id="year-output">1990</span> </div> function change(event) { var yearOut = document.getElementById("year-output"); switch (event.target.id) { case "year": yearOut.innerHTML = event.target.value; break; default: return; } }; Without aria-atomic="true" the screenreader announces only the changed value of year. With aria-atomic="true", the screenreader announces "The set year is: changedvalue" Advanced use case: Roster A chat site would like to display a list of users currently logged in. Display a list of users where a user's log-in and log-out status will be reflected dynamically (without a page reload). <ul id="roster" aria-live="polite" aria-relevant="additions removals"> <!-- use JavaScript to add remove users here--...
ARIA: grid role - Accessibility
ated ARIA roles, states, and properties Roles treegrid (subclass) If a grid has columns that can expanded or collapsed, a treegrid can be used. row A row inside the grid. rowgroup A group containing one or multiple rows. States and properties aria-level Indicates the hierarchical level of the grid within other structures. aria-multiselectable If aria-multiselectable is set to true, multiple items in the grid can be selected. The default value is false. aria-readonly If the user can navigate the grid but not change the value or values of the grid, the aria-readonly should be set to true. The default value is false. For many use cases, an HTML table element is sufficient as it and its elements already include many ARIA roles. Keyboard interactions When a keyboard use...
...on the checkbox. ctrl + A Selects all cells. shift + -> Extends selection one cell to the right. shift + <- Extends selection one cell to the left. shift + ? Extends selection one cell down. shift + ? Extends selection one cell up. ...
...; function moveto(newrow, newcol) { var tgt = document.querySelector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getAttribute('role')==='gridcell') ) { Array.prototype.forEach.call(document.querySelectorAll('[role=gridcell]'), function(el, i){ el.setAttribute('tabindex', '-1'); }); tgt.setAttribute('tabindex', '0'); tgt.focus(); return true; } else { return false; } } document.querySelector('table').addEventListener("keydown", function(event) { switch (event.key) { case "ArrowRight": moveto(parseInt(event.target.dataset.row, 10), parseInt(event.target.dataset.col, 10) + 1); break; case "ArrowLeft": moveto(parseInt(event.target.dataset.row, 10), parseInt(event.target.dataset.col, 10) - 1); b...
...; function moveto(newrow, newcol) { var tgt = document.querySelector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getAttribute('role')==='gridcell') ) { Array.prototype.forEach.call(document.querySelectorAll('[role=gridcell]'), function(el, i){ el.setAttribute('tabindex', '-1'); }); tgt.setAttribute('tabindex', '0'); tgt.focus(); return true; } else { return false; } } document.querySelector('table').addEventListener("keydown", function(event) { switch (event.key) { case "ArrowRight": moveto(parseInt(event.target.dataset.row, 10), parseInt(event.target.dataset.col, 10) + 1); break; case "ArrowLeft": moveto(parseInt(event.target.dataset.row, 10), parseInt(event.target.dataset.col, 10) - 1); b...
CSS Scrollbars - CSS: Cascading Style Sheets
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoFirefox...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support NoLegend Full support Full support ...
...s Full support 64Notes Notes On macOS, you need to set the General > Show scroll bars setting in System Preferences to "Always" for this property to have any effect. Full support 63Disabled Disabled From version 63: this feature is behind the layout.css.scrollbar-color.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoFirefox...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support NoLegend Full support Full support ...
Getting Started - Developer guides
define the actions that will process the response, like this: httpRequest.onreadystatechange = function(){ // Process the server response here. }; Next, after declaring what happens when you receive the response, you need to actually make the request, by calling the open() and send() methods of the HTTP request object, like this: httpRequest.open('GET', 'http://www.example.org/some.file', true); httpRequest.send(); The first parameter of the call to open() is the HTTP request method - GET, POST, HEAD, or another method supported by your server. Keep the method all-capitals as per the HTTP standard, otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods, check the W3C specs. The second parameter is the URL you...
...efault. Be sure to use the exact domain name on all of your pages or you will get a "permission denied" error when you call open(). A common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld. If you really need to send a request to another domain, see HTTP access control (CORS). The optional third parameter sets whether the request is asynchronous. If true (the default), JavaScript execution will continue and the user can interact with the page while the server response has yet to arrive. This is the first A in AJAX. The parameter to the send() method can be any data you want to send to the server if POST-ing the request. Form data should be sent in a format that the server can parse, like a query string: "name=value&anothername="+encodeURICompo...
...e data the server sent. You have two options to access that data: httpRequest.responseText - returns the server response as a string of text httpRequest.responseXML - returns the response as an XMLDocument object you can traverse with JavaScript DOM functions Note that the steps above are valid only if you used an asynchronous request (the third parameter of open() was unspecified or set to true). If you used a synchronous request you don't need to specify a function, but this is highly discouraged as it makes for an awful user experience. Step 3 - A Simple Example Let's put it all together with a simple HTTP request. Our JavaScript will request an HTML document, test.html, which contains the text "I'm a test." Then we'll alert() the contents of the response. Note that this example use...
... if(timeArray[timeArray.length-1] === '') { timeArray.pop(); } ...
<input type="button"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › button
doesn't intefere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are). Disabling and enabling a button To disable a button, simply specify the disabled global attribute on it, like so: <input type="button" value="Disable me" disabled> You can enable and disable buttons at run time by simply setting disabled to true or false. In this example our button starts off enabled, but if you press it, it is disabled using button.disabled = true. A setTimeout() function is then used to reset the button back to its enabled state after two seconds. Hidden code 1 <input type="button" value="Enabled"> const button = document.querySelector('input'); button.addEventListener('click', disableButton); function disableBut...
...ur button starts off enabled, but if you press it, it is disabled using button.disabled = true. A setTimeout() function is then used to reset the button back to its enabled state after two seconds. 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. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a <fieldset> element, and then sett...
...d. Hidden code 2 <fieldset> <legend>Button group</legend> <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. Use the autocomplete attribute to control this feature. Validation Buttons don't participate in constraint validation; they have no real value to be constrained. Examples The below exampl...
... coordinates document.onmousemove = function(e) { curX = (window.Event) ? e.pageX : e.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); curY = (window.Event) ? e.pageY : e.clientY + (document.documentElement.scrollTop ? ...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
ds are provided by the HTMLInputElement interface which represents <input> elements in the DOM. Also available are those methods specified by the parent interfaces, HTMLElement, Element, Node, and EventTarget. checkValidity() Immediately runs the validity check on the element, triggering the document to fire the invalid event at the element if the value isn't valid. reportValidity() Returns true if the element's value passes validity checks; otherwise, returns false. select() Selects the entire content of the <input> element, if the element's content is selectable. For elements with no selectable text content (such as a visual color picker or calendar date input), this method does nothing. setCustomValidity() Sets a custom message to display if the input element's value isn't valid. ...
... :default Form elements that are the default in a group of related elements. Matches checkbox and radio input types that were checked on page load or render. :checked Matches checkbox and radio input types that are currently checked (and the (<option> in a <select> that is currently selected). :indeterminate checkbox elements whose indeterminate property is set to true by JavaScript, radio elements, when all radio buttons with the same name value in the form are unchecked, and <progress> elements in an indeterminate state :valid Form controls that can have constraint validation applied and are currently valid. :invalid Form controls that have constraint validation applied and are currently not valid. Matches a form control whose value do...
...an readonly properties. The validity object includes: validityState.valueMissing validityState.typeMismatch validityState.patternMismatch validityState.tooLong validityState.tooShort validityState.rangeUnderflow validityState.rangeOverflow validityState.stepMismatch validityState.badInput validityState.valid validityState.customError For each of these Boolean properties, a value of true indicates that the specified reason validation may have failed is true, with the exception of the valid property, which is true if the element's value obeys all constraints. If there is an error, supporting browsers will both alert the user and prevent the form from being submitted. A word of caution: if a custom error is set to a truthy value (anything other than the empty string or null), the ...
...rue if the element's value obeys all constraints. If there is an error, supporting browsers will both alert the user and prevent the form from being submitted. A word of caution: if a custom error is set to a truthy value (anything other than the empty string or null), the form will be be prevented from being submitted. If there is no custom error message, and none of the other properties return true, valid will be true, and the form can be submitted. function validate(input) { let validityState_object = input.validity; if(validityState_object.valueMissing) { input.setCustomValidity('A value is required'); } else if (input.rangeUnderflow) { input.setCustomValidity('Your value is too low'); } else if (input.rangeOverflow) { input.setCustomValidity('Your value is too high'...
<template>: The Content Template element - HTML: Hypertext Markup Language
Web › HTML › Element › template
f the template element's content attribute. ...
...} The result is the original HTML table, with two new rows appended to it via JavaScript: table { background: #000; ...
...fer to the elements within it. ...
...secondClone is an HTMLDivElement instance, clicking on it works as one would expect. Specifications Specification Status Comment...
Global attributes - HTML: Hypertext Markup Language
classes of the element. Classes allows CSS and JavaScript to select and access specific elements via the class selectors or functions like the method Document.getElementsByClassName(). contenteditable An enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing. 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. contextmenu The id of a <menu> to use as the contextual menu for this element. data-* Forms a class of attributes, called custom data attributes, that allow proprietary information to be exchanged between the HTML and its DOM representation that may be u...
... (like Arabic); auto, which lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then it applies that directionality to the whole element. draggable An enumerated attribute indicating whether the element can be dragged, using the Drag and Drop API. 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. dropzone An enumerated attribute indicating what types of content can be dropped on an element, using the Drag and Drop API. It can have the following values: copy, which indicates that dropping will create a copy of the element that was dragged move, which indicates that t...
...shadow tree via the ::part pseudo-element. slot Assigns a slot in a shadow DOM shadow tree to an element: An element with a slot attribute is assigned to the slot created by the <slot> element whose name attribute's value matches that slot attribute's value. spellcheck An enumerated attribute defines whether the element may be checked for spelling errors. 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. style Contains CSS styling declarations to be applied to the element. Note that it is recommended for styles to be defined in a separate file or files. This attribute and the <style> element have mainly the purpose of all...
...n Snapshot of HTML Living Standard. From HTML5, contextmenu, draggable, dropzone, and spellcheck have been added. HTML5The definition of 'Global attributes' in that specification. Recommendation Snapshot of HTML Living Standard. From HTML 4.01 Specification, the concept of global attributes is introduced and the dir, lang, style, id, class, tabindex, accesskey, and title are now true global attributes. xml:lang which was initially part of XHTML, is now also part of HTML. hidden, data-*, contenteditable, and translate have been added. HTML 4.01 Specification Recommendation There are no global attributes defined. Several attributes that will become global attributes in subsequent specifications are defined on a subset of elements. class and style are ...
Working with objects - JavaScript
the statement in which it appears is executed. Identical object initializers create distinct objects that will not compare to each other as equal. Objects are created as if a call to new Object() were made; that is, objects made from object literal expressions are instances of Object. The following statement creates an object and assigns it to the variable x if and only if the expression cond is true: if (cond) var x = {greeting: 'hi there'}; The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties. var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}; You can also use object initializers to create arrays. See array literals. Using a constructor function Alternatively, you can create an o...
...ty. 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 distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true. // 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 ...
... ...
... ...
Array.prototype.map() - JavaScript
7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { var kValue, mappedValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal // method of O with argument Pk. kValue = O[k]; // ii. Let mappedValue be the result of calling the Call internal // method of callback with T as the this value and argument // list containing kValue, k, and O. mappedValue = callback.call(T, kVa...
...appedValue be the result of calling the Call internal // method of callback with T as the this value and argument // list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. ...
...ling the Call internal // method of callback with T as the this value and argument // list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. ...
... method of callback with T as the this value and argument // list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments // Pk, Property Descriptor // { Value: mappedValue, // Writable: true, // Enumerable: true, // Configurable: true }, // and false. // In browsers that support Object.defineProperty, use the following: // Object.defineProperty(A, k, { // value: mappedValue, // writable: true, // enumerable: true, // configurable: true // }); // For best browser support, use the following: A[k] = mappedValue; } // d. Increase ...
Object.defineProperties() - JavaScript
props An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties. Each value in props must be either a data descriptor or an accessor descriptor; it cannot be both (see Object.defineProperty() for more details). Data descriptors and accessor descriptors may optionally contain the following keys: configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Defaults to false. A data descriptor also has the following optional keys: value The value associated with t...
... Defaults to false. An accessor descriptor also has the following optional keys: get A function which serves as a getter for the property, or undefined if there is no getter. ...
...etc. }); Specifications Specification ECMAScript (ECMA-262)The definition of 'Object.defineProperties' in that specification. ...
...etc. }); Specifications Specification ECMAScript (ECMA-262)The definition of 'Object.defineProperties' in that specification. ...
Object.prototype.isPrototypeOf() - JavaScript
hain. ...
... F...
... For example, check if baz object descends from Foo.proto...
... For example, check if baz object descends from Foo.prototype: if (Foo.prototype.isPrototypeOf(baz)) { // do som...
handler.getPrototypeOf() - JavaScript
llowing invariants are violated, the proxy will throw a TypeError: getPrototypeOf() method must return an object or null. If target is not extensible, Object.getPrototypeOf(proxy) method must return the same value as Object.getPrototypeOf(target). ...
... throw a TypeError: getPrototypeOf() method must return an object or null. If target is not extensible, Object.getPrototypeOf(proxy) method must return the same value as Object.getPrototypeOf(target). ...
...Of(proxy) method must return the same value as Object.getPrototypeOf(target). ...
... console.log(this === handler); // true return proto; } }; const p = new Proxy(obj, handler); console.log(Object.getPrototypeOf(p) === proto); // true Five ways to trigger the getPrototypeOf trap const obj = {}; const p = new Proxy(obj, { getPrototypeOf(target) { return Array.prototype; } }); console.log( Object.getPrototypeOf(p) === Array.prototype, // true Reflect.getPrototypeOf(p) === Array.prototype, // true p.__proto__ === Array.prototype, // true Array.prototype.isPrototypeOf(p), // true p instanceof Array // true ); Two kinds of exceptions const obj = {}; const p = new Proxy(obj, { getPrototypeOf(target) { return 'foo'; } }); Object.getPrototypeOf(p); // ...
RegExp.prototype.sticky - JavaScript
repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. 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. The "y" flag indicates that it matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes). A regular expression defined as both sticky and global ignores the global flag. You cannot change this property directly. It is read-only. Examples Using...
...Index property of this regular expression in the target string (and does not attempt to match from any later indexes). A regular expression defined as both sticky and global ignores the global flag. You cannot change this property directly. It is read-only. 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. Th...
...ng with the ^ assertion and using the sticky flag to match when they shouldn't. The bug was introduced some time after Firefox 3.6 (which had the sticky flag but not the bug) and fixed in 2015. ...
... of the input, or (if multiline is true) at the beginning of a line. Examples of correct behavior: var regex = /^foo/y; regex.lastIndex = 2; regex.test('..foo'); // false - index 2 is not the beginning of the string var regex2 = /^foo/my; regex2.lastIndex = 2; regex2.test('..foo'); // false - index 2 is not the beginning of the string or line regex2.lastIndex = 2; regex2.test('.\nfoo'); // true - index 2 is the beginning of a line Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.prototype.sticky' in that specification. ...
String.prototype.includes() - JavaScript
The includes() method determines whether one string may be found within another string, returning true or false as appropriate. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.includes(searchString[, position]) Parameters searchString A string to be searched for within str. position Optional The position within the string at which to begin searching for searchString. (Defaults to 0.) Return value true if the search string is found anywhere within the given string; otherwise, false if not. Description This method lets you determine whether or not a string includes another string. Case-sensiti...
... ...
... ...
... ...
Destructuring assignment - JavaScript
let a, b; ({a, b} = {a: 1, b: 2}); Notes: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declarat...
... let a, b; ({a, b} = {a: 1, b: 2}); Notes: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration. {a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand si...
...d not an object literal. However, ({a, b} = {a: 1, b: 2}) is valid, as is const {a, b} = {a: 1, b: 2} Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line. Assigning to new variable names A property can be unpacked from an object and assigned to a variable with a different name than the object property. const o = {p: 42, q: true}; const {p: foo, q: bar} = o; console.log(foo); // 42 console.log(bar); // true Here, for example, const {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo. Default values A variable can be assigned a default, in the case that the value unpacked from the object is undefined. const {a = 10, b = 5} = {a: 3}; console.log(a); // 3 console.log(...
...erable property keys that are not already picked off by the destructuring pattern. let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40} a; // 10 b; // 20 rest; // { c: 30, d: 40 } Invalid JavaScript identifier as a property name Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid. const foo = { 'fizz-buzz': true }; const { 'fizz-buzz': fizzBuzz } = foo; console.log(fizzBuzz); // "true" Combined Array and Object Destructuring Array and Object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following: const props = [ { id: 1, name: 'Fizz'}, { id: 2, name: 'Buzz'}, { id: 3, name: 'FizzBuzz'} ...
yield* - JavaScript
ject, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax yield* expression; expression The expression which returns an iterable object. Description The yield* expression iterates over the operand and yields each value returned by it. The value of yield* expression itself is the value returned by that iterator when it's closed (i.e., when done is true). Examples Delegating to another generator In following code, values yielded by g1() are returned from next() calls just like those which are yielded by g2(). 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, d...
... 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.nex...
... 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()); ...
... ...
function* - JavaScript
ates whether the generator has yielded its last value, as a boolean. Calling the next() method with an argument will resume the generator function execution, replacing the yield expression where an execution was paused with the argument from next(). A return statement in a generator, when executed, will make the generator finish (i.e. the done property of the object returned by it will be set to true). If a value is returned, it will be set as the value property of the object returned by the generator. Much like a return statement, an error is thrown inside the generator will make the generator finished -- unless caught within the generator's body. When a generator is finished, subsequent next() calls will not execute any of that generator's code, they will just return an object of this for...
...t will be set as the value property of the object returned by the generator. Much like a return statement, an error is thrown inside the generator will make the generator finished -- unless caught within the generator's body. When a generator is finished, subsequent next() calls will not execute any of that generator's code, they will just return an object of this form: {value: undefined, done: true}. Examples Simple example function* idMaker() { var index = 0; while (true) yield index++; } var gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // 3 // ... Example with yield* function* anotherGenerator(i) { yield i + 1; yield i + 2; yield i + 3; } function* generator...
...ement 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 obje...
... 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 constructo...
import - JavaScript
ModuleExportName as shortName, anotherLongModuleName as short } from '/modules/my-module.js'; Import a module for its side effects only Import an entire module for side effects only, without importing anything. This runs the module's global code, but doesn't actually import any values. import '/modules/my-module.js'; This works with dynamic imports as well: (async () => { if (somethingIsTrue) { // import module for side effects await import('/modules/my-module.js'); } })(); If your project uses packages that export ESM, you can also import them for side effects only. This will run the code in the package entry point file (and any files it imports) only. Importing defaults It is possible to have a default export (whether it is an object, a function, a class, etc.). The i...
...st. For instance: import myDefault, * as myModule from '/modules/my-module.js'; // myModule used as a namespace or import myDefault, {foo, bar} from '/modules/my-module.js'; // specific, named imports When importing a default export with dynamic imports, it works a bit differently. You need to destructure and rename the "default" key from the returned object. (async () => { if (somethingIsTrue) { const { default: myDefault, foo, bar } = await import('/modules/my-module.js'); } })(); Dynamic Imports The standard import syntax is static and will always result in all code in the imported module being evaluated at load time. In situations where you wish to load a module conditionally or on demand, you can use a dynamic import instead. The following are some reasons why you might ne...
...ur program's memory usage and there is a low likelihood that you will need the code you are importing. When the module you are importing does not exist at load time When the import specifier string needs to be constructed dynamically. (Static import only supports static specifiers.) When the module being imported has side effects, and you do not want those side effects unless some condition is true. (It is recommended not to have any side effects in a module, but you sometimes cannot control this in your module dependencies.) Use dynamic import only when necessary. The static form is preferable for loading initial dependencies, and can benefit more readily from static analysis tools and tree shaking. To dynamically import a module, the import keyword may be called as a function. When use...
... also supports the await keyword. let module = await import('/modules/my-module.js'); Examples Standard Import The code below shows how to import from a secondary module to assist in processing an AJAX JSON request. ...
<mstyle> - MathML
Web › MathML › Element › mstyle
aracter for the alignment point within <mstack> and <mtable> columns, if the decimalpoint value is used to specify the alignment. 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. The main effect is that larger versions of operators are displayed, when displaystyle is set to true. See also largeop and movablelimits on <mo>. infixlinebreakstyle Specifies the default linebreakstyle to use for infix operators. The values before, after and duplicate are allowed. scriptlevel Controls mostly the font-size. The higher the scriptlevel, the smaller the font size. This attribute accepts a non-negative integer, as well as a "+" or a "-" sign, which increments or decrements the c...
...ce or voffset do not apply to <mpadded>. fontfamily does not apply to <mglyph>. align does not apply to <mtable> or <mstack>. index cannot be set on <mstyle>. src and alt on <mglyph> cannot be set on <mstyle>. actiontype on <maction> cannot be set on <mstyle>. Examples Using displaystyle and mathcolor to effect style changes in the layout of the whole sum. ...
...h>. align does not apply to <mtable> or <mstack>. index cannot be set on <mstyle>. src and alt on <mglyph> cannot be set on <mstyle>. actiontype on <maction> cannot be set on <mstyle>. Examples Using displaystyle and mathcolor to effect style changes in the layout of the whole sum. ...
... displaystyle and mathcolor to effect style changes in the layout of the whole sum. <math> <mstyle displaystyle="true" mathcolor="teal"> <mrow> <munderover> <mo stretchy="true" form="prefix">&sum;</mo> <mrow> <mi>i</mi> <mo form="infix">=</mo> <mn>1</mn> </mrow> <mi>n</mi> </munderover> <mstyle displaystyle="true"> <mfrac> <mn>1</mn> <mi>n</mi> </mfrac> </mstyle> </mrow> </mstyle> </math> Specifications Specification Status Comment MathML 3.0The definition of 'mstyle' in that specification. Recommendation Current specification MathML 2.0The definition of 'mstyle' in that specification. Recommendation Init...
format - SVG: Scalable Vector Graphics
Web › SVG › Attribute › format
given font. Two elements are using this attribute: <altGlyph> and <glyphRef> Context notes Value <string> Default value None Animatable No <string> This value specifies the format of the given font. ...
...o elements are using this attribute: <altGlyph> and <glyphRef> Context notes Value <string> Default value None Animatable No <string> This value specifies the format of the given font. ...
... Animatable No <string> This value specifies the format of the given font. ...
... No <string> This value specifies the format of the given font. Here is a list of font formats and their strings that can be used as values for this attribute: Format string Format truedoc-pfr TrueDoc(TM) Portable Font Resource embedded-opentype Embedded OpenType type-1 PostScript(TM) Type 1 truetype TrueType opentype OpenType, including TrueType Open truetype-gx TrueType with GX extensions speedo Speedo intellifont Intellifont Specifications Specification Status Comment Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'format for <glyphRef>' in that specification. Recom...
panel - Archive of obsolete content
panel.show() when the currently active window is a private window, then the panel will not be shown. Panel limitations Although panels can host HTML documents, they are not implemented as browser tabs, so many things that work in normal web pages do not work inside panels: Prior to Firefox 33, you don't get a context menu. From Firefox 33 you can enable a context menu by passing contextMenu: true to the panel's constructor. The HTML <select> element doesn't work. The HTML <datalist> element doesn't give you autocomplete suggestions (bug 918600). You can't embed Flash (bug 952578). You can't provide tooltips using title attributes (bug 918600). Security warning pages (the "This Connection is Untrusted" warning) does not work, so panels which trigger it will be broken (bug 1031554). M...
...}).show(); // This is equivalent to: require("panel").Panel({ position { top: 40 }, height: 400 }).show(); The same principle is applied in the horizontal axis with width, left and right. focus boolean Set to false to prevent taking the focus away when the panel is shown. Only turn this off if necessary, to prevent accessibility issue. Optional, default to true. contentURL string,URL The URL of the content to load in the panel. That is, they can't refer to remote scripts. The URLs are usually constructed using self.data.url(). From Firefox 34, you can use "./my-file.html" as an alias for self.data.url("my-file.html"). allow object An optional object describing permissions for the content. It...
... usually constructed using self.data.url(). From Firefox 34, you can use "./my-file.html" as an alias for self.data.url("my-file.html"). allow object An optional object describing permissions for the content. It should contain a single key named script whose value is a boolean that indicates whether or not to execute script in the content. script defaults to true. contentScriptFile string,array A URL or an array of URLs. The URLs point to scripts to load into the panel. The scripts must be packaged with the add-on under the add-on's data directory. That is, they can't refer to remote scripts. The URLs are usually constructed using self.data.url(). From Firefox 34, you can use "./my-script.js" as an alias for self.dat...
private-browsing - Archive of obsolete content
rivate browsing by opening a new private browser window. When they do this, any existing non-private windows are kept open, so the user will typically have both private and non-private windows open at the same time. ...
... from such objects. Additionally, add-ons that use low-level modules such as window/utils may see private browser windows with certain functions, even if they have not explicitly opted into private browsing. Respecting private browsing The private-browsing module exports a single function isPrivate() that takes an object, which may be a BrowserWindow, tab, or worker, as an argument. It returns true only if the object is: a private window, or a tab belonging to a private window, or a worker that's associated with a document hosted in a private window any window, tab, or worker if the browser has been configured to never remember history (Options->Privacy->History) Add-ons can use this API to decide whether or not to store user data. For example, here's an add-on that stores the title...
...This may be a BrowserWindow, tab, or worker. ...
tabs - Archive of obsolete content
lobals Functions open(options) Opens a new tab. The new tab will open in the active window or in a new window, depending on the inNewWindow option. Example var tabs = require("sdk/tabs"); // Open a new tab on active window and make tab active. tabs.open("http://www.mysite.com"); // Open a new tab in a new window and make it active. tabs.open({ url: "http://www.mysite.com", inNewWindow: true }); // Open a new tab on active window in the background. tabs.open({ url: "http://www.mysite.com", inBackground: true }); // Open a new tab as an app tab and do something once it's open. tabs.open({ url: "http://www.mysite.com", isPinned: true, onOpen: function onOpen(tab) { // do stuff like listen for content // loading. } }); Parameters options : object Required option...
...d property. Optional options: Name Type isPrivate boolean Boolean which will determine whether the new tab should be private or not. If your add-on does not support private browsing this will have no effect. See the private-browsing documentation for more information. Defaults to false. ...
...r add-on does not support private browsing this will have no effect. See the private-browsing documentation for more information. Defaults to false. inNewWindow boolean If present and true, a new browser window will be opened and the URL will be opened in the first tab in that window. This is an optional property. inBackground boolean If present and true, the new tab will be opened to the right of the active tab and will not be active. This is an optional property. isPinned boolean If present and true, then the new tab will be pinned as an app tab. onOpen function A callback function that will be registered for the 'open' event. This is an optional property. onClose function ...
ui/frame - Archive of obsolete content
lePong, false); Sending JSON In all cases, you can send a string as a message or a JSON object. If you send a JSON object, the SDK takes care of serializing and deserializing it for you: // frame.js var label = window.document.getElementById("linky"); label.addEventListener("click", function() { window.parent.postMessage({ "type" : "ping", "reason" : "they clicked me" }, "*"); }, true); // main.js var { Frame } = require("sdk/ui/frame"); var frame = new Frame({ url: "./frame.html" }); frame.on("message", pong); function pong(e) { if (e.data.type == "ping") { console.log(e.data.reason); e.source.postMessage("pong", event.origin); } } Globals Constructors Frame(options) Creates an frame. Once created, the frame needs to be added to a toolbar for it to be ...
...as the targetOrigin argument to postMessage() if you want to communicate with this particular frame instance. ...
...tMessage() if you want to communicate with this particular frame instance. data, which represents the event's payload. ...
util/match-pattern - Archive of obsolete content
Parameters pattern : string The pattern to use. See Patterns above. MatchPattern Methods test(url) Tests a URL against the match pattern...
... Parameters pattern : string The pattern to use. See Patterns above. MatchPattern Methods test(url) Tests a URL against the match pattern. Parameters url : string The URL to test. Returns boolean ...
... ...
Dialogs and Prompts - Archive of obsolete content
itle="General" description="whatever"/> Note, that you should only use this element in a <dialog>, because otherwise it may be not styled properly. (Although it seems to work in <window> as well). Programmatic button access If you want to access the accept ("OK") and cancel buttons from script, use this: // Disable the OK and Cancel btns document.documentElement.getButton("accept").disabled = true; document.documentElement.getButton("cancel").disabled = true; Links dialog.xml -- XBL bindings for <dialog> and <dialogheader> elements. Passing parameter to a dialog and getting return values from it. Passing arguments and displaying a dialog The following code demonstrates how to pass custom arguments to a dialog, process those arguments in the dialog, and return user-modified argume...
...ssing parameter to a dialog and getting return values from it. Passing arguments and displaying a dialog The following code demonstrates how to pass custom arguments to a dialog, process those arguments in the dialog, and return user-modified arguments to the caller. The code to open a dialog named mydialog.xul and pass it arguments: var params = {inn:{name:"foo", description:"bar", enabled:true}, out:null}; window.openDialog("chrome://myext/content/mydialog.xul", "", "chrome, dialog, modal, resizable=yes", params).focus(); if (params.out) { // User clicked ok. Process changed arguments; e.g. write them to disk or whatever } else { // User clicked cancel. Typically, nothing is done here. } mydialog.xul: <dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper...
...he user clicks OK function onOK() { // Return the changed arguments. // Notice if user clicks cancel, window.arguments[0].out remains null // because this function is never called window.arguments[0].out = {name:document.getElementById("name").value, description:document.getElementById("description").value, enabled:document.getElementById("enabled").checked}; return true; } See also Passing parameter to a dialog and getting return values from it. Displaying the standard "Open File"/"Save File"/"Select Folder" dialogs nsIFilePicker Prompts and the prompt service Now that you understand dialogs, let's examine prompts. Prompts differ from dialogs in that they don't require custom XUL. Because of this, however, they are less customizable. Most web developers ar...
On page load - Archive of obsolete content
// doc.location is a ...
...sion = { init: function() { var appcontent = document.getElementById("appcontent"); // browser if(appcontent){ appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true); } var messagepane = document.getElementById("messagepane"); // mail if(messagepane){ messagepane.addEventListener("load", function(event) { myExtension.onPageLoad(event); }, true); } }, onPageLoad: function(aEvent) { var doc = aEvent.originalTarget; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a Location object (see below for a link). // You can use it to make your code executed on certain pages only. if(doc.location.href.search("forum") > -1) alert("a forum page is loaded"); ...
...he loaded page. // doc.location is a Location object (see below for a link). // You can use it to make your code executed on certain pages only. if(doc.location.href.search("forum") > -1) alert("a forum page is loaded"); // add event listener for page unload aEvent.originalTarget.defaultView.addEventListener("unload", function(event){ myExtension.onPageUnload(event); }, true); }, onPageUnload: function(aEvent) { // do something } }; Current Firefox trunk nightlies will fire the onPageLoad function for not only documents, but xul:images (favicons in tabbrowser). If you only want to handle documents, ensure aEvent.originalTarget.nodeName == "#document" . If you are running code on a page load it is likely you would want to run some cleanup code on page un...
Preferences - Archive of obsolete content
*/ PrefListener.prototype.register = function(trigger) { this._branch.addObserver('', this, false); if (trigger) { let that = this; this._branch.getChildList('', {}). forEach(function (pref_leaf_name) { that._callback(that._branch, pref_leaf_name); }); } }; PrefListener.protot...
...After it's garbage collected, you won't receive notifications anymore, so use the provided examples above, and don't write something like the following code: // DON'T DO THIS Components.classes["@mozilla.org/preferences-servi...
...nents.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService) .getBranch("myextension.prefs.") .QueryInterface(Components.interfaces.nsIPrefBranch2) .addObserver("", this, false); Using prefHasUserValue() nsIPrefBranch.prefHasUserValue(preference) checks whether the preference has been changed from the default value. If so, it will return true, otherwise false. In particular, when no default value exists for a preference, prefHasUserValue() indicates whether a preference exists. Attempting to read a nonexistent preference using one of the get*Pref methods will throw an exception. Using prefHasUserValue() lets you check if the preference exists before attempting to read it. For example: if (prefs.prefHasUserValue("mypref")) { alert(...
Rosetta - Archive of obsolete content
getSource(oScript) : createScript(oScript); } } function parseDocument () { for ( var aScripts = document.getElementsByTagName("script"), nIdx = 0; nIdx ...
...First, you should declare a function which will translate an input plain-text written in C to an output plain-text written in ECMAScript. Let us call this f...
... } if (typeof fCompiler !== "function") { throw new TypeError("rosetta.appendCompiler() \u2013 second argument must be a function"); } if (!Array.isArray(vMimeTypes)) { oDicts[(vMimeTypes).toString()] = fCompiler; return true; } for (var nIdx = 0; nIdx < vMimeTypes.length; nIdx++) { oDicts[(vMimeTypes[nIdx]).toString()] = fCompiler; } return true; }; })(); Now, imagine you need a compiler for scripts written in C (MIME type: text/x-c). First, you should declare a function which will translate an input plain-text written in C to an output plain-text written in ECMAScript. Let us call this function createECMASrc() and let us associate it with the C MIME types: rosetta_c.js: A C compiler /* C Compiler for Rosetta */ (function () { ...
StringView - Archive of obsolete content
ere a normal length property. For custom cycles, look at the example proposed here. toBase64() Syntax stringView.toBase64([wholeBuffer]) Description Returns a base64-encoded string corresponding to the stringView or to its buffer. Arguments wholeBuffer Optional A boolean expressing whether the returned base64-encoded string will correspond to the whole buffer (true) or to the stringView (false or omitted). Examples var myStringView = new StringView("\u6432\u6432\u6432\u6432"); alert(StringView.makeFromBase64(myStringView.toBase64())) // ???? See also: Base64 encoding and decoding. subview() Syntax stringView.subview(characterOffset[, charactersLength]) Description Returns a new stringView object which will share the ...
...methods respectively with getUTF16CharLength() and loadUTF16CharCode(). See also: stringView.makeIndex() and its note. valueOf() Syntax stringView.valueOf() Description Converts stringView's content into string and returns it. Arguments none No arguments expected. Examples alert((new StringView("Hello world!")).valueOf() === "Hello world!"); // true JavaScript calls the stringView.valueOf() method to convert an object to a primitive value. You rarely need to invoke the stringView.valueOf() method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. toString() Syntax stringView.toString() Description Converts stringView's content into string and returns it. ...
...() method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. toString() Syntax stringView.toString() Description Converts stringView's content into string and returns it. Arguments none No arguments expected. Examples alert((new StringView("Hello world!")).toString() === "Hello world!"); // true The stringView.toString() method is automatically called when the object is to be represented as a text value or when an object is referred to in a manner in which a string is expected. Appendix: other StringView constructor's methods (utilities) bytesToBase64() Syntax StringView.bytesToBase64(uint8Array) Description Converts an array of bytes (a typed array of Uin...
Enhanced Extension Installation - Archive of obsolete content
tems at the // profile Install Location _globalExtensions // The RDF/XML datasource for the items at the // global Install Location. }; Tracking Install Locations Since there are only two locations, the installed location of an Extension is expressed throughout the code using a boolean value, often referred to as isProfile - true if the item is installed in the profile directory's extensions folder. This boolean relationship itself is not stored directly in the datasource. Rather, if the system needs to know where an item is located, it checks to see if the item is a member of the the appropriate type container (urn:mozilla:extension:root or urn:mozilla:theme:root) in each of the two datasources. This is clumsy. Item Typ...
....ini manifests and create the .autoreg file in the profile directory. Finalization On the next startup, the Startup system discovers the .autoreg file (as before) and starts the Extension System with the dirty flag, which causes the system to scan for items to be installed as before. Regardless of whether or not the Extension System is called from the Startup process with the dirty flag set to true (i.e. the Startup process discovered the .autoreg file, before pending operations are finalized the Extension System reads the extensions-startup.manifest and scans all of the Install Locations looking for items that match the following criteria: Item in Install Location is not listed in Startup Manifest (new item being installed by just appearing in the Install Location). Item in Install Loc...
...stall Locations in the list - that is there were actually two RDF containers and ordering is unique to each. By moving to a unified datasource where Install Location containment is expressed as a property, user-defined ordering can be respected. Extension authors installing into restricted Install Locations can specify that their item does not show up in the Extensions UI by using the <em:hidden>true<em:hidden> property in their Install Manifests. This property is ignored for Extensions installed into unrestricted locations, such as the profile location, to prevent abuse. There is more logging for failures in the installation and update process. The set of error logs written is still neither perfect nor complete, but it's a very good start. Log strings are written to the application's error ...
How to convert an overlay extension to restartless - Archive of obsolete content
available in the global for a window, but in JSM you'll need to fetch it from an interface: const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1", "nsIXMLHttpRequest"); Here's how to load a file using it: function loadFile(url,type,returnresult) { var request = new XMLHttpRequest(); request.open("GET", url, true); // async=true request.responseType = type; request.onerror = function(event) { logErrorMessage("Error attempting to load: " + url); returnresult(null); }; request.onload = function(event) { if (request.response) returnresult(request.response); else request.onerror(event); }; request.send(); } loadFile("chrome://myA...
...else request.onerror(event); }; request.send(); } loadFile("chrome://myAddon/content/filename.ext",dataType,function(data) { /* do stuff with data */ }); Note: When using XMLHttpRequest to access a file:// URL the request.status is not properly set to 200 to indicate success. In such cases, request.readyState == 4, request.status == 0 and request.response will evaluate to true. If your file is text, use "text" as your data type. If you're getting JSON this way make sure to explicitly set the type as "text" if you intend to parse it yourself. Even though it says that the default type is "text", Firefox will attempt to autodetect and fail, resulting in an error message in the console. This doesn't seem to break anything, but it is easily avoidable by being explicit with...
.... So, it's pretty much internal JARor extractionless XPI. Well, you can't use an internal JAR anymore. Firefox aggressively caches add-on data a bit too much. Your restartless add-on won't actually reload some types of files if they are in a JAR and the add-on is updated without a restart. The big culprits are JSM files and locale files (namely property files), though in some situations this is true for dynamically loaded image files too. You're still going to have to manually clear the chrome cache on add-on shutdown to work around this, but that doesn't seem to be enough with an internal JAR. So, time to switch to extractionless, too. See here for the list of stuff you can't have in addition to no resource:// URIs or file:// URIs to files inside your XPI. If you actually can't find a way ...
Adding sidebars - Archive of obsolete content
hello.mainTab.label;" /> <tab label="&xulschoolhello.advancedTab.label;" /> </tabs> <tabpanels> <tabpanel> <!-- Content for the main panel. --> </tabpanel> <tabpanel> <!-- Content for the advanced panel. --> </tabpanel> </tabpanels> </tabbox> The first tab is selected by default, but you can change the default selection by setting the selected attribute to true in the << XUL Reference << element. A tabpanel can hold any kind of content. You should take into account that the whole tab box is going to be as large as the tab strip on the top and the content of the largest panel. You should try to balance the content in the tab panels so that you don't end up with uneven and mostly empty panels. Decks and stacks Sometimes you'll need finer grained contro...
...ecol label="&xulschoolhello.nameColumn.label;" flex="1" /> <treecol label="&xulschoolhello.greetingColumn.label;" flex="3" /> </treecols> <treechildren> <treeitem> <treerow> <treecell label="Peter" /> <treecell label="Hey, what's up?" /> </treerow> </treeitem> <!-- Notice that you need to specify the container attribute. ...
...&xulschoolhello.nameColumn.label;" flex="1" /> <treecol label="&xulschoolhello.greetingColumn.label;" flex="3" /> </treecols> <treechildren> <treeitem> <treerow> <treecell label="Peter" /> <treecell label="Hey, what's up?" /> </treerow> </treeitem> <!-- Notice that you need to specify the container attribute. ...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
Attribute("value", "testValue"); newItem.setAttribute("label", "Another popup menu item"); menuPopup.appendChild(newItem); }; var jsonTemplateBtn = ["xul:toolbarbutton", { id: "myTestButton", class: "toolbarbutton-1", type: "menu", label: "Test button label", tooltiptext: "Test button tooltip", removable: true, key: "myTestButton123" }, [ "menupopup", { onpopupshowing: function(event) { addEntryToPopup(this, document, window); } }, null ] ]; var capturedNodes = {}; var toolbox = doc.getElementById("navigator-toolbox"); var palette = toolbox.palette; var domFragment = jsonToDOM(jsonTemplateBtn, document, capture...
...t fragment while removing any scripts or other unsafe content in the process. let { Cc, Ci } = require("chrome"); /** * Safely parse an HTML fragment, removing any executable * JavaScript, and return a document fragment. * * @param {Document} doc The document in which to create the * returned DOM tree. * @param {string} html The HTML fragment to parse. * @param {boolean} allowStyle If true, allow <style> nodes and * style attributes in the parsed fragment. Gecko 14+ only. * @param {nsIURI} baseURI The base URI relative to which resource * URLs should be processed. Note that this will not work for * XML fragments. * @param {boolean} isXML If true, parse the fragment as XML. */ function parseHTML(doc, html, allowStyle, baseURI, isXML) { let PARSER_UTILS = "@mozi...
... !!isXML, baseURI, doc.documentElement); } return Cc["@mozilla.org/feed-unescapehtml;1"] .getService(Ci.nsIScriptableUnescapeHTML) .parseFragment(html, !!isXML, baseURI, doc.documentElement); } The returned fragment may be appended to any element in the given document. ...
Intercepting Page Loads - Archive of obsolete content
ads. Read the recommendations in Appendix A regarding performance if you're planning on implementing any of these. The Easy Way: Load Events This comes from the tabbrowser code snippets page. In a nutshell, from the chrome code in the overlay we add an event listener for the load event. this._loadHandler = function() {that._onPageLoad(); }; gBrowser.addEventListener("load", this._loadHandler, true); gBrowser is a global object that corresponds to the tabbrowser element in the main browser window. It is full of useful functions, so you should always keep it in mind when you want to handle tabs and web content windows. Attaching the load event handler to gBrowser allows us to listen to these events for all tabs, without having to worry how many tabs are open. gBrowser exists in every brows...
...to handle tabs and web content windows. Attaching the load event handler to gBrowser allows us to listen to these events for all tabs, without having to worry how many tabs are open. gBrowser exists in every browser window. We store the handler function in a private variable because later we want to remove it when we do not need it anymore. gBrowser.removeEventListener("load", this._loadHandler, true); Finally, the actual code for the handler, which is very simple: _onPageLoad : function(event) { // this is the content document of the loaded page. let doc = event.originalTarget; if (doc instanceof HTMLDocument) { // is this an inner frame? if (doc.defaultView.frameElement) { // Frame within a tab was loaded. // Find the root document: while (doc.defaultView...
...he chrome are attached to specific instances of the browser element. What does this mean? It means you have to keep track of tabs being opened and closed, in order to add and remove your listener. ...
XUL user interfaces - Archive of obsolete content
olumn/> </columns> <rows> <row> <label class="text-prompt" value="Date:" accesskey="D" control="date-text"/> <textbox id="date-text" type="timed" timeout="750" oncommand="refresh();"/> </row> <row> <label value="Day:"/> <hbox id="day-box"> <label class="day" value="Sunday" disabled="true"/> <label class="day" value="Monday" disabled="true"/> <label class="day" value="Tuesday" disabled="true"/> <label class="day" value="Wednesday" disabled="true"/> <label class="day" value="Thursday" disabled="true"/> <label class="day" value="Friday" disabled="true"/> <label class="day" value="Saturday" disabled="true"/> ...
...sh() } // called by Date textbox function refresh() { var d = dateBox.value var theDate = null showStatus(null) if (d != "") { try { var a = d.split("/") var theDate = new Date(a[2], a[0] - 1, a[1]) showStatus(theDate) } catch (ex) {} } setDay(theDate) } // internal function setDay(aDate) { if (currentDay) currentDay.setAttribute("disabled", "true") if (aDate == null) currentDay = null else { var d = aDate.getDay() currentDay = dayBox.firstChild while (d-- > 0) currentDay = currentDay.nextSibling currentDay.removeAttribute("disabled") } dateBox.focus(); } function showStatus(aDate) { if (aDate == null) { status.removeAttribute("warning") status.setAttribute("label", "") } else if (aDate === fals...
...If you use a different theme, it changes some user-interface styles and the demonstration might look strange. Open the document in your Moz...
Install.js - Archive of obsolete content
e user (don't include the version) extShortName: 'sampleext', // The leafname of the JAR file (without the .jar part) extVersion: '1.0', extAuthor: 'Insert-your-name-here', extLocaleNames: null, // e.g. ['en-US', 'en-GB'] extSkinNames: null, // e.g. ...
... this.profileInstall = Install.confirm('Install ' + this.extFullName + ' ' + this.extVersion + ' to your Profile directory (OK) or your Browser directory (Cancel)?'); } // Init install var dispName = this.extFullName + ' ' + this.extVersion; var regName = '/' + this.extAuthor + '/' +...
...ED) { if (!this.silentInstall && this.extPostInstallMessage) { Install.alert(this.extPostInstallMessage); } } else { this.handleError(err); return; } }, parseArguments: function() { // Can't use string handling in install, so use if statement instead var args = Install.arguments; if (args == 'p=0') { this.profileInstall = false; this.silentInstall = true; } else if (args == 'p=1') { this.profileInstall = true; this.silentInstall = true; } }, handleError: function(err) { if (!this.silentInstall) { Install.alert('Error: Could not install ' + this.extFullName + ' ' + this.extVersion + ' (Error code: ' + err + ')'); } Install.cancelInstall(err); } }; XpiInstaller.install(); ...
MMgc - Archive of obsolete content
much faster and limit memory growth. All of the rules for GCObject apply to RCObject, and there are a few more: Any pointer to a RCObject from unmanaged memory must use the DRC macro. class MyObject : public MMgc::RCObject { ... }; class MyUnmanagedObject : public MMgc::GCRoot { DRC(MyObject*) myObject; }; Any pointer to a RCObject from managed (GC) memory must use the DRCWB macro. This is true whether the object containing the pointer is GCObject or RCObject. class MyObject : public MMgc::RCObject { ... }; class MyOtherManagedGCObject : public MMgc::GCObject { DRCWB(MyObject*) myObject; }; class MyOtherManagedRCObject : public MMgc::RCObject { DRCWB(MyObject*) myObject; }; The RCObject must zero itself out on deletion. For this reason, RCObject's always have finalizers. Declare ...
... free GC memory (GC::Free) Change the set of GC roots (create a GCRoot object or derivative) Cause itself to become reachable If a finalized object holds a reference to an RCObject, it may safely call decrementref on the RCObject. Threading The GC routines are not currently thread safe, we're operating under the assumption that none of the player spawned threads create GC'd things. If this isn't true we hope to eliminate other threads from doing this and if we can't do that we will be forced to make our GC thread safe, although we hope we don't have to do that. Threading gets more complicated because it makes sense to re-write ChunkMalloc and ChunkAllocBase to get their blocks from the GCHeap. They can also take advantage of the 4K boundary to eliminate the 4 byte per allocation penalty. Trou...
...Another point to consider is whether marking should always be on or should be turned on and off at some point based on memory allocation patterns. I think we want the later because: All WB's take the fast path when we're not marking, so the more time we spend out of the marking phase the better performance will be overall Applications that have low or s...
Using microformats - Archive of obsolete content
formats = Microformats.count(name, rootElement, options); Parameters name The name of the microformat to count. rootElement Required. The DOM element at which to begin the search. If you want to search the entire document, specify content.document. options Optional. If provided, this is a JavaScript object that contains zero or more of the following flags: recurseExternalFrames If true, child frames are included in the search. The default is true. showHidden If true, hidden microformats are added; otherwise they're left out. The default is false. debug Specify true if debug mode is in use; otherwise, specify false. The default is false. Return value An integer value indicating the number of microformats that match the specified criteria. debug() Returns a string that ...
...Microformats.get(name, rootElement, options, targetArray); Parameters name The name of the microformat to find. rootElement Required. The DOM element at which to begin the search. If you want to search the entire document, specify content.document. options Optional. If provided, this is a JavaScript object that contains zero or more of the following flags: recurseExternalFrames If true, child frames that reference external content are included in the search. The default is true. showHidden If true, hidden microformats are added; otherwise they're left out. The default is false. debug Specify true if debug mode is in use; otherwise, specify false. The default is false. targetArray Optional. If provided, this is an array of microformat objects to which the search result...
...node whose parent you wish to retrieve. Return value The parent of the specified node. Returns nothing if the specified node isn't a microformat or the child of a microformat. isMicroformat() Determines whether or not the specified DOM node is a microformat. var flag = Microformats.isMicroformat(node); Parameters node The DOM node to check to see if it's a microformat. Return value true if the node is a microformat, otherwise false. Note: This method doesnot return true if the node is a child of a microformat. See also Microformats.org ...
JavaScript Client API - Archive of obsolete content
entation, for example applyIncomingBatch if the underlying storage for your data supports batch operations. createRecord The createRecord( id, collection ) method gets called by the engine to request a new record for an item with a given GUID. It's your Store's responsibility to instantiate a Record object, assign the given GUID, and return it. itemExists(guid) Should simply return true if an item with the given guid exists in the store, false otherwise. changeItemID(oldId, newId) Must find the stored item currently associated with the guid oldId and change it to be associated with the guid newId. getAllIDs() Must return an iterable list containing the GUIDs of every item being stored on the local system. This can be a dictionary-type object where the keys are th...
...passed in to this method having any of its attributes set correctly except for .id. The .id should be al you need, anyway.) applyIncomingBatch : TODO Example Store Skeleton // Maintains the store of all your Foo-type items and their GUIDs. function FooStore(name) { Store.call(this, name); } FooStore.prototype = { __proto__: Store.prototype, itemExists: function(guid) { // Return true if an item with given guid exists in the store. }, createRecord: function(id, collection) { record = new FooRecord(uri); // Look up the data corresponding to this guid, by the mapping // you've defined. // Set the data and the guid on the new record: record.bar = 17; // or whatever record.id = guid; // return the record return record; }, changeItemID: funct...
...ve: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 = true; } break; case "weave:engine:stop-tracking": if (this._enabled) { // remove event handler or observer here ... this._enabled = false; } break; }, onEvent: function onEvent() { /* Here is where you'd handle the event. See the documentation for whatever service you are observing to find out what to call...
Introducing the Audio API extension - Archive of obsolete content
e: Sample rate per second mozFrameBufferLength: Number of samples collected in all channels This information is needed later to decode the audio data stream. ...
...l: Channel1-Sample1 Channel2-Sample1 Channel1-Sample2 Channel2-Sample2 Channel1-Sample3 Channel2-Sample3. ...
...). It's also possible to auto-detect the minimal duration of the pre-buffer, such that the sound is played without interruptions, and lag between writing and playback is minimal. To do this start writing the data in small portions and wait for the value returned by mozCurrentSampleOffset() to be greater than 0. var prebufferSize = sampleRate * 0.020; // Initial buffer is 20 ms var autoLatency = true, started = new Date().valueOf(); ... // Auto latency detection if (autoLatency) { prebufferSize = Math.floor(sampleRate * (new Date().valueOf() - started) / 1000); if (audio.mozCurrentSampleOffset()) { // Play position moved? autoLatency = false; } Processing an audio stream Since the MozAudioAvailable event and the mozWriteAudio() method both use Float32Array values, it is possible to...
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
before the menu is shown. If the menu is a context menu, it is called as beforeShow(menu, context) and otherwise as beforeShow(menu). menu is the Menu object to which beforeShow is attached. context is an object describing the context in which the menu was shown. beforeShow may modify the menu, and when the menu is shown, it will reflect the changes. isShowing boolean True if the menu is currently visible and false otherwise. Read-only. items array An array of menuitems in the menu. Read-only. Methods add(items) clear() contextOn(node) hide() insertBefore(newItems, target) item(target) popupOn(node) ...
...Due to a platform bug in Firefox, on OS X only, for menus in the menu bar only, command functions defined on menuitems with submenus are not called when descendant menuitems are clicked. See bug 534014 for details and a workaround. data string An arbitrary string that the feature may associate with the menuitem. disabled boolean If true, the menuitem is disabled. icon string The URL of an icon to display in the menuitem. Note that some environments, notably Gnome 2.28, do not support menuitem icons either by default or at all. label string The label of the menuitem. menu jetpack.Menu If defined, the menuitem expands into a submenu. ...
...t: beforeHide beforeShow Note that a jetpack.Menu object is passed to beforeHide and beforeShow, since they are called during a context menu's invocation. They may then modify the menu. Individual menus are drawn from the set using on(): on(selector) Returns a new ContextMenuSet whose context menus are those that arise from nodes that match the given CSS selector(s). The selector must be a true CSS selector, not a jQuery or other type of pseudo-selector. Note: Selectors don't automatically include the children of nodes they match. For example, jetpack.menu.context.page.on("a[href]") does not match images contained in links. To match links and all elements contained in links, use jetpack.menu.context.page.on("a[href], a[href] *"). A future version of Jetpack may change this behavior; ...
Microsummary XML grammar reference - Archive of obsolete content
f conditional intervals based on the content of the page being summarized. Attributes: interval (optional) An absolute interval of time, in minutes, that must elapse between updates. Child Elements: <condition> (optional) An XPath boolean expression along with a conditional interval of time, in minutes, that must elapse between updates if the expression evaluates to true. The interval attribute defines an absolute interval in minutes. Its value must be a number greater than or equal to 1. Fractional values (e.g. 5.5 minutes) are permitted, although they probably aren't useful. The <update> element may contain any number of <condition> child elements. Firefox determines which interval to apply to a microsummary generated by a generator according to the following ...
... <update> element may contain any number of <condition> child elements. Firefox determines which interval to apply to a microsummary generated by a generator according to the following rules: Firefox processes each <condition> child element in document order. For each one, Firefox evaluates the element's XPath boolean expression against the page being summarized. If the expression evaluates to true, Firefox applies that element's interval and stops processing child elements. Thus, the first matching <condition> determines the update interval. If there are no <condition> child elements, or if none of their expressions evaluate to true, Firefox applies the value of the <update> element's interval attribute. If the <update> element does not include an interval attribute, Firefox applies th...
...al indicates; Firefox respects the browser cache when updating microsummaries, so it will not reload a page to update its microsummary if the cache contains a fresh copy of the page. The <condition> element The optional <condition> element specifies an XPath boolean expression along with a conditional interval of time, in minutes, that must elapse between updates if the expression evaluates to true when evaluated against the page being summarized. It must be a child of the <update> element. Attributes: expression (required) An XPath boolean expression to be evaluated against the page being summarized. interval (required) An interval of time, in minutes, that must elapse between updates if the expression evaluates to true. Child Elements: None. For more informat...
Install script template - Archive of obsolete content
You can also simply call refreshPlugins() } else cancelInstall(errBlock1); // PLID solution -- write keys to the registry /** * Function for secondary installation of plugin (FirstInstall). * You should not stop the install process because the function failed, * you still have a chance to ins...
... You can also simply call refreshPlugins() } else cancelInstall(errBlock1); // PLID solution -- write keys to the registry /** * Function for secondary installation of plugin (FirstInstall). * You should not stop the install process because the function failed, * you still have a chance to install the plugin for the already...
... * You should not stop the install process because the function failed. * You still have a chance to install the plugin for the * current Gecko browser. * * @param rootKey must be one of these two string values HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER * @param plidID PLID for Plugins * @param dllAbsolutePath the fully q...
Using XPInstall to Install Plugins - Archive of obsolete content
can pass command line parameters to the executable. An example of calling the execute method from the Install Object on an executable that has a temporary life span (and is not needed after one execution) is: // Initialize the installation .... // initInstall(..... ...
...ng the Install Object's execute method to block on a native installer execute("setup.exe", "-s", true); // In the above sample, assume that running "setup -s" from the // Command Prompt runs the setup executable, and that "-s" is some // invocation parameter defined by the setup.exe file, perhaps to force // the installer to run silently. We are passing "-s" to the setup file. // By passing 'true' we are telling the Install Script to block // on the execution of the installable, and do it synchronously // Must call performInstall to make it all happen... err = getLastError(); if (!err) performInstall(); else cancelInstall(err); Installing Plugin Files To the Current Browser Installing to the current browser is the task that is the most important for the XPI Package to succeed in...
...r window. This install script does all of the following: It installs both a DLL and an XPT file to the browser's plugins directory. The plugin itself is an imaginary one: MyPlugin. The variables that determine the plugin name, however, can be easily modified. This install.js file assumes that the plugin software that is to be installed consists of both a DLL and an XPT file, which is not always true. Many plugins may involve more than one DLL, or perhaps additional native code. It is, however, a safe assumption for most plugins, especially Macromedia's Flash Plugin which consists of a single DLL (on Windows this is npswf32.dll) and a single XPT file for scriptability (called flashplayer.xpt). It further installs to a secondary location on the user's desktop. In particular, like many OCX fil...
Windows Install - Archive of obsolete content
// subkeys have to exist before values can be put in. var subkey; // the name of the subkey you are poking around in var valname; // the name of the value you want to l...
...fLongFilePath; var sShortFilePath; if(fRen8dot3Ini != null) { for(i = 0; i < listLongFilePaths.length; i++) { fLongFilePath = getFolder(fProgram, listLongFilePaths[i]); sShortFilePath = File.windowsGetShortName(fLongFilePath); if(sShortFilePath) { fRen8dot3Ini.writeString("rename", sShortFilePath, fLongFilePath); bIniCreated = true; } } if(bIniCreated) updateWinReg4Ren8dot3() ; } return(0); } // main var srDest; var err; var fProgram; srDest = 449; err = initInstall(prettyName, regName, "6.0.0.2000110801"); logComment("initInstall: " + err); fProgram = getFolder("Program"); logComment("fProgram: " + fProgram); if(verifyDiskSpace(fProgram, srDest)) { setPackageFolder(fProgram); err = addDirect...
...ent("initInstall: " + err); fProgram = getFolder("Program"); logComment("fProgram: " + fProgram); if(verifyDiskSpace(fProgram, srDest)) { setPackageFolder(fProgram); err = addDirectory("", "6.0.0.2000110801", "bin", // dir name in jar to extract fProgram, // Where to put this file // (Returned from GetFolder) "", // subdir name to create relative to fProgram true); // Force Flag logComment("addDirectory() returned: " + err); // check return value if(err == SUCCESS) { err = performInstall(); logComment("performInstall() returned: " + err); } else cancelInstall(err); } else cancelInstall(INSUFFICIENT_DISK_SPACE); // end main ...
execute - Archive of obsolete content
ecute method on the File object instead. File.execute() executes an installed file (such as a browser) after it has been installed, and is typically placed at the end of an install script and outside of the main install block. The Install object's execute method, on the other hand, deletes the executable from its temporary location once it has finished. The optional blocking argument, when set to true, specifies that the installation should wait for this executable to finish before processing the next queued install command. If you do not set this flag and launch an executable that is not a part of the installation, you will raise an error when you restart the browser. Passing Arguments to the Executable The args parameter, when present, passes a string to the executable as command-line param...
...u do not set this flag and launch an executable that is not a part of the installation, you will raise an error when you restart the browser. Passing Arguments to the Executable The args parameter, when present, passes a string to the executable as command-line parameters. The following line, for example, passes the "-c" command-line parameter to the executable: err = file.execute(myfile, "-c", true); When you want to pass more than one parameter to the executable itself, however, you must format the args string in a particular way so that the parameters can be broken up and passed separately as required. In general, you should use single quotes for the args string and double quotes to delimit the command-line arguments within args. The following parsing rules apply: Double quotes are t...
... args string itself are stripped off when the string is passed to the executable. Quotes that are escaped, or "backslashed," are passed through the executable intact. All other backslashed cases are ignored. This means that in order to pass three command-line arguments (-c, -d, and -s) to the executable, you should format the args string as follows: err = file.execute(myfile, '"-c""-d""-s"', true); //Technically, given the rules above, you could also pass the same //arguments with the following line, but the result is much less //readable: err = file.execute(myfile, "\"-c\"\"-d\"\"-s\"", true); Also see the note about binaries on the Macintosh platform in addFile. ...
allowevents - Archive of obsolete content
<< XUL Reference home allowevents Type: boolean If true, events are passed to children of the element. Otherwise, events are passed to the element only. On listitem and titlebar elements, mouse events normally do not get sent to their children; instead they are retargeted to the listitem and titlebar element itself. This means that elements placed inside a listitem do not respond to events, and instead clicking the mouse simply selects that item within the list. By setting the allowevents attribute to true, this special behavior is disabled, and the events are targeted the same as other elements. For menu, menuseparator, menuitem and treecol elements, as well as menu buttons, and the popup datepicker, mouse events are also retargeted to the element itself. However, the ...
...ing the allowevents attribute to true, this special behavior is disabled, and the events are targeted the same as other elements. For menu, menuseparator, menuitem and treecol elements, as well as menu buttons, and the popup datepicker, mouse events are also retargeted to the element itself. However, the allowevents attribute is handled in a different way. Instead, the allowevents may be set to true on a descendant instead. This does the same thing in that it allows events to be targeted normally, but allows this to be different for each descendant. This behavior is used for menus, for instance, to allow a menu button to behave as a menu when clicking on it, yet have part of the menu behave as a button. ...
... the allowevents may be set to true on a descendant instead. This does the same thing in that it allows events to be targeted normally, but allows this to be different for each descendant. This behavior is used for menus, for instance, to allow a menu button to behave as a menu when clicking on it, yet have part of the menu behave as a button. For the latter, the allowevents attribute is set to true to have a click on the child button receive events instead of targeting all events at the menu. ...
reserved - Archive of obsolete content
<< XUL Reference home reserved Type: string This attribute applies to a command element. Setting this attribute to "true" indicates that the command is reserved for Chrome code and is not available for use in the content. This means that, to execute these commands, key events won't be passed to content, and event listeners registered for them in content will not be executed. Currently, the content still receives these key events, even though it can't override them. In future releases, it won't receive them. See bug 1173061 for details. ...
...sed to content, and event listeners registered for them in content will not be executed. Currently, the content still receives these key events, even though it can't override them. In future releases, it won't receive them. See bug 1173061 for details. ...
...leases, it won't receive them. See bug 1173061 for details. ...
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
57 close XUL Attributes, XUL Reference No summary! 58 closebutton XUL Attributes, XUL Reference No summary! 59 closemenu XUL Attributes, XUL Reference No summary! 60 coalesceduplicatearcs XUL Attributes, XUL Reference No summary! 61 collapse ...
...summary! 1088 action NeedsExample, XUL Elements, XUL Reference Used to specify the content that should be generated for each matching result from a query. The action should be contained within a query or rule element. 1089 appendChild Node appendChild ( Node newChild ) 1090 arrowscrollbox XUL Elements, XUL Reference clicktoscroll, if true, the arrows must be clicked to scroll the scrollbox content. 1091 assign XUL Elements, XUL Reference For XML templates, specifies an additional variable to assign a value to. 1092 attribute.align The align attribute specifies how child elements of the box are aligned, when the size of the box is larger than the total size of the children. For boxes that ...
...nd object attributes may be variables. 1214 vbox XUL Elements, XUL Reference A container element which can contain any number of child elements. This is equivalent to the box element, except it defaults to vertical orientation. 1215 where XUL Elements, XUL Reference Indicate a condition that must match for a template result to be used. If the condition is true, the corresponding action body is generated; otherwise the result is ignored and no content is generated. 1216 window XUL Elements, XUL Reference Describes the structure of a top-level window. It is the root node of a XUL document. It is by default a horizontally oriented box. As it is a box, all box attributes can be used. By default, the window will have a platform-specific...
appendNotification - Archive of obsolete content
ng properties: accessKey - the accesskey to appear on the button callback - function to be called when the button is activated. This function is passed three arguments: the <notification> the button is associated with the button description as passed to appendNotification. the element which was the target of the button press event. If the return value from this function is not True, then the notification is closed. The notification is also not closed if an error is thrown. label - the label to appear on the button popup - the id of a popup for the button. If null, the button is not a button popup (e.g. a menu). The type property must also be set to "menu", or "menu-button". isDefault - if True, this is the default button. There can be only one default button. If no ...
... .getMostRecentWindow("navigator:browser"); } if (typeof gBrowser === "undefined") { //If there is no gBrowser defined, get it var gBrowser = window.gBrowser; } function testNotificationButton1Callback(theNotification, buttonInfo, eventTarget) { window.alert("Button 1 pressed"); //Prevent notification from closing: return true; }; function testNotificationButton2Callback(theNotification, buttonInfo, eventTarget) { window.alert("Button 2 pressed"); //Do not prevent notification from closing: }; function testNotificationCallback(reason) { window.alert("Reason is: " + reason); }; let notifyBox = gBrowser.getNotificationBox(); let buttons = []; let button1 = { ...
...); }; 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". popup: null }; buttons.push(button1); let button2 = { isDefault: true, accessKey: "2", label: "Button 2", callback: testNotificationButton2Callback, type: "", // If a popup, then must be: "menu-button" or "menu". popup: null }; buttons.push(button2); //appendNotification( label , value , image (URL) , priority , buttons, eventCallback ) notifyBox.appendNotification("My Notification text", "Test notification ...
ContextMenus - Archive of obsolete content
that the target of the contextmenu event is what is desired. To cancel a context menu event, you can use the preventDefault method of the event object. function checkContextMenu(event) { if (event.target.localName == "textbox") event.preventDefault(); } function init() { var container = document.getElementById("container"); container.addEventListener("contextmenu", checkContextMenu, true); } The 'checkContextMenu' function checks to see if the textbox was the target of the context menu and, if so, cancels the event using the preventDefault method. This has the effect of disabling the context menu. The event listener is attached using the addEventListener method within the 'init' function. This might be called while initializing a window during a load event for example. Attachi...
...ypically, this will cause the menuitem's label to appear in the context menu in bold. What constitutes the default item isn't specified, but is usually the operation carried out when the item was left-clicked or pressed normally, as opposed to context clicked. You can indicate this item, if it applies, using the default attribute. <menupopup id="link-menu"> <menuitem label="Open Link" default="true"/> <menuitem label="Open In New Window"/> <menuitem label="Properties"/> </menupopup> The default attribute has been set to true on the first menu item ('Open Link'). On platforms that support it, it will be marked as a default item. On other platforms, the attribute will just be ignored and the menuitem will be displayed normally. Naturally, it only makes sense to have one default item per...
...nu. Typically, this will vary based on what the context is. For example, right clicking on an image might display items pertaining to images, whereas clicking on a link would display items pertaining to links. In many cases, it may be easier to use a single context menu containing every possible item, and show and hide the necessary items when needed. To hide an item, set its hidden property to true. To show an item, set its hidden property to false. <script> function showHideDeleteItem() { var deleteItem = document.getElementById("delete"); var rows = document.getElementById("rows"); deleteItem.hidden = (rows.childNodes.length == 0); } </script> <menupopup id="inssel-menu" onpopupshowing="showHideDeleteItem()"> <menuitem label="Insert"/> <menuitem id="delete" label="Delete"/> <...
Template and Tree Listeners - Archive of obsolete content
onto a folder type of row. In other situations, you may wish to allow items to be dragged between (before or after) rows. This would be the situation if you were dragging items from that tree around, for instance dragging a bookmark from one location to another. The tree widget will draw a small line between the rows while dragging. ...
...to another. The tree widget will draw a small line between the rows while dragging. All you need to do is add a tree builder observer which returns true for the canDrop method. Note that the 'drag on' case only allows dragging onto containers, not ordinary rows. ...
... { return !orient; }, onDrop : function(idx, orient) { // do something here }, }; //tree.builderView.addObserver(treeBuilderObserver); // ppchenhui@hotmail.com tree.builder.QueryInterface (Components.interfaces.nsIXULTreeBuilder) .addObserver(treeBuilderObserver); The canDropBeforeAfter method returns false since we do not want to allow before and after drops. The canDropOn method returns true however. The canDrop method is there for compatibility with older versions; this function checks the orientation and returns the opposite. This works as the 'on' value is 0 and the 'between' values are -1 and 1. Obviously, this code is much simpler than what we would really want to use -- we should be checking what is being dragged to make sure that it is compatible with the tree. Or, we might wa...
Adding Buttons - Archive of obsolete content
ed with it, a label and an image. You need one or the other or both. Thus, a button can have a label only, an image only or both a label and an image. Buttons are commonly used for the OK and Cancel buttons in a dialog, for example. Syntax of buttons The button tag has the following syntax: <button id="identifier" class="dialog" label="OK" image="images/image.jpg" disabled="true" accesskey="t"/> The attributes are as follows, all of which are optional: id A unique identifier so that you can identify the button with. You'll see this attribute on all elements. You'll want to use this if you want to refer to the button in a style sheet or script. However, you should add this attribute to almost all elements. It isn't always placed on elements in this tutorial for...
...n most cases, you will not use a class for a button. label The label that will appear on the button. For example, OK or Cancel. If this is left out, no text appears. image The URL of the image to appear on the button. If this is attribute is left out, no image appears. You can also specify the image in a stylesheet using the list-style-image property. disabled If this attribute is set to true, the button is disabled. This is usually drawn with the text in grey. If the button is disabled, the function of the button cannot be performed. If this attribute is left out entirely, the button is enabled. You can switch the disabled state of the button using JavaScript. accesskey This should be set to a letter that is used as a shortcut key. This letter should appear in the label text and w...
...nd will typically be drawn underlined. When the user presses ALT (or a similar key that varies on each platform) and the access key, the button will be focused from anywhere in the window. Note: Buttons support more attributes than those listed above. Others will be discussed later. Some examples of buttons Example 1 : Source View <button label="Normal"/> <button label="Disabled" disabled="true"/> The examples above will generate the buttons in the image. The first button is a normal button. The second button is disabled so it appears greyed out. We'll start by creating a simple Find button for the find files utility. The example code below shows how to do this. <button id="find-button" label="Find"/> Note: Firefox does not allow you to open chrome windows from web pages, so the V...
Adding Event Handlers - Archive of obsolete content
ms.js"/> This tutorial does not attempt to describe how to use JavaScript (except as related to event handling) as this is a fairly large topic and there are plenty of other resources that are available for this. By default the JavaScript console only shows errors from web content. To show errors in chrome JavaScript, it is necessary to change the preference javascript.options.showInConsole to true. You can also change the preference javascript.options.strict for debugging. By setting this value to true, non-standard, poorly written, or syntax prone to cause logic errors are logged to the JavaScript console. Responding to Events The script will contain code which responds to various events triggered by the user or other situations. There are about thirty or so different events that may be...
...ent's addEventListener method. This allows you to attach an event listener dynamically and listen for events during the capturing phase. ...
...You can also listen during the bubbling phase by setting the last argument to false. The event listener function passed as the second argument should take one argument, the event object, as shown in the declaration for the buttonPressed function above. ...
Adding Methods to XBL-defined Elements - Archive of obsolete content
Nodes(). The next example can be used to create text with a label. The method 'showTitle' can be used to show or hide the label. It works by getting a reference to the title element using the anonymous array and changing the visibility of it. ...
... getBindingParent method is useful for a node that is nested several levels deep. ...
...ding will be removed, after its destructor is called. Then, the new binding will be added in its place and its constructor invoked. The script for a constructor or destructor should be placed directly inside the appropriate tag. There should only be at most one of each per binding and they take no arguments. Here are some examples: <constructor> if (this.childNodes[0].getAttribute("open") == "true"){ this.loadChildren(); } </constructor> <destructor action="saveMyself(this);"/> The next section shows how to add event handlers to XBL-defined elements. << PreviousNext >> ...
Box Objects - Archive of obsolete content
as in the following example. ...
...You will then have to unhide and uncollapse the label for it to appear again. XUL Element ...
...ll displayed but have no size. For example, the next box sibling of button 1 is this next example will be button 3, because button 2 is hidden. But the next box sibling of button 3 will be button 4 because it is only collapsed. Example 3 : Source View <hbox> <button label="Button 1" oncommand="alert('Next is: ' + this.boxObject.nextSibling.label);"/> <button label="Button 2" hidden="true"/> <button label="Button 3" oncommand="alert('Next is: ' + this.boxObject.nextSibling.label);"/> <button label="Button 4" collapsed="true"/> </hbox> Box Ordering Attributes When a XUL box is laid out on a window, the elements are ordered according to a number of properties, for instance the orientation, their ordinal group and their direction. orient attribute The orientation is co...
Localization - Archive of obsolete content
onload="initSearchList()" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="findfile.js"/> <popupset> <menupopup id="editpopup"> <menuitem label="&cutCmd.label;" accesskey="&cutCmd.accesskey;"/> <menuitem label="&copyCmd.label;" accesskey="&copyCmd.accesskey;"/> <menuitem label="&pasteCmd.label;" accesskey="&pasteCmd.accesskey;" disabled="true"/> </menupopup> </popupset> <keyset> <key id="cut_cmd" modifiers="accel" key="&cutCmd.commandkey;"/> <key id="copy_cmd" modifiers="accel" key="&copyCmd.commandkey;"/> <key id="paste_cmd" modifiers="accel" key="&pasteCmd.commandkey;"/> <key id="close_cmd" keycode="VK_ESCAPE" oncommand="window.close();"/> </keyset> <vbox flex="1"> <toolbox> <menubar id="findfiles-menubar"> ...
...esskey="&editMenu.accesskey;"> <menupopup id="edit-popup"> <menuitem label="&cutCmd.label;" accesskey="&cutCmd.accesskey;" key="cut_cmd"/> <menuitem label="&copyCmd.label;" accesskey="&copyCmd.accesskey;" key="copy_cmd"/> <menuitem label="&pasteCmd.label;" accesskey="&pasteCmd.accesskey;" key="paste_cmd" disabled="true"/> </menupopup> </menu> </menubar> <toolbar id="findfiles-toolbar"> <toolbarbutton id="opensearch" label="&openCmdToolbar.label;"/> <toolbarbutton id="savesearch" label="&saveCmdToolbar.label;"/> </toolbar> </toolbox> <tabbox> <tabs> <tab label="&searchTab;" selected="true"/> <tab label="&optionsTab;"/> </tabs> <tabpanels> <tabpanel id="searchpanel" ...
...tem label="&type.size;"/> <menuitem label="&type.date;"/> </menupopup> </menulist> <spacer class="springspace"/> <menulist id="searchmode"> <menupopup> <menuitem label="&mode.is;"/> <menuitem label="&mode.isnot;"/> </menupopup> </menulist> <spacer class="springspace"/> <menulist id="find-text" flex="1" editable="true" datasources="file:///mozilla/recents.rdf" ref="http://www.xulplanet.com/rdf/recent/all"> <template> <menupopup> <menuitem label="rdf:http://www.xulplanet.com/rdf/recent#Label" uri="rdf:*"/> </menupopup> </template> </menulist> </groupbox> </tabpanel> <tabpanel id="optionspanel" orient="vertical"> <checkbox id="casecheck...
arrowscrollbox - Archive of obsolete content
If false, the mouse must be hovered over the arrows to scroll automatically. disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it ca...
... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
... an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. smoothscroll Type: boolean true initially enables smooth scrolling for the corresponding arrowscrollbox, false disables it. Currently, smooth scrolling supports horizontal arrowscrollboxes only. tabindex Type: integer The tab order of the element. The tab order is the order in which the focus is moved when the user presses the "tab" key. Elements with a higher tabindex are later in the tab sequence. Properties ...
button - Archive of obsolete content
p, image, label, open, orient, tabIndex, type Examples <button label="Press Me" oncommand="alert('You pressed me!');"/> Attributes accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. autocheck Type: boolean If this attribute is true or left out, the checked state of the button will be switched each time the button is pressed. If this attribute is false, the checked state must be adjusted manually. When autocheck is true, the button type should be "checkbox" or "radio". checkState Type: integer, values 0, 1, or 2 This attribute may be used to create three state buttons, numbered 0, 1 and 2. When in state 0 or 1, pres...
... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...n of the image is determined by the dir and orient attributes. label Type: string The label that will appear on the element. If this is left out, no text appears. For an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. open Type: boolean For the menu type buttons, the open attribute is set to true when the menu is open. The open attribute is not present if the menu is closed. orient Type: one of the values below Used to specify whether the children of the element are oriented horizontally or vertically. The default value depends on the element. You can also use the -moz-box-orient style property. horizontal Child elements of the element are placed next to each other in a row...
datepicker - Archive of obsolete content
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...ormally preferred to use of the attribute, as it may need to update additional state. firstdayofweek Type: integer which day of the week to display as the first day in the grid. The values range from 0 to 6, where 0 is Sunday and 6 is Saturday. The default value is determined by the locale, so only use this attribute if you want to override it. readonly Type: boolean If set to true, then the user cannot change the value of the element. However, the value may still be modified by a script. tabindex Type: integer The tab order of the element. The tab order is the order in which the focus is moved when the user presses the "tab" key. Elements with a higher tabindex are later in the tab sequence. type Type: one of the values below You can set ...
...: boolean A read only value indicating whether a leading zero should be displayed before the month when it is less than 10. open Type: boolean For popup type datepickers, specifies whether the popup is open. Set this property to open or close the popup. For non-popup datepickers, this property is always false. readOnly Type: boolean If set to true, then the user cannot modify the value of the element. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string The currently selected date in the form YYYY-MM-DD. Unlike the month property, months in this value range from 01 to 12. Set this property to change the selected date. year Type: integer...
menuseparator - Archive of obsolete content
nvoke the command. If this value is set, it overrides an assigned key set in the key attribute. This attribute does not apply to menus directly on the menubar. accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. allowevents Type: boolean If true, events are passed to children of the element. Otherwise, events are passed to the element only. command Type: id Set to the id of a command element that is being observed by the element. crop Type: one of the values below If the label of the element is too big to fit in its given space, the text will be cropped on the side specified by the crop attribute.
... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...ment associated with the control. This is set when a label has a control attribute pointing to this element. This property will be null when no label is associated with the control. parentContainer Type: menu element Read only property that returns the containing menu element, or null if there isn't a containing menu. selected Type: boolean This property's value is true if this element is selected, or false if it is not. This property is read only. This property is available for menuitem and menuseparator elements in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the conte...
toolbarbutton - Archive of obsolete content
="Radio 2" type="radio" group="RadioGroup"/> <toolbarbutton accesskey="3" label="Radio 3" type="radio" group="RadioGroup"/> </toolbar> Attributes accesskey Type: character This should be set to a character that is used as a shortcut key. This should be one of the characters that appears in the label attribute for the element. autocheck Type: boolean If this attribute is true or left out, the checked state of the button will be switched each time the button is pressed. If this attribute is false, the checked state must be adjusted manually. When autocheck is true, the button type should be "checkbox" or "radio". checkState Type: integer, values 0, 1, or 2 This attribute may be used to create three state buttons, numbered 0, 1 and 2. When in state 0 or 1, press...
... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...em element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. oncommand Type: script code This event handler is called when the command is activated. This occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. open Type: boolean For the menu type buttons, the open attribute is set to true when the menu is open. The open attribute is not present if the menu is closed. orient Type: one of the values below Used to specify whether the children of the element are oriented horizontally or vertically. The default value depends on the element. You can also use the -moz-box-orient style property. horizontal Child elements of the element are placed next to each other in a row ...
Getting started with XULRunner - Archive of obsolete content
ou need to change XULRunner itself or integrate it with external binaries you may need to read that article. Step 1: Download XULRunner You can find a download link on the main XULRunner page here on MDN. Since we are not creating any binary XPCOM components, we only need to download and install the XULRunner runtime package, not the SDK. The XULRunner download for Windows is a zip file, not a true install. As a developer, I like the idea that XULRunner only needs to be unzipped onto my machine. I am assuming that it doesn't need to hook into my Windows system and that's a good thing. It also means that the XULRunner is portable so, if you develop your applications to be portable you could carry them around on a flash drive or sync them in the cloud. The Mac version of XULRunner is distrib...
...e root. Here is the application root chrome.manifest: manifest chrome/chrome.manifest Step 6: Set up preferences The prefs.js file tells XULRunner the name of the XUL file to use as the main window. Here is mine: pref("toolkit.defaultChromeURI", "chrome://myapp/content/main.xul"); /* debugging prefs, disable these before you deploy your application! */ pref("browser.dom.window.dump.enabled", true); pref("javascript.options.showInConsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); XULRunner specific preferences include: toolkit.defaultChromeURI Specifies the default window to open when the application is launched. toolkit.defaultChromeFeatures Specifies the features passed to wi...
...XUL is simple to use and quite powerful and can even be used on mobile devices.</description> </window> Note: Make sure there is no extra whitespace at the beginning of the XML/XUL file The application also has a JavaScript file. Most XUL applications will include some external JavaScript, so the sample application does too, just to show how to include...
ant script to assemble an extension - Archive of obsolete content
/*.tpl.*"/> <exclude name="blogmark.jar"/> </fileset> </jar> </target> <target name="templates" description="Generate files from templates."> <copy file="chrome/content/blogmark/contents.rdf.tpl.xml" tofile="chrome/content/blogmark/contents.rdf" overwrite="true"> <filterchain> <replacetokens> <token key="VERSION" value="${VERSION}"/> <token key="DESCRIPTION" value="${DESCRIPTION}"/> </replacetokens> </filterchain> </copy> <copy file="chrome/...
...="VERSION" value="${VERSION}"/> <token key="DESCRIPTION" value="${DESCRIPTION}"/> </replacetokens> </filterchain> </copy> <copy file="chrome/content/blogmark/about.xul.tpl.xml" tofile="chrome/content/blogmark/about.xul" overwrite="true"> <filterchain> <replacetokens> <token key="VERSION" value="${VERSION}"/> </replacetokens> </filterchain> </copy> <copy file="install.rdf.tpl.xml" tofile="install.rdf" overwrit...
... <filterchain> <replacetokens> <token key="VERSION" value="${VERSION}"/> </replacetokens> </filterchain> </copy> <copy file="install.rdf.tpl.xml" tofile="install.rdf" overwrite="true"> <filterchain> <replacetokens> <token key="VERSION" value="${VERSION}"/> <token key="DESCRIPTION" value="${DESCRIPTION}"/> </replacetokens> </filterchain> </copy> </target> </project> ...
NPEvent - Archive of obsolete content
pends upon event type. EventRecord NPEvent on Mac OS NPEvent is defined as an EventRecord data structure, which has the following fields: what Integer representing an event type. Both windowed and windowless plug-ins receive the same events. 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. message LongInt. Additional information about the event. Type of information depends on the event type. Undefined for null, mouseUp, and mouseDown events. when LongInt. Ticks since start-up. where Point. Cursor location. modifiers Integer. Flags. XEvent NPE...
...s: Sent to all instances in all windows. In addition to these standard types, the browser provides three additional event types that can be passed in the what field of the EventRecord: getFocusEvent: Sent when the instance could become the focus of subsequent key events, when the user clicks the instance or presses the tab key to focus the instance. If your instance accepts key events, return true, and key events will be sent to the instance until it receives a loseFocusEvent. If your plug-in ignores key events, return false, and the key events will be processed by the browser itself. loseFocusEvent: Sent when the instance has lost the text focus, as a result of the user clicking elsewhere on the page or pressing the Tab key to move the focus. No key events are sent to the instance until...
...hen the instance has lost the text focus, as a result of the user clicking elsewhere on the page or pressing the Tab key to move the focus. No key events are sent to the instance until the next getFocusEvent. adjustCursorEvent: Sent when the mouse enters or leaves the bounds of the instance. If your plug-in wants to set the cursor when the mouse is within the instance, set the cursor and return true. If you don't want a special cursor, return false and the browser will use the standard arrow cursor. XWindows Description The NPEvent object represents an event passed by NPP_HandleEvent() to a windowless plug-in. The NPEvent structure is defined as XEvent, the definition of the event type used by the XWindows platform. For information about the XEvent structure and XWindows events, see the XW...
NPFullPrint - Archive of obsolete content
<< Gecko Plugin API Reference << Plug-in Side Plug-in API Summary Substructure of NPPrint that contains platform-specific information used during full-page mode printing. Syntax typedef struct _NPFullPrint { NPBool pluginPrinted; /* true: print fullscreen */ NPBool printOne; /* true: print one copy */ /* to default printer */ void* platformPrint; /* Platform-specific */ } NPFullPrint; Fields The data structure has the following fields: pluginPrinted Determines whether the plug-in prints in full-page mode. Values: true: Plug-in takes complete control of the printing process and prints full-page. false: (Default) Plug-in renders its area of the page only (for embedded plug-in). printOne Not currently in use. Should always be fal...
... false: Display print dialogs so user can choose printer, other options. platformPrint Platform-specific printing information. ...
... a pointer to an NPPrint object (previously allocated by the browser). The NPFullPrint structure is used when the mode field of NPPrint is set to NP_Full. The pluginPrinted field of this structure determines whether the plug-in prints in full-page mode or not. If you want the plug-in to take complete control of the printing process, it should print the full page and set the field pluginPrinted to true before returning. If you want an embedded plug-in to simply render its area of the page, set pluginPrinted to false and return immediately; the browser calls NPP_Print again with the NPEmbedPrint substructure of NPPrint. See Also NPP_Print, NPPrint, NPEmbedPrint ...
NPVariant - Archive of obsolete content
NPVARIANT_IS_STRING() Evaluates to tru...
... NPN_IdentifierIsString() NPN_UTF8FromIdentifier() NPN_IntFromIdentifier() Macros Plugin developers are not expected to directly manipulate or access the members of the NPVariant instance, instead, the function NPN_ReleaseVariantValue(), and the following macros are provided: NPVARIANT_IS_VOID() Evaluates to true if v is of type NPVariantType_Void. NPVARIANT_IS_NULL() Evaluates to true if v is of type NPVariantType_Null. NPVARIANT_IS_BOOLEAN() Evaluates to true if v is of type NPVariantType_Bool. NPVARIANT_IS_INT32() Evaluates to true if v is of type NPVariantType_Int32. NPVARIANT_IS_DOUBLE() Evaluates to true if v is of type NPVariantType_Double. NPVARIANT_IS_STRING() Evaluates to true if v is of type NPVariantType_String. NPVARIANT_IS_OBJECT() Evaluates to...
... NPVARIANT_TO_BOOLEAN() Extracts the boolean value from v. NPVARIANT_TO_INT32() Extracts a signed 32-bit integer value from v. NPVARIANT_TO_DOUBLE() Extracts a double precision floating point value from v. NPVARIANT_TO_STRING() Extracts the NPString value from v. ...
Common Firefox theme issues and solutions - Archive of obsolete content
ro Glass support Firefox doesn't always go to full screen mode from a normal window properly. The resolution to this issue is to add the following code to your browser.css file somewhere below where the main-window is made transparent to support Aero glass. @media all and (-moz-windows-compositor) { /* Make transition to Fullscreen mode seamlessly in Firefox 10+ */ #main-window[inFullscreen="true"] { -moz-appearance: none; background-color: -moz-dialog!important; } } For more information about this issue please see bug 732757 and bug 732757 and this MozillaZine thread. Mac OS X OS X Lion missing toolbar button icons Due to Firefox bug 679708 and bug 702558, some toolbar buttons icons may be missing on Firefox 8 and later running on Mac OS X Lion. In order to work around this...
...tity-box-inner > #page-proxy-stack > #page-proxy-favicon { list-style-image: url(chrome://browser/skin/identity-icons-https-ev.png); } #identity-box:hover > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon { -moz-image-region: rect(0, 32px, 16px, 16px); } #identity-box:hover:active > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon, #identity-box[open=true] > #identity-box-inner > #page-proxy-stack > #page-proxy-favicon { -moz-image-region: rect(0, 48px, 16px, 32px); } #page-proxy-favicon[pageproxystate="invalid"] { opacity: 0.5; } For more information about identity boxes please see the identity box section of the AMO editors theme review guidelines No visual clue for disabled url bars There needs to be a visual clue when URL ba...
...e HTML5 video control bar. To test this go to Mozilla's Mission page. Warning: If you copy over the Firefox 11 or newer style rules and graphics from the media folder in omni.ja you need to make the following changes in videocontrols.css or the pause and mute buttons will break in Firefox 10. Change the style rules: .playButton[paused] {...} .muteButton[muted] {...} To: .playButton[paused="true"] {...} .muteButton[muted="true"] {...} Error console warnings Unknown namespace for videocontrols.css The error console is reporting the following issue: Warning: Unknown namespace prefix 'html'. Ruleset ignored due to bad selector. Source file: chrome://global/skin/media/videocontrols.css The solution to this issue is to add the following name space to the second line of the file right a...
Sharp variables in JavaScript - Archive of obsolete content
s. var a = { foo:[], bar:undefined }; a.bar = a.foo; a.foo.push("Hello"); a.bar.push("there!"); alert(a.foo[1]); // "there!" Cyclic references Sharp variables can be used to create a circularly linked list in one line of code. ...
... // 1 a.next.val; // 2 a.next.next.val; // 1 a.next.next == a; // true Again, you can eliminate the need for sharp variables by using two lines instead of one for the declaration. ...
...val; // 1 a.next.next == a; // true Multiple sharp variables var a = #1 = { val:#2=[], next:{val:[], next:{val:#02#, next:#1#}} }; // Leading 0s don't matter a.val.push(1); a.next.val.push(2); a.val[0]; // 1 a.next.val[0]; // 2 a.next.next.val[0]; // 1 a.next.next.next.val[0]; // 1 a == a.next.next; // false a == a.next.next.next; // true ...
XForms Custom Controls Examples - Archive of obsolete content
g id="output-image" extends="chrome://xforms/content/xforms.xml#xformswidget-base"> <content> <html:div> <html:img anonid="content"/> </html:div> </content> <implementation implements="nsIXFormsUIWidget"> <method name="refresh"> <body> var img = document.getAnonymousElementByAttribute(this, "anonid", "content"); img.setAttribute("src", this.stringValue); return true; </body> </method> </implementation> </binding> Output Showing XHTML <binding id="output-xhtml" extends="chrome://xforms/content/xforms-xhtml.xml#xformswidget-output"> <content> <children includes="label"/> <xhtml:div class="xf-value" anonid="content"></xhtml:div> <children/> </content> <implementation implements="nsIXFormsUIWidget"> <field name="_domparse...
...g> Output Showing XHTML <binding id="output-xhtml" extends="chrome://xforms/content/xforms-xhtml.xml#xformswidget-output"> <content> <children includes="label"/> <xhtml:div class="xf-value" anonid="content"></xhtml:div> <children/> </content> <implementation implements="nsIXFormsUIWidget"> <field name="_domparser">null</field> <property name="domparser" readonly="true"> <getter> if (!this._domparser) this._domparser = new DOMParser(); return this._domparser; </getter> </property> <method name="refresh"> <body> // Get new value, parse, and import it. var val = this.stringValue; var newdom = this.domparser.parseFromString(val, "text/xml"); var impnode = document.importNode(newdom.firstChild, true); // Get content node, clean i...
... it. ...
Desktop mouse and keyboard controls - Game development
accordingly in both handler functions. Inside them we can get the code of the key that was pressed from the keyCode property of the event object, see which key it is, and then set the proper variable. There are no helpers so you have to remember what the given codes are (or look them up); 37 is the left arrow: function keyDownHandler(event) { if(event.keyCode == 39) { rightPressed = true; } else if(event.keyCode == 37) { leftPressed = true; } if(event.keyCode == 40) { downPressed = true; } else if(event.keyCode == 38) { upPressed = true; } } The keyUpHandler looks almost exactly the same as the keyDownHandler above, but instead of setting the pressed variables to true, we would set them to false. If the left arrow is pressed (?; key ...
... 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. ...
...d from within the requestAnimationFrame. We could write our own KeyCode object containing the key codes, for example: var KeyboardHelper = { left: 37, up: 38, right: 39, down: 40 }; That way instead of using the codes to compare the input in the handler functions we could do something like this, which is arguably easier to remember: if(event.keyCode == KeyboardHelper.left) { leftPressed = true; } Note: You can also find a list if the different keycodes and what keys they relate to in the keyCode reference page. You can see this example in action online at end3r.github.io/JavaScript-Game-Controls and the full source code can be found at github.com/end3r/JavaScript-Game-Controls. Phaser approach As I mentioned before you can write everything on your own, but you can also take the...
Graceful asynchronous programming with Promises - Learn web development
en devices enabled, and directly returning the MediaStream for the stream created from the selected sources, getUserMedia() returns a promise which is resolved with the MediaStream once it's available. ...
...abled, and directly returning the MediaStream for the stream created from the selected sources, getUserMedia() returns a promise which is resolved with the MediaStream once it's available. ...
...esponse.blob(); } Unfortunately, we need to do slightly more than this. Fetch promises do not fail on 404 or 500 errors -- only on something catasrophic like a network failure. 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. This can be done like so -- add the following lines below your first line of JavaScript. let promise2 = promise.then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { return response.blob(); } }); Each call to .then() creates a new promise. This is very useful; because the blob() method also returns a promise, we can hand...
Test your skills: Conditionals - Learn web development
ns the string "winter", and again assigns an appropriate string to response. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. 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. This score is fed into the answer machine, which provides a response to indicate how well you did. response -- begins uninitialized, but is later used to store a reponse that will be printed to the output panel. You need to create an if...else structure that checks whether the machine is switched on and puts a message into the response...
...hings, but it's a pretty bad score. Needs improvement." Score of 40 to 69 -- "You did a passable job, not bad!" Score of 70 to 89 -- "That\'s a great score, you really know your stuff." Score of 90 to 100 -- "What an amazing score! Did you cheat? Are you for real?" Try updating the live code below to recreate the finished example. After you've entered your code, try changing machineActive to true, to see if it works. Download the starting point for this task to work in your own editor or in an online editor. Conditionals 3 In this task you need to take the code you wrote for the second task, and rewrite the inner if...else if...else to use a switch statement instead. Try updating the live code below to recreate the finished example: Download the starting point for this task to...
... rewrite the inner if...else if...else to use a switch statement instead. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. 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). pwd -- Contains the user's login password. machineResult -- begins uninitialized, but is later used to store a reponse that will be printed to the output panel, letting the user know whether the machine is switched on. pwdResult -- begins uninitialized, but is later used to store a reponse that will be printed to the output panel, letting the user know whether their login attempt was s...
Adding features to our bouncing balls demo - Learn web development
structor and add a new Ball() constructor: The Shape() constructor should define the x, y, velX, and velY properties in the same way as the Ball() constructor did originally, but not the color and size properties. It should also define a new property called exists, which is used to track whether the balls exist in the program (have not been eaten by the evil circle). This should be a boolean (true/false). The Ball() constructor should inherit the x, y, velX, velY, and exists properties from the Shape() constructor. It should also define a color and a size property, like the original Ball() constructor did. Remember to set the Ball() constructor's prototype and constructor appropriately. The ball draw(), update(), and collisionDetect() method definitions should be able to stay exactly ...
...l() constructor did. Remember to set the Ball() constructor's prototype and constructor appropriately. The ball draw(), update(), and collisionDetect() method definitions should be able to stay exactly the same as they were before. You also need to add a new parameter to the new Ball() ( ... ) constructor call -- the exists parameter should be the 5th parameter, and should be given a value of true. At this point, try reloading the code -- it should work just the same as it did before, with our redesigned objects. Defining EvilCircle() Now it's time to meet the bad guy -- the EvilCircle()! Our game is only going to involve one evil circle, but we are still going to define it using a constructor that inherits from Shape() to give you some practice. You might want to add another circle to ...
...he edge of the screen, and stop it from doing so. Again, you can mostly just copy the Ball.prototype.update definition, but there are a few changes you should make: Get rid of the last two lines -- we don't want to automatically update the evil circle's position on every frame, because we will be moving it in some other way, as you'll see below. Inside the if() statements, if the tests return true we don't want to update velX/velY; we want to instead change the value of x/y so the evil circle is bounced back onto the screen slightly. Adding or subtracting (as appropriate) the evil circle's size property would make sense. setControls() This method will add an onkeydown event listener to the window object so that when certain keyboard keys are pressed, we can move the evil circle around. ...
Starting our Svelte Todo list app - Learn web development
for="todo-0" class="label__lg"> What needs to be done? ...
... a checkbox to set the completed status, and two buttons to edit or delete the task. Finally there are two buttons to check/uncheck all task and to remove completed tasks. In subsequent articles we'll get all these features working, and more besides. Accessibility features of the todo list You may notice some unusual attributes here. For example: <button class="btn toggle-btn" aria-pressed="true"> <span class="visually-hidden">Show</span> <span>All</span> <span class="visually-hidden">tasks</span> </button> Here, aria-pressed tells assistive technology (like screen readers) that the button can be in one of two states: pressed or unpressed. Think of these as analogs for on and off. Setting a value of true means that the button is pressed by default. The class visually-hidden has n...
... body { font-size: 1.9rem; line-height: 1.31579; } } /*END RESETS*/ /* GLOBAL STYLES */ .form-group > input[type="text"] { display: inline-block; margin-top: 0.4rem; } .btn { padding: 0.8rem 1rem 0.7rem; border: 0.2rem solid #4d4d4d; cursor: pointer; text-transform: capitalize; } .btn.toggle-btn { border-width: 1px; border-color: #d3d3d3; } .btn.toggle-btn[aria-pressed="true"] { text-decoration: underline; border-color: #4d4d4d; } .btn__danger { color: #fff; background-color: #ca3c3c; border-color: #bd2130; } .btn__filter { border-color: lightgrey; } .btn__primary { color: #fff; background-color: #000; } .btn__primary:disabled { color: darkgrey; background-color:#565656; } .btn-group { display: flex; justify-content: space-between; } .btn-grou...
Dynamic behavior in Svelte: working with variables and props - Learn web development
a todos array. We'll also create two variables to keep track of the total number of tasks and the completed tasks. The state of our component will be represented by these three top-level variables. 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. Let's start by showing a status message. Find the <h2> heading with an id of list-h...
...ere!" message. This is because we are currently not passing any value into it from App.svelte, so it's using the default value. Now let's move our todos to App.svelte and pass them to the Todos.svelte component as a prop. 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. Try this now. <Todos {todos} /> ...
...heading is not being updated. Read on to find out why this is happening and how we can solve it. Reactive todos As we've already seen, every time the value of a component top-level variable is modified Svelte knows how to update the UI. In our app, the todos array value is updated directly every time a todo is toggled or deleted, and so Svelte will update the DOM automatically. The same is not true for totalTodos and completedTodos, however. In the following code they are assigned a value when the component is instantiated and the script is executed, but after that, their values are not modified: let totalTodos = todos.length let completedTodos = todos.filter(todo => todo.completed).length We could recalculate them after toggling and removing todos, but there's an easier way to do it. We...
Rendering a list of Vue components - Learn web development
ented by an object with a name and a done property. Add a few sample to-do items, along the lines of those seen below. This way you have some data available for rendering using v-for. export default { name: 'app', components: { ToDoItem }, data() { 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. Directives are applied to elements like other attributes. In case of v-for, you use a special syntax similar to a for...in loop in JavaScript -- v-for="item in items" -- where items is the arra...
...t> element contents should now look like this: import ToDoItem from './components/ToDoItem.vue'; import uniqueId from 'lodash.uniqueid' export default { name: 'app', components: { ToDoItem }, data() { return { ToDoItems: [ { id: uniqueId('todo-'), label: 'Learn Vue', done: false }, { id: uniqueId('todo-'), label: 'Create a Vue project with the CLI', done: true }, { id: uniqueId('todo-'), label: 'Have fun', done: true }, { id: uniqueId('todo-'), label: 'Create a to-do list', done: false } ] }; } }; Now, add the v-for directive and key attribute to the <li> element in your App.vue template, like so: <ul> <li v-for="item in ToDoItems" :key="item.id"> <to-do-item label="My ToDo Item" :done="true"></to-do-item> <...
...red, and make its type a String. To prevent name collisions, remove the id field from your data attribute. You are no longer using uniqueId, so you need to remove the import uniqueId from 'lodash.uniqueid'; line, otherwise your app will throw an error. The <script> contents in your ToDoItem component should now look something like this: export default { props: { label: {required: true, type: String}, done: {default: false, type: Boolean}, id: {required: true, type: String} }, data() { return { isDone : this.done, } }, } Now, over in your App.vue component, pass item.id as a prop to the ToDoItem component. Your App.vue template should now look like this: <template> <div id="app"> <h1>My To-Do List</h1> <ul> ...
Implementing feature detection - Learn web development
Note: If you have trouble getting this to work, check your code against our modernizr-css.html and modernizr-css.css files (see this running live also). JavaScript Modernizr is also equally well-prepared for implementing JavaScript feature detects too. ...
... Let's look at an example to show how you'd use those properties. First of all, make a local copy of the modernizr-js.html example file. Attach the Modernizr library to the HTML using a <script> element, as we have done in previous demos. ...
...If it is, we run some code tha...
Embedding API for Accessibility
s the appearance of the page to match the new prefs, without reloading the document over the network. ...
...e "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: Functionality Implementation Works as of Images SetIntPref("network.image.imageBehavior", behavior); /* behavior: 0=Accept, 1=Accep...
...ility.policy.popupsites.windowinternal.open","noAccess"); // Or turn it off everywhere: user_pref("capability.policy.default.windowinternal.open","noAccess"); // Override popping up new windows on target=anything user_pref("browser.block.target_new_window", true); // Override popup windows at beginning of new page load (blocks most popup advertisements) user_pref("dom.disable_open_during_load", true); Moz 0.8 Client side redirects SetBoolPref("browser.accept.redirects", acceptRedirects); No ...
Mozilla’s UAAG evaluation report
(P2) C When focus and/or selection changes they are in the viewport 5.5 Confirm form submission. (P2) P Only allows confirmation if the information is not secure? This ...
...es.windowinternal.open", "noAccess"); Or turn it off everywhere: user_pref("capability.policy.default.windowinternal.open", "noAccess"); Override popping up new windows on target=anything: user_pref("browser.target_new_blocked", true); Override popup windows at beginning of new page load (blocks most popup advertisements): user_pref("dom.disable_open_during_load", true); 5.4 Selection and focus in viewport. (P2) C When focus and/or selection changes they are in the viewport 5.5 Confirm form submission. (P2) P Only allows confirmation if the information is not secure? This is also under Preferences, Security, SSL, "Sending form data from unencrypted page to unencrypted page" 5.6 Confirm fee links. (P2) NI ...
...(P1) VG We rely on color alone when showing which links have be...
Creating a Login Manager storage module
Implement the nsILoginManagerStorage interface. Register that interface in a specific category. Some work has already been done to integrate the Login Manager with the Mac OS X keychain (bug 106400) and Gnome Keyring Manager (bug 309807). You should start with the existing code if you want to implement that in your extension. To see some debugging output in the console set signon.debug to true using about:config. Sample JavaScript implementation The following code snippet is a JavaScript component that implements a dummy nsILoginManagerStorage interface. See How_to_Build_an_XPCOM_Component_in_Javascript for more details about JavaScript components. const Cc = Components.classes; const Ci = Components.interfaces; Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); fun...
... ...
... ...
Performance
by the total number of tabs in a session. The following examples omit some boilerplate code for the sake of brevity The "better" examples also omit some best practices and only demonstrate how to fix the problem described in their respective subtopics. Performance best practices Declaring stateless functions once per process BAD: // addon.js Services.mm.loadFrameScript("framescript.js", true) // framescript.js const precomputedConstants = // ... function helper(window, action) { // ... do some work on the window } function doSomething(message) { result = helper(content, message.data) sendAsyncMessage("my-addon:response-from-child", {something: result}) } addMessageListener("my-addon:request-from-parent", doSomething) Why is this bad? Because declared functions are al...
...r lifetime to that of the frame itself, this does not apply to observer registrations. ...
...Since the code calls to the parent process to check whether a specific request can be allowed it wou...
Performance best practices for Firefox front-end engineers
umably the user isn't doing something. See also the blog post Collective scheduling with requestIdleCallback. As of bug 1353206, you can also schedule idle events in non-DOM contexts by using Services.tm.idleDispatchToMainThread. See the nsIThreadManager.idl file for more details. Hide your panels If you're adding a new XUL <xul:popup> or <xul:panel> to a document, set the hidden attribute to true by default. By doing so, you cause the binding applied on demand rather than at load time, which makes initial construction of the XUL document faster. Get familiar with the pipeline that gets pixels to the screen Learn how pixels you draw make their way to the screen. Knowing the path they will take through the various layers of the browser engine will help you optimize your code to avoid pitf...
...ct when and where paints are occurring. This feature is called "paint flashing," and it can be activated for both web content and the browser chrome. Paint flashing tints each region being painted with a randomly selected color so that it's more easy to see what on the screen is being painted. You can activate paint flashing for browser chrome by setting nglayout.debug.paint_flashing_chrome to true. You can activate paint flashing for web content by setting nglayout.debug.paint_flashing to true. After enabling these, exercise your function and see what's painting. See a lot of flashing / colors? That means a lot of painting is going on. The worst case is called over-painting. This is when you draw multiple times over the same space. Unless transparency is involved, all but the last paint...
...hines to make it more obvious to yourself if what you've written impacts the performance of the browser. ...
mozbrowsercaretstatechanged
ottom position of the bounding rectangle, in CSS pixels. left: The left position of the bounding rectangle, in CSS pixels. right: The right position of the bounding rectangle, in CSS pixels. commands An object that defines what commands can currently be executed in the browser <iframe>. 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. Possible values are visib...
...command is available (true) or not (false.) reason A DOMString that defines the reason for the state being changed. Possible values are visibilitychange, updateposition, longpressonemptycontent, taponcaret, presscaret, and releasecaret. zoomFactor A number defining the current zoom factor in the browser <iframe>. ...
...he state being changed. Possible values are visibilitychange, updateposition, longpressonemptycontent, taponcaret, presscaret, and releasecaret. zoomFactor A number defining the current zoom factor in the browser <iframe>. 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. sendDoCommandMsg A method allowing you to issue a command via an anonymouse function, i.
mozbrowserselectionstatechanged
of the bounding box, in CSS pixels. left: The X coordinate of the left of the bounding box, in CSS pixels. right: The X coordinate of the right of the bounding box, in CSS pixels. commands An object that stores information about what commands can be executed on the current selection. 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). canPaste: A Boolean Indicating whether the paste command can be issued (true) or not (false). zoomFactor A number representing the current zoom factor in the child frame. This is unitless ...
... states The current state of the selection. ...
... states The current state of the selection. ...
HTMLIFrameElement.setVisible()
e behavior may change in the future. The setVisible() method of the HTMLIFrameElement is used to change the visibility state of the browser <iframe>. The visible state of a browser <iframe> has nothing to do with its actual visibility (which is handled through CSS). The visible state is used to define the level of resources required by the browser <iframe>. ...
...me>. If the visible state is set to true, it means that the browser <iframe> should have high priority over the resources needed to render and handle its content. On the contrary, if its visible state is set to false, it has low priority over the resources it needs. As an example, if the content of a browser <iframe> uses the window.requestAnimationFrame method and if the visible state is set to true, window.requestAnimationFrame will be called as often as necessary. However, if the visible state is set to false, window.requestAnimationFrame will be called only when there are free resources to do it. Syntax instanceOfHTMLIframeElement.setVisible(visible); Returns Void. Parameters visible A Boolean that indicates if the browser <iframe> visible state is true or false. Examples var ...
...ary. However, if the visible state is set to false, window.requestAnimationFrame will be called only when there are free resources to do it. Syntax instanceOfHTMLIframeElement.setVisible(visible); Returns Void. Parameters visible A Boolean that indicates if the browser <iframe> visible state is true or false. Examples var browser = document.querySelector('iframe'); browser.setVisible(true); Specification Not part of any specification. ...
Chrome-only CSS reference
Mozilla › Gecko › Chrome › CSS
to the Web in general are also usable in Chrome stylesheets: see the CSS documentation for a list of these. -moz-window-draggingThe -moz-window-dragging CSS property specifies whether a window is draggable or not. ...
...window-dragging CSS property specifies whether a window is draggable or not. ...
...s in chrome documents when the root element's lightweightthemes attribute is true and a theme is selected.:-moz-lwtheme-brighttextThe :-moz-lwtheme-brighttext pseudo-class matches in chrome documents when :-moz-lwtheme is true and a lightweight theme with a bright text color is selected.:-moz-lwtheme-darktextThe :-moz-lwtheme-darktext pseudo-class matches in chrome documents when :-moz-lwtheme is true and a lightweight theme with a dark text color is selected.::-moz-tree-cellActivated by the properties attribute.::-moz-tree-cell-textActivated by the properties attribute.::-moz-tree-cell-text(hover)The :-moz-tree-cell-text(hover) CSS pseudo-class will match an element if the mouse cursor is presently hovering over text in a tree cell.::-moz-tree-columnActivated by the properties attribute.::-mo...
JavaScript-DOM Prototypes in Mozilla
o XPConnect through the object's class info. One of these interfaces is nsIDOMHTMLImageElement, others are nsIDOMNSHTMLImageElement (Netscape extensions to the standard interface), nsIDOMEventTarget, nsIDOMEventListener, nsIDOM3Node, and so on. The prototype object that XPConnect creates for the classes that have class info are shared within a scope (window). Because of this, the following holds true (assuming img1 and img2 are two different image objects in the same document): img1.__proto__ === img2.__proto__ If img1 would come from one document and img2 from another document, then the above would not be true. Both prototypes would look identical, but they would be two different JSObject's. This sharing of prototypes lets users do cool things like modify how all instances of a given cla...
...If such objects are provided, they are not guaranteed by any specification to have any e...
...If such objects are provided, they are not guaranteed by any specification to have any effect on the environment. Results in other browsers is not guaranteed. So how does all this work ...
PopupNotifications.jsm
s, so you don't have to do it yourself in most extensions. Method overview void locationChange(); Notification getNotification(id, browser); void remove(notification); Notification show(browser, id, message, anchorID, mainAction, secondaryActions, options); Properties Attribute Type Description isPanelOpen Boolean Returns true if the notification panel is currently visible, false if it is not. Methods locationChange() The consumer can call this method to let the popup notification module know that the current browser's location has changed. This lets the notification service update the active notifications as appropriate. Note: You shouldn't need to call this when using the PopupNotifications object in Firefo...
... until this time. The user may manually dismiss the notification, however. For most use cases, the value of this parameter should be Date.now() plus an offset indicating the amount of time the notification should be kept open (for example, Date.now() + 30000 for 30 seconds). persistWhileVisible A Boolean value indicating whether or not the notification should persist across location changes. If true, the notification will remain visible even if the browser navigates to a different location. dismissed A Boolean value indicating whether or not the notification should be added as a dismissed notification. Dismissed notifications can be activated by clicking on their anchor. This lets you create a notification that will appear when the user clicks the anchor. eventCallback A JavaScript funct...
...cations can be activated by clicking on their anchor. This lets you create a notification that will appear when the user clicks the anchor. eventCallback A JavaScript function to be invoked when the notification changes state. The callback's first parameter is a string identifying the state change that occurred. See Notification events below. neverShow Notifications with this parameter set to true will be removed when they would have otherwise been dismissed (i.e. any time the popup is closed due to user interaction). removeOnDismissal Notifications with this parameter set to true will be removed when they would have otherwise been dismissed (that is, any time the popup is closed due to user interaction). popupIconURL A string specifying the URL of the image to be displayed in the pop...
WebRequest.jsm
cancel it redirect it modify request headers modify response headers. To perform one of these operations, include a property with the appropriate name in the object returned from the listener, and assign it the desired value, as detailed in the table below: Operation Available in Return property Cancel onBeforeRequest cancel Boolean value set to true. See some examples of canceling requests. Redirect onBeforeSendHeaders redirectUrl String set to the URL to redirect the request to. See some examples of redirection. Modify request headers onBeforeSendHeaders requestHeaders Array of HTTP headers. Modify response headers onHeadersReceived responseHeaders Array ...
...ce://gre/modules/WebRequest.jsm", {}); Cu.import("resource://gre/modules/MatchPattern.jsm"); let pattern = new MatchPattern("http://example.org/*"); WebRequest.onBeforeRequest.addListener(cancelRequest, {urls: pattern}, ["blocking"]); function cancelRequest(e) { console.log("Canceling: " + e.url); return {cancel: true}; } This code cancels requests for images that are made to URLs under "https://mdn.mozillademos.org/": let {WebRequest} = Cu.import("resource://gre/modules/WebRequest.jsm", {}); Cu.import("resource://gre/modules/MatchPattern.jsm"); let pattern = new MatchPattern("https://mdn.mozillademos.org/*"); WebRequest.onBeforeRequest.addListener(cancelImages, { ...
...s.org/*"); WebRequest.onBeforeRequest.addListener(cancelImages, { urls: pattern, types: ["image"] }, ["blocking"]); function cancelImages(e) { console.log("Canceling: " + e.url); return {cancel: true}; } Redirecting This code replaces, by redirection, all network requests for images that are made to URLs under "https://mdn.mozillademos.org/": let {WebRequest} = Cu.import("resource://gre/modules/WebRequest.jsm", {}); Cu.import("resource://gre/modules/MatchPattern.jsm"); let pattern = new MatchPattern("https://mdn.mozillademos.org/*"); WebRequest.onBeforeSendHeaders.addListener(redirect, ...
Profiling with the Firefox Profiler
e arm-eabi-addr2line (on Linux) or mdfind name:arm-eabi-addr2line (on OS X) and stick an export to its location in ~/.bash_profile. The extension will invoke bash to use adb and addr2line. Install the latest pre-release build in your host machine's Firefox browser that has your phone reachable via ADB. This will add a icon in the top right of the browser. Set devtools.debugger.remote-enabled to true in about:config for Fennec. Select target Mobile USB and press Connect. The first run will take an additional 1 minute or so to pull in the required system libraries. Profiling Firefox Startup Start your Firefox with the environment variable MOZ_PROFILER_STARTUP=1 set. This way the profiler is started as early as possible during startup. Then capture the profile using the add-on as usual. ...
...e IO, Profiled Thread File IO, All File IO - "mainthreadio", "fileio", "allfileio" This will interpose file I/O from a selection of threads, and report them in the profiles. Screenshots This will insert screenshots into the profile. It may have significant performance impact, especially on graphics operations. Viewing the Layer Tree To view the layer tree, the layers.dump pref must be set to true in the Firefox or B2G program being profiled. In addition, both the compositor thread and the content thread (in the case of B2G, the content thread of whichever app you're interested in) must be profiled. For example, on B2G, when profiling the Homescreen app, you might start the profiler with: ./profile.sh start -p b2g -t Compositor && ./profile.sh start -p Homescreen Having gotten a profil...
...layer tree (a PaintedLayerComposite), and a strip at the top of the right panel is highlighted, telling me that this layer is for the system notification bar in B2G. Viewing Textures Sometimes, it's useful to see not only the structure of the layer tree for each composite, but also the rendered textures for each layer. This can be achieved by additionally setting the layers.dump-texture pref to true, or by adding -f layersdump to the profiler command line (the latter implies both the layers.dump and layers.dump-texture prefs). Warning: Dumping texture data slows performance considerably, and requires a lot of storage for the profile files. Expect rendering to happen at a significantly reduced frame rate when profiling this way, and keep the duration of the capture short, to ensure the samp...
Leak And Bloat Tests
user_pref("mail.accountmanager.accounts", "account1,account2"); user_pref("mail.accountmanager.defaultaccount", "account2"); user_pref("mail.accountmanager.localfoldersserver", "server1"); user_pref("mail.identity.id1.fullName", "Tinderbox"); user_pref("mail.identity.id1.smtpServer", "smtp1"); user_pref("mail.identity.id1.useremail", "tinderbox@invalid.com"); user_pref("mail.identity.id1.valid", true); user_pref("mail.root.none-rel", "[ProfD]Mail"); user_pref("mail.root.pop3-rel", "[ProfD]Mail"); user_pref("mail.server.server1.directory-rel", "[ProfD]Mail/Local Folders"); user_pref("mail.server.server1.hostname", "Local Folders"); user_pref("mail.server.server1.name", "Local Folders"); user_pref("mail.server.server1.type", "none"); user_pref("mail.server.server1.userName", "nobody"); user_pre...
...s"); 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("...
...erver.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.roo...
Index
guments. -changepw tokenname Change the password on the named token. If the token has not been initialized, this option initializes the password. Use this option with the -pwfile and -newpwfile arguments. A password is equivalent to a personal identification number (PIN). -chkfips Verify whether the module is in the given FIPS mode. true means to verify that the module is in FIPS mode, while false means to verify that the module is not in FIPS mode. -create Create new certificate, key, and module databases. Use the -dbdir directory argument to specify a directory. If any of these databases already exist in a specified directory, modutil returns an error messag...
...-delete modulename Delete the named module. The default NSS PKCS #11 module cannot be deleted. -disable modulename Disable all slots on the named module. Use the -slot argument to disable a specific slot. -enable modulename Enable all slots on the named module. Use the -slot argument to enable a specific slot. -fips [true | false] Enable (true) or disable (false) FIPS 140-2 compliance for the default NSS module. -force Disable modutil's interactive prompts so it can be run from a script. Use this option only after manually testing each planned operation to check for warnings and to ensure that bypassing the prompts will cause no security lapse...
... " enabled. Be sure that the appropriate amount of trailing whitespace is after the slot name. Some slot names have a significant amount of whitespace that must be included, or the operation will fail. Enabling and Verifying FIPS Compliance The NSS modules can have FIPS 140-2 compliance enabled or disabled using modutil with the -fips option. For example: modutil -fips true -dbdir sql:/home/my/sharednssdb/ FIPS mode enabled. To verify that status of FIPS mode, run the -chkfips command with either a true or false flag (it doesn't matter which). The tool returns the current FIPS setting. modutil -chkfips false -dbdir sql:/home/my/sharednssdb/ FIPS mode enabled. Changing the Password on a Token Initializing or changing a token's password: modu...
NSS Sample Code Utilities_1
PORT_Alloc(outLen) : PORT_Alloc(len); if (!outbuf->data) { return -1; } if (isHexData) { while (*inString) { if ((*inString == '\n') || (*inString == ':')) { inString++; continue; } digit1 = GetDigit(*inString++); ...
...ng == '\n') || (*inString == ':')) { inString++; continue; } digit1 = GetDigit(*inString++); digit2 = GetDigit(*inString++); if ((digit1 == -1) || (digit2 == -1)) { PORT_Free(outbuf->data); outbuf->data = NULL; return -1; } outbuf->data[trueLen++] = digit1 << 4 | digit2; } } else { while (*inString) { if (*inString == '\n') { inString++; continue; } outbuf->data[trueLen++] = *inString++; } outbuf->data[trueLen] = '\0'; trueLen = trueLen-1; } outbuf->len = trueLen; return 0; } /* * FileToItem */ SECStatus File...
...; tcsetattr(fd, TCSAFLUSH, &tio); } } /* * CheckPassword */ PRBool CheckPassword(char *cp) { int len; char *end; len = PORT_Strlen(cp); if (len < 8) { return PR_FALSE; } end = cp + len; while (cp < end) { unsigned char ch = *cp++; if (!((ch >= 'A') && (ch <= 'Z')) && !((ch >= 'a') && (ch <= 'z'))) { return PR_TRUE; } } return PR_FALSE; } /* * GetPassword */ char* GetPassword(FILE *input, FILE *output, char *prompt, PRBool (*ok)(char *)) { char phrase[200] = {'\0'}; int infd = fileno(input); int isTTY = isatty(infd); for (;;) { /* Prompt for password */ if (isTTY) { fprintf(output, "%s", prompt); fflus...
Utilities for nss samples
PORT_Alloc(outLen) : PORT_Alloc(len); if (!outbuf->data) { return -1; } if (isHexData) { while (*inString) { if ((*inString == '\n') || (*inString == ':')) { inString++; continue; } digit1 = GetDigit(*inString++); ...
...ng == '\n') || (*inString == ':')) { inString++; continue; } digit1 = GetDigit(*inString++); digit2 = GetDigit(*inString++); if ((digit1 == -1) || (digit2 == -1)) { PORT_Free(outbuf->data); outbuf->data = NULL; return -1; } outbuf->data[trueLen++] = digit1 << 4 | digit2; } } else { while (*inString) { if (*inString == '\n') { inString++; continue; } outbuf->data[trueLen++] = *inString++; } outbuf->data[trueLen] = '\0'; trueLen = trueLen-1; } outbuf->len = trueLen; return 0; } /* * FileToItem */ SECStatus File...
...; tcsetattr(fd, TCSAFLUSH, &tio); } } /* * CheckPassword */ PRBool CheckPassword(char *cp) { int len; char *end; len = PORT_Strlen(cp); if (len < 8) { return PR_FALSE; } end = cp + len; while (cp < end) { unsigned char ch = *cp++; if (!((ch >= 'A') && (ch <= 'Z')) && !((ch >= 'a') && (ch <= 'z'))) { return PR_TRUE; } } return PR_FALSE; } /* * GetPassword */ char* GetPassword(FILE *input, FILE *output, char *prompt, PRBool (*ok)(char *)) { char phrase[200] = {'\0'}; int infd = fileno(input); int isTTY = isatty(infd); for (;;) { /* Prompt for password */ if (isTTY) { fprintf(output, "%s", prompt); fflus...
nss tech note3
ENCIPHERMENT. For other types of keys, it is KEY_AGREEMENT. Cert Extensions: One vital Certificate extension is the "Basic Constraints" extension. It tells NSS whether the cert is a CA cert, or not, and affects every other aspect of how the cert is interpreted by NSS. The OID for this extension is { 2 5 29 19 }, encoded in hex as 0x55, 0x1d, 0x13. If the extension is present and has the value TRUE, then this cert is taken to be a CA cert. Otherwise it is not (except that trust flags may override this, see discussion of trust flags farther below). Netscape has its own openly defined Cert Type extension, which can be used to explicitly set the Cert Type in any Cert. The Cert Type extension has bits in it that correspond directly to the cert types named above. The OID for this extension is...
...f. If present, this extension directly determines the values of the 8 key usages defined above. If absent, the cert is assumed to be valid for all key usages. The X.509v3 extended Key usage extension as OID { 2 5 29 37 } encoded in hex as 0x55, 0x1d, 0x25. That extension contains a sequence of OIDs, each of which signifies one or more Cert Types, depending on the presence or absence of of the True Basic Constraints extension; that is, the interpretation of the extended Key Usage extension is controlled by whether the cert is a CA cert, or not. The following table shows the OIDs recognized in the extended key usage extension, and how they map to cert types and key usages for CA and non-CA certs. extended key usage OID non-CA cert CA cert ----------------------------------- -------------...
... If the basic constraints extension is missing, but the user has trusted the cert as a CA cert, the cert also gets the STATUS_RESPONDER cert type. If the cert has a Fortezza type public key with the magic bits that signify that it is a CA, it is given cert types SSL_CA and EMAIL_C...
PKCS11 FAQ
Mozilla › Projects › NSS › PKCS11 › FAQ
ve the same label). S/MIME-capable certificates are also looked up by issuer/serial number. Certificates may be looked up by their DER value. Certificates may also be looked up by subject. More than one certificate can match, but each certificate with the same subject should be part of the same personality. NSS may enumerate all the permanment certificates in a token (CKA_TOKEN set to true). Private keys must have the same CKA_ID value as their corresponding certificate, and this value must be unique on the token. Orphaned keys have a CKA_ID generated from some part of the public key. This value is set when the key is generated, so that NSS will be able to find the key when the certificate for that key is loaded. This case is interesting only for read/write tokens. Wha...
...atically? Yes. If your token can do CKM_RSA_PKCS, and is writable, NSS displays it as one of the options to do key generation with. If the token cannot do CKM_RSA_PKCS_GEN_KEYPAIR, NSS uses its software key generation code and writes the private and public keys into the token using C_CreateObject. The RSA private key will contain all the attributes specified by PKCS #11 version 2.0. This is also true for CKM_DSA and CKM_DSA_GEN_KEYPAIR. What is the C_GenerateKeyPair process? For example, what happens when an application in the a server asks an NSS based client to do a keypair generation while a smartCard is attached? How is the private key stored to the smartCard, and how is the public key sent to the server (with wrapping?). The private key is created using C_GenerateKeyPair or stored us...
...Pair if the token supports the keygen method. If the token does not support keygen, NSS generates the key internally and uses C_CreateObject to load the private key into the token. When the certificate is received after the keygen, NSS loads it into the token with C_CreateObject. NSS also does a similiar operation for importing private keys and certificates through pkcs12. The above statement is true for read-write tokens only. When and how does NSS generate private keys on the token? As stated above, NSS uses C_GenerateKeyPair if the token supports the keygen method. If an RSA key is being generated, the NSS application will present a list of all writable RSA devices asks the user to select which one to use, if a DSA key is being generated, it will present a list of all the writable DSA de...
NSS tools : modutil
is option with the -libfile, -ciphers, and -mechanisms arguments. -changepw tokenname Change the password on the named token. If the token has not been initialized, this option initializes the password. Use this option with the -pwfile and -newpwfile arguments. A password is equivalent to a personal identification number (PIN). -chkfips Verify whether the module is in the given FIPS mode. true means to verify that the module is in FIPS mode, while false means to verify that the module is not in FIPS mode. -create Create new certificate, key, and module databases. Use the -dbdir directory argument to specify a directory. If any of these databases already exist in a specified directory, modutil returns an error message. -default modulename Specify the security mechanisms for whi...
...anisms argument. -delete modulename Delete the named module. The default NSS PKCS #11 module cannot be deleted. -disable modulename Disable all slots on the named module. Use the -slot argument to disable a specific slot. The internal NSS PKCS #11 module cannot be disabled. -enable modulename Enable all slots on the named module. Use the -slot argument to enable a specific slot. -fips [true | false] Enable (true) or disable (false) FIPS 140-2 compliance for the default NSS module. -force Disable modutil's interactive prompts so it can be run from a script. Use this option only after manually testing each planned operation to check for warnings and to ensure that bypassing the prompts will cause no security lapses or loss of database integrity. -jar JAR-file Add a new PKCS ...
...ryptographic Services " enabled. Be sure that the appropriate amount of trailing whitespace is after the slot name. Some slot names have a significant amount of whitespace that must be included, or the operation will fail. Enabling and Verifying FIPS Compliance The NSS modules can have FIPS 140-2 compliance enabled or disabled using modutil with the -fips option. For example: modutil -fips true -dbdir sql:/home/my/sharednssdb/ FIPS mode enabled. To verify that status of FIPS mode, run the -chkfips command with either a true or false flag (it doesn't matter which). The tool returns the current FIPS setting. modutil -chkfips false -dbdir sql:/home/my/sharednssdb/ FIPS mode enabled. Changing the Password on a Token Initializing or changing a token's password: modutil -changepw tok...
NSS Tools modutil
isms for which the named module will not be a default provider. The security mechanisms are specified with the -mechanisms mechanism-list argument. -enable modulename Enable all slots on the named module. Use the [-slot slotname] argument to enable a specific slot. -disable modulename Disable all slots on the named module. Use the [-slot slotname] argument to disable a specific slot. -fips [true | false] Enable (true) or disable (false) FIPS 140-2 compliance for the Netscape Communicator internal module. -force Disable the Security Module Database Tool's interactive prompts so it can be run from a script. Use this option only after manually testing each planned operation to check for warnings and to ensure that bypassing the prompts will cause no security lapses or loss of database int...
... This information file contains special scrip...
...ing, you should exit Communicator before continuing thisoperation. Type 'q <enter>' to abort, or <enter> to continue: After you press Enter, the tool displays the following: Using database directory c:\databases...Slot "Cryptographic Reader" enabled. Enabling FIPS Compliance This example enables FIPS 140-2 compliance in Communicator's internal module: modutil -dbdir "C:\databases" -fips true The Security Module Database Tool displays a warning: WARNING: Performing this operation while the browser is running could causecorruption of your security databases. If the browser is currently running,you should exit browser before continuing this operation. Type'q <enter>' to abort, or <enter> to continue: After you press Enter, the tool displays the following: FIPS mode enabled. Addi...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
guments. -changepw tokenname Change the password on the named token. If the token has not been initialized, this option initializes the password. Use this option with the -pwfile and -newpwfile arguments. A password is equivalent to a personal identification number (PIN). -chkfips Verify whether the module is in the given FIPS mode. true means to verify that the module is in FIPS mode, while false means to verify that the module is not in FIPS mode. -create Create new certificate, key, and module databases. Use the -dbdir directory argument to specify a directory. If any of these databases already exist in a specified directory, modutil returns an error messag...
...-delete modulename Delete the named module. The default NSS PKCS #11 module cannot be deleted. -disable modulename Disable all slots on the named module. Use the -slot argument to disable a specific slot. -enable modulename Enable all slots on the named module. Use the -slot argument to enable a specific slot. -fips [true | false] Enable (true) or disable (false) FIPS 140-2 compliance for the default NSS module. -force Disable modutil's interactive prompts so it can be run from a script. Use this option only after manually testing each planned operation to check for warnings and to ensure that bypassing the prompts will cause no security lapse...
... " enabled. Be sure that the appropriate amount of trailing whitespace is after the slot name. Some slot names have a significant amount of whitespace that must be included, or the operation will fail. Enabling and Verifying FIPS Compliance The NSS modules can have FIPS 140-2 compliance enabled or disabled using modutil with the -fips option. For example: modutil -fips true -dbdir sql:/home/my/sharednssdb/ FIPS mode enabled. To verify that status of FIPS mode, run the -chkfips command with either a true or false flag (it doesn't matter which). The tool returns the current FIPS setting. modutil -chkfips false -dbdir sql:/home/my/sharednssdb/ FIPS mode enabled. Changing the Password on a Token Initializing or changing a token's password: modu...
JS_AddArgumentFormatter
ed by formatter, or whose handler should be removed. formatter JSArgumentFormatter The function to be used to convert arguments described by the given format. This function is described in more detail below. Description JS_AddArgumentFormatter establishes formatter as the conversion function for format strings beginning with format in the context cx. On success, it returns JS_TRUE. Otherwise it returns JS_FALSE. (At the moment, JS_AddArgumentFormatter fails only if there is no memory available to record the registration.) JS_AddArgumentFormatter does not copy format, it points at the string storage allocated by the caller, which is typically a string constant. If format is in dynamic storage, the caller must keep the string alive until JS_RemoveArgumentFormatter is called.
...SArgumentFormatter)(JSContext *cx, const char *format, JSBool fromJS, jsval **vpp, va_list *app); Name Type Description cx JSContext * The context in which the conversion is being performed. format const char * The tail of the format string whose prefix is associated with this formatting function. 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. vpp jsval ** In-out parameter. A pointer into an array of jsval values. app va_list * In-out parameter. A pointer to an argument pointer, used to retrieve pointers to C values. Callback Description The conver...
...should convert from jsval values to C values; JS_FALSE if the conversion function should convert from C values to jsval values. vpp jsval ** In-out parameter. A pointer into an array of jsval values. app va_list * In-out parameter. A pointer to an argument pointer, used to retrieve pointers to C values. Callback Description The conversion function should return true on success, and return false after reporting an error or detecting an already-reported error. For a given format string, for example "AA", the formatter is called from JS_ConvertArgumentsVA like so: formatter(cx, "AA...", JS_TRUE, &sp, &ap); sp points into the arguments array on the JS stack, while ap points into the stdarg.h va_list on the C stack. The JS_TRUE passed for fromJS tells the format...
JS_DeleteProperty2
perty. name or id const char * or const char16_t or JS::HandleId Name of the property to delete. namelen size_t (only in JS_DeleteUCProperty2) The length of name in characters; or -1 to indicate that name is null-terminated. succeeded bool * Out parameter. 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. It behaves like the JavaScript expression delete obj[name]. JS_DeleteUCProperty2 is the Unicode version of the function. JS_DeletePropertyById2 is the same but takes a JS::HandleId for the property name. First, a property lookup is performed. Then one...
...ript expression delete obj[name]. JS_DeleteUCProperty2 is the Unicode version of the function. JS_DeletePropertyById2 is the same but takes a JS::HandleId for the property name. First, a property lookup is performed. ...
...*succeeded is set to true and obj's JSClass.delProperty hook is called (which may change *succeeded). No property is deleted, but this is not an error. If obj has the specified property but it is permanent, then *succeeded receives false. No property is deleted, but this is not an error. Otherwise obj has a non-permanent own property with the given name or id. In this case, *succeeded is set to true and obj's JSClass.delProperty hook is called (which may change *succeeded). If the hook returns false, the error is propagated. Otherwise, if obj is not configurable, an error is raised. Otherwise, *succeeded receives true and the property is removed. These functions return true on success, regardless of whether a property was actually deleted. On error or exception, the return value is false, ...
JS_GetProperty
ption JS_GetProperty examines a specified JS object obj and its prototype chain for a property with the specified name. It behaves like the JavaScript expression obj[name]. JS_GetUCProperty is the Unicode version of the function. JS_GetPropertyById is the same but takes a JS::HandleId for the property name. In the simplest case, JS_GetProperty stores the value of the property in *vp and returns true. However, several different hooks can affect property gets. The full algorithm is described below. Details First, a property lookup is performed. If the lookup proceeds without error, exactly one of the following cases applies: If the property is not found, then *vp is set to undefined. Then the JSClass.getProperty hook of obj's class is called with the arguments (cx, obj, id, vp). For many ...
... First, a property lookup is performed. If the lookup proceeds without error, exactly one of the following cases applies: If the property is not found, then *vp is set to undefined. Then the JSClass.getProperty hook of obj's class is called with the arguments (cx, obj, id, vp). For many objects, including objects of standard classes such as Object and Array, this hook does nothing and returns true, so the property get succeeds and undefined is left in *vp. If the property is found on a non-native object, get handler of Proxy (only if the object is a Proxy) or its JSObjectOps.getProperty method is called. Otherwise the property is found on a native object. If the property has a JavaScript getter, it is called. Otherwise *vp is set to the property's stored value, or undefined if the proper...
...s JSObjectOps.getProperty method is called. Otherwise the property is found on a native object. If the property has a JavaScript getter, it is called. Otherwise *vp is set to the property's stored value, or undefined if the property does not have a stored value, and then the property's getter is called with the arguments (cx, obj, id, vp). For many properties, the getter does nothing and returns true, so the property get succeeds and the property's stored value is left in *vp. Internally, property retrieval, including all the behavior described above, is implemented by obj's JSObjectOps.getProperty callback. On success, these functions set *vp to the current value of the property, or undefined if obj has no such property, and return true. On an error or exception, these functions return fa...
TPS Bookmark Lists
" denotes that "folder1" is a sub-folder of "menu". TPS does not support forward slashes as part of a folder name. Folder contents The contents for a folder are given as an array of objects, representing various bookmark types, described below. Bookmark objects Valid properties are: uri: the bookmark uri. Required. title: the bookmark title. Optional. Defaults to the bookmark uri. loadInSidebar: true or false. Optional. Toggles the "load in sidebar" property. description: the bookmark description. Optional. tags: an array of tags for the bookmark. Optional. keyword: the keyword for the bookmark. Optional. after: the title of the bookmark item expected to be found AFTER this bookmark; used only in verify and modify actions. before: the title of the bookmark item expected to be found BEFORE thi...
...changes: an object containing new properties to be set for this separator when this asset list is used in a modify action. The properties for this object are: location: the full path of the folder that this separator should be moved to position: th...
...That is, the first item is appended to its parent folder, then the second, and so forth. after and before properties are ignored. Bookmarks.verify - The bookmark items ...
Components.utils.cloneInto
If you do pass this flag, then functions in the object are cloned using the same mechanism as that used in Components.utils.exportFunction: // add-on script var addonScriptObject = { greetme: function() { alert("hello from add-on"); } }; contentWindow.addonScriptObject = cloneInto(addonScriptObject, contentWindow, ...
...n functions in the object are cloned using the same mechanism as that used in Components.utils.exportFunction: // add-on script var addonScriptObject = { greetme: function() { alert("hello from add-on"); } }; contentWindow.addonScriptObject = cloneInto(addonScriptObject, contentWindow, {cloneFunctions: true}); // page script var test = document.getElementById("test"); test.addEventListener("click", function() { window.addonScriptObject.greetme(); }, false); Cloning objects that contain DOM elements By default, if the object you clone contains objects that are reflected from C++, such as DOM elements, the cloning operation will fail with an error. If you pass the {wrapReflectors:true} flag, then...
...on will fail with an error. If you pass the {wrapReflectors:true} flag, then the object you clone is allowed to contain these objects: // add-on script var addonScriptObject = { body: contentWindow.document.body }; contentWindow.addonScriptObject = cloneInto(addonScriptObject, contentWindow, {wrapReflectors: true}); // page script var test = document.getElementById("test"); test.addEventListener("click", function() { console.log(window.addonScriptObject.body.innerHTML); }, false); Access to these objects in the target scope is subject to the normal security checks. ...
Components.utils.createObjectIn
he new object will be created in the scope of this object's compartment. options An object containing a single option defineAs, which determines the name of the object in the target compartment. Return value A new object in the specified scope. ...
...e created in the scope of this object's compartment. options An object containing a single option defineAs, which determines the name of the object in the target compartment. Return value A new object in the specified scope. ...
... scope of this object's compartment. options An object containing a single option defineAs, which determines the name of the object in the target compartment. Return value A new object in the specified scope. ...
XPCshell Test Manifest Expressions
Integers: A series of contiguous digits. Only decimal integers are supported. ...
... Comments If an expression contains a # (pound/hash) character outside of a string, the character and the rest of the line will be treated as a comment. This is useful as the entire line will generally be reported whenever tests are reported as being ski...
...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. Comments If an expression contains a # (pound/hash) character outside of a string, the character and the rest of the line will be treated as a comment. This is useful as the entire line will generally be reported whenever tests are reported as being skipped, meaning the comment as well as the expression itself will appear in any...
NS_ConvertASCIItoUTF16
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...t PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* aTarget PRUnichar* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...e string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters PRUnichar** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(PRUnichar, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters PRUnichar aChar PRInt32 aOffset ...
NS_ConvertUTF16toUTF8
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...eplaceSubstring(const char*, const char*) - source Parameters char* aTarget char* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...of the string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters char** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(char, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters char aChar PRInt32 aOffset ...
NS_ConvertUTF8toUTF16
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...t PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* aTarget PRUnichar* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...e string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters PRUnichar** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(PRUnichar, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters PRUnichar aChar PRInt32 aOffset ...
NS_LossyConvertUTF16toASCII
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...eplaceSubstring(const char*, const char*) - source Parameters char* aTarget char* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...of the string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters char** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(char, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters char aChar PRInt32 aOffset ...
nsAdoptingCString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...eplaceSubstring(const char*, const char*) - source Parameters char* aTarget char* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...of the string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters char** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(char, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters char aChar PRInt32 aOffset ...
nsAdoptingString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...t PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* aTarget PRUnichar* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...e string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters PRUnichar** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(PRUnichar, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters PRUnichar aChar PRInt32 aOffset ...
nsAutoString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...t PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* aTarget PRUnichar* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...e string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters PRUnichar** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(PRUnichar, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters PRUnichar aChar PRInt32 aOffset ...
nsCAutoString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace th...
...ing(const char*, const char*) - source Parameters char* aTarget char* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading c...
... is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters char** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(char, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters char aChar PRInt32 aOffset ...
nsCString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...eplaceSubstring(const char*, const char*) - source Parameters char* aTarget char* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...of the string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters char** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(char, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters char aChar PRInt32 aOffset ...
nsDependentCString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...eplaceSubstring(const char*, const char*) - source Parameters char* aTarget char* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...of the string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters char** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(char, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters char aChar PRInt32 aOffset ...
nsDependentString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...t PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* aTarget PRUnichar* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...e string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters PRUnichar** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(PRUnichar, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters PRUnichar aChar PRInt32 aOffset ...
nsFixedCString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...eplaceSubstring(const char*, const char*) - source Parameters char* aTarget char* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...of the string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters char** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(char, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters char aChar PRInt32 aOffset ...
nsFixedString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...t PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* aTarget PRUnichar* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...e string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters PRUnichar** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(PRUnichar, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters PRUnichar aChar PRInt32 aOffset ...
nsPromiseFlatCString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...eplaceSubstring(const char*, const char*) - source Parameters char* aTarget char* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...of the string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters char** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(char, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters char aChar PRInt32 aOffset ...
nsPromiseFlatString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...t PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* aTarget PRUnichar* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...e string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters PRUnichar** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(PRUnichar, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters PRUnichar aChar PRInt32 aOffset ...
nsString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...t PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* aTarget PRUnichar* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...e string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters PRUnichar** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(PRUnichar, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters PRUnichar aChar PRInt32 aOffset ...
nsXPIDLCString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...eplaceSubstring(const char*, const char*) - source Parameters char* aTarget char* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...of the string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters char** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(char, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters char aChar PRInt32 aOffset ...
nsXPIDLString
@param aSet -- characters to be cut from this Parameters char* aSet StripWhitespace void StripWhitespace() - source This method strips whitespace throughout the string. ...
...t PRUnichar*, const PRUnichar*) - source Parameters PRUnichar* aTarget PRUnichar* aNewValue Trim void Trim(const char*, PRBool, PRBool, PRBool) - source This method trims characters found in aTrimSet from either end of the underlying string. @param aSet -- contains chars to be trimmed from both ends @param aEliminateLeading @param aEliminateTrailing @param aIgnoreQuotes -- if true, causes surrounding quotes to be ignored @return this Parameters char* aSet PRBool aEliminateLeading PRBool aEliminateTrailing PRBool aIgnoreQuotes CompressWhitespace void CompressWhitespace(PRBool, PRBool) - source This method strips whitespace from string. You can control whether whitespace is yanked from start and end of string as well. @param aEliminateLeading controls stripping...
...e string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters PRUnichar** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(PRUnichar, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters PRUnichar aChar PRInt32 aOffset ...
IAccessibleTable
ans multiple columns. Return value E_INVALIDARG if bad [in] passed, [out] value is 0. S_OK. isColumnSelected() Returns a boolean value indicating whether the specified column is completely selected. [propget] HRESULT isColumnSelected( [in] long column, [out] boolean isSelected ); Parameters column 0 based index of the column for which to determine whether it is selected. isSelected Returns true if the specified column is selected completely and false otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value indicating whether the specified row is completely selected. [propget] HRESULT isRowSelected( [in] long row, [out] boolean isSelected ); Parameters row 0 based index of the row for which to determine whether it...
...ted completely and false otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value indicating whether the specified row is completely selected. [propget] HRESULT isRowSelected( [in] long row, [out] boolean isSelected ); Parameters row 0 based index of the row for which to determine whether it is selected. isSelected Returns true if the specified row is selected completely and false otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. isSelected() Returns a boolean value indicating whether the specified cell is selected. [propget] HRESULT isSelected( [in] long row, [in] long column, [out] boolean isSelected ); Parameters row 0 based index of the row for the cell to determine whethe...
...ue is false. S_OK. isSelected() Returns a boolean value indicating whether the specified cell is selected. [propget] HRESULT isSelected( [in] long row, [in] long column, [out] boolean isSelected ); Parameters row 0 based index of the row for the cell to determine whether it is selected. column 0 based index of the column for the cell to determine whether it is selected. isSelected Returns true if the specified cell is selected and false otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. modelChange() Returns the type and extents describing how a table changed. Provided for use by the IA2_EVENT_TABLE_MODEL_CHANGED event handler. This data is only guaranteed to be valid while the thread notifying the event continues. Once the handler has returned, the v...
inIDOMUtils
rieve the font faces of. Return value An nsIDOMFontFaceList object listing all the font faces used by the text in the range. isIgnorableWhitespace() Determines if the specified text node contains only ignorable whitespace characters. boolean isIgnorableWhitespace( in nsIDOMCharacterData aDataNode ); Parameters aDataNode A DOM CharacterData node; that is, a text node. ...
... parseStyleSheet() Parse CSS and update the style sheet in place. void parseStyleSheet( in nsIDOMCSSStyleSheet aSheet, in DOMString aInput ); Parameters aSheet A DOMCSSStyleSheet. aInput A DOMString. The new source string for the style sheet. ...
... aPseudoClass The pseudo-class to remove the lock of. e.g. ":hover". hasPseudoClassLock() Checks whether the element element has a particular pseudo-class lock applied. boolean hasPseudoClassLock( in nsIDOMElement aElement, in DOMString aPseudoClass ); Parameters aElement The element to test. aPseudoClass The pseudo-class lock to test for existence, e.g. ":hover". Return value true if lock exists, false otherwise clearPseudoClassLocks() Removes any pseudo-class locks from the element. void clearPseudoClassLocks( in nsIDOMElement aElement ); Parameters aElement The element to remove the pseudo-class locks from. ...
mozIThirdPartyUtil
ow() with arguments of the channel's bottommost window and the channel URI, respectively. Therefore, both the channel's URI and each level in the window hierarchy associated with the channel is tested. For example, if aURI is "http://mail.google.com/", aChannel has a URI of "http://google.com/", and its parent is the topmost content window with a URI of "http://mozilla.com", the result will be true. boolean isThirdPartyChannel( in nsIChannel aChannel, in nsIURI aURI Optional ); Parameters aChannel The channel associated with the load. aURI Optional A URI to test against. If null, the URI of the channel will be used. Return value true if aURI is third party with respect to the channel URI or any of the URIs associated with the same-type window hierarchy of the channel. isThirdPartyURI...
...r a file:// URI), an exact string comparison on host is performed. For example, the URI "http://mail.google.com/" is not third party with respect to "http://images.google.com/", but "http://mail.yahoo.com/" and "http://192.168.1.1/" are. boolean isThirdPartyURI( in nsIURI aFirstURI, in nsIURI aSecondURI ); Parameters aFirstURI Missing Description aSecondURI Missing Description Return value true if aFirstURI is third party with respect to aSecondURI. isThirdPartyWindow() Determine whether the given window hierarchy is third party. This is done as follows: Obtain the URI of the principal associated with aWindow. Call this the 'bottom URI'. If aURI is provided, determine if it is third party with respect to the bottom URI. If so, return. Find the same-type parent window, if there is one,...
...re, each level in the window hierarchy is tested. (This means that nested iframes with different base domains, even though the bottommost and topmost URIs might be equal, will be considered third party.) For example, if aURI is "http://mail.google.com/", 'aWindow' has a URI of "http://google.com/", and its parent is the topmost content window with a URI of "http://mozilla.com", the result will be true. boolean isThirdPartyWindow( in nsIDOMWindow aWindow, in nsIURI aURI Optional ); Parameters aWindow The bottommost window in the hierarchy. aURI Optional A URI to test against. If null, the URI of the principal associated with aWindow will be used. Return value true if aURI is third party with respect to any of the URIs associated with aWindow and its same-type parents. ...
nsIAbCard
m4 AString notes AString lastModifiedDate unsigned long popularityIndex unsigned long popularityIndex is bumped every time e-mail is sent to this recipient . preferMailFormat unsigned long Allowed values are stored in nsIAbPreferMailFormat. isMailList boolean mailListURI string If isMailList is true then mailListURI will contain the URI of the associated mailing list. allowRemoteContent boolean Allow remote content to be displayed in HTML mail received from this contact Methods getCardValue() AString getCardValue(in string name) Parameters name The attribute you want the value for. Return value The value of the attribute asked for. setCardValue() void se...
...AString value) Parameters attrname The attribute you want to set. value The value to set the attribute to. copy() This function will copy all values from one card to another. void copy(in nsIAbCard srcCard) Parameters srcCard The source card to copy values from. equals() boolean equals(in nsIAbCard card) Parameters card The card you are comparing with. Return value true if the cards are the same. convertToBase64EncodedXML() string convertToBase64EncodedXML() Return value convertToXMLPrintData() AString convertToXMLPrintData() Return value convertToEscapedVCard() string convertToEscapedVCard() Return value generateName() Generate a name from the card for display purposes. Using the firstName, lastName and the displayName. We allow the caller ...
...n will obtain the bundle itself. If cached by the caller and supplied to this function, then performance will be improved over many calls. Return value A string containing the generated name. generatePhoneticName() Generate a phonetic name from the card, using the firstName and lastName values. AString generatePhoneticName(in boolean aLastNameFirst) Parameters aLastNameFirst Set to true to put the last name before the first. Return value A string containing the generated phonetic name. ...
nsIAuthPrompt
lt ); Parameters dialogTitle The title of the dialog. text The text of the prompt message dialog box. passwordRealm The password realm. For example, ldap://localhost/dc=test. savePassword Saving password option. One of the SAVE_PASSWORD_* constants defaultText The default text for the text input dialog box. result The result of the dialog box, OK or Cancel buttons. Return value true for OK, false for Cancel. promptPassword() This method puts up a password dialog with OK and Cancel buttons. Note: If a username is specified, the username should be escaped. boolean promptPassword( in wstring dialogTitle, in wstring text, in wstring passwordRealm, in PRUint32 savePassword, inout wstring pwd ); Parameters dialogTitle The title of the dialog. text The text of...
...sword realm. For example, ldap://localhost/dc=test. If a username is specified (http://user@site.com) it will be used when matching existing logins or saving new ones. If no username is specified, only password-only logins will be matched or saved. savePassword Saving password option. One of the SAVE_PASSWORD_* constants pwd The password entered by the user if OK was selected. Return value true for OK, false for Cancel. promptUsernameAndPassword() This method puts up a username/password dialog with OK and Cancel buttons. boolean promptUsernameAndPassword( in wstring dialogTitle, in wstring text, in wstring passwordRealm, in PRUint32 savePassword, inout wstring user, inout wstring pwd ); Parameters dialogTitle The title of the dialog. text The text of the prompt me...
... ...
nsIBrowserHistory
setting up a batch operation doesn't make sense anymore. void removePages( [array, size_is(aLength)] in nsIURI aURIs, in unsigned long aLength, in boolean aDoBatchNotify /* parameter removed in Gecko 9.0 */ ); Parameters aURIs An array of page URIs to be removed from history. aLength The number of pages listed in the aURIs array. aDoBatchNotify Obsolete since Gecko 9.0 If set to true, the BeginUpdateBatch and EndUpdateBatch events are sent; otherwise, no notification of changes to the history is provided. This parameter was removed in Gecko 9.0. removePagesByTimeframe() Removes all pages within the given timeframe, using a batch. void removePagesByTimeframe( in long long aBeginTime, in long long aEndTime ); Parameters aBeginTime The time of the first page to re...
...emove, in microseconds from epoch. aEndTime The time of the last page to remove, in microseconds from epoch. removePagesFromHost() This method removes all the pages from the given host. It is called from the UI when the user deletes a group associated with a host or domain. This method lets you delete pages from a specific host, or pages from all hosts in a given domain. If aEntireDomain is true, it will assume aHost is a domain, and remove all pages from the entire domain. void removePagesFromHost( in AUTF8String aHost, in boolean aEntireDomain ); Parameters aHost The name of the host to be removed. An empty value for this parameter means local files and anything else without a hostname. You can also pass in the localized "(local files)" title given to you by a history query ...
...in. void removePagesFromHost( in AUTF8String aHost, in boolean aEntireDomain ); Parameters aHost The name of the host to be removed. An empty value for this parameter means local files and anything else without a hostname. You can also pass in the localized "(local files)" title given to you by a history query to remove all history information for local files. aEntireDomain If set to true, it will assume aHost is a domain, and remove all pages from the entire domain, including subdomains. Set to false otherwise. removeVisitsByTimeframe() Removes all visits within the given timeframe, using a batch. Any pages that become unvisited as a result are also deleted. void removeVisitsByTimeframe( in long long aBeginTime, in long long aEndTime ); Parameters aBeginTime The tim...
nsIClipboardCommands
opySelection(); boolean canCutSelection(); boolean canPaste(); void copyImageContents(); void copyImageLocation(); void copyLinkLocation(); void copySelection(); void cutSelection(); void paste(); void selectAll(); void selectNone(); Methods canCopyImageContents() Returns whether we can copy an image's contents. boolean canCopyImageContents(); Parameters None. Return value true if an image is selected, false otherwise. canCopyImageLocation() Returns whether we can copy an image location. boolean canCopyImageLocation(); Parameters None. Return value true if an image is selected, false otherwise. canCopyLinkLocation() Returns whether we can copy a link location. boolean canCopyLinkLocation(); Parameters None. Return value true if a link is selected, false otherwise. can...
...eLocation(); Parameters None. Return value true if an image is selected, false otherwise. canCopyLinkLocation() Returns whether we can copy a link location. boolean canCopyLinkLocation(); Parameters None. Return value true if a link is selected, false otherwise. canCopySelection() Returns whether there is a selection and it is copyable. boolean canCopySelection(); Parameters None. Return value true if there is a selection, false otherwise. canCutSelection() Returns whether there is a selection and it is not read-only. boolean canCutSelection(); Parameters None. Return value true if the current selection can be cut, false otherwise. canPaste() Returns whether the current contents of the clipboard can be pasted and if the current selection is not read-only. boolean canPaste(); Parameters No...
...copyImageContents() Copy the contents of the selected image. void copyImageContents(); Parameters None. ...
nsIContentSecurityPolicy
s policy allows eval and eval-like functions such as setTimeout("code string", time). Calls to this may trigger violation reports when queried, so this value should not be cached. Read only. allowsInlineScript boolean Whether this policy allows in-page script. Calls to this may trigger violation reports when queried, so this value should not be cached. Read only. ...
... Methods permitsAncestry() Verifies ancestry as permitted by the policy. Calls to this may trigger violation reports when queried, so this value should not be cached. ...
...ng and fail-closed are disabled: Content Security Policy will only send reports, and not modify behavior. Methods permitsAncestry() Verifies ancestry as permitted by the policy. Calls to this may trigger violation reports when queried, so this value should not be cached. boolean permitsAncestry( in nsIDocShell docShell ); Parameters docShell Containing the protected resource. Return value true if the frame's ancestors are all permitted by policy. refinePolicy() Updates the policy currently stored in the Content Security Policy to be "refined" or tightened by the one specified in the string policyString. void refinePolicy( in AString policyString, in nsIURI selfURI ); Parameters policyString selfURI scanRequestData() Called after the Content Security Policy object is created to...
nsICookieManager2
string will be normalized to ASCII or ACE; any trailing dot will be stripped. To be a domain cookie, the host must have at least two subdomain parts (e.g. '.foo.com', not '.com'), otherwise an exception will be thrown. An empty string is acceptable (e.g. file:// URI's). aPath The path within the domain for which the cookie is valid. aName The cookie name. aValue The cookie data. aIsSecure true if the cookie should only be sent over a secure connection. aIsHttpOnly true if the cookie should only be sent to, and can only be modified by, an HTTP connection. aIsSession true if the cookie should exist for the current session only. aExpiry Holds the expiration date, in seconds since the epoch. Only relevant if aIsSession is false. cookieExists() Returns whether or not a matching coo...
... countCookiesFromHost() Returns the number of cookies that would be returned to a given host. This ignores the cookie flags isDomain, isSecure, and isHttpOnly. ...
...ow many cookies a given host has already set. This is useful when e.g. prompting the user whether to accept a given cookie. boolean findMatchingCookie( in nsICookie2 aCookie, out unsigned long aCountFromHost ); Parameters aCookie The cookie to look for. aCountFromHost The number of cookies found whose hosts are the same as, or subdomains of, the host field of aCookie. Return value true if a cookie was found which matches the host, path, and name fields of aCookie. getCookiesFromHost() Returns an enumerator of cookies that would be returned to a given host, ignoring the cookie flags isDomain, isSecure, and isHttpOnly. Therefore, if the specified host is "weather.yahoo.com", host or domain cookies for "weather.yahoo.com" and "yahoo.com" would both be returned, while a cookie fo...
nsIDOMNSHTMLDocument
xecCommand( in DOMString commandID, in boolean doShowUI, in DOMString value ); Parameters commandID The name of the command to execute. See Rich-Text Editing in Mozilla for a list of supported commands. doShowUI This is not implemented in Gecko. value Some commands require an argument. You can pass null for those commands that do not need an argument. Return value true if the command was recognized, false otherwise. execCommandShowHelp() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11) This method never did anything but throw an exception, and was removed entirely in Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11). boolean execCommandShowHelp( in DOMString commandID ); Parameters comman...
...f the type is not supported by the HTML content sink, trying to write to the document will probably throw. aReplace Whether the document should replace the existing document in session history. Return value The new document. queryCommandEnabled() boolean queryCommandEnabled( in DOMString commandID ); Parameters commandID The name of the command to query. Return value Returns true if the command is supported and enabled, false otherwise. queryCommandIndeterm() boolean queryCommandIndeterm( in DOMString commandID ); Parameters commandID The name of the command to query. Return value For stateful commands, returns true if the command is in an indeterminate state, false otherwise. For instance, if there is a selection and part of the selected text is bold, then t...
...commands, returns true if the command is in an indeterminate state, false otherwise. For instance, if there is a selection and part of the selected text is bold, then then bold command is in an indeterminate state. queryCommandState() boolean queryCommandState( in DOMString commandID ); Parameters commandID The name of the command to query. Return value For stateful commands, returns true if the command has is active, false otherwise. queryCommandSupported() boolean queryCommandSupported( in DOMString commandID ); Parameters commandID The name of the command to query. Return value Returns true if the command is supported on the current range, false otherwise. queryCommandText() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.1...
nsIDOMXULElement
iew void blur(); void click(); void doCommand(); void focus(); nsIDOMNodeList getElementsByAttribute(in DOMString name, in DOMString value); nsIDOMNodeList getElementsByAttributeNS(in DOMString namespaceURI, in DOMString name, in DOMString value); Attributes Attribute Type Description align DOMString Gets/sets the value of the element's align attribute. allowEvents boolean true if the element's allowevents attribute is the string "true", otherwise false. Removes the attribute if you set it to false. boxObject nsIBoxObject Read only. Gets or creates a box object for the element; browser, editor, iframe, listbox, menu, menupopup, scrollbox, tooltip and tree elements receive specialized box objects allowing access to additional properties not normally available from scri...
... browser, editor, iframe, listbox, menu, menupopup, scrollbox, tooltip and tree elements receive specialized box objects allowing access to additional properties not normally available from script. builder nsIXULTemplateBuilder Read only. Retrives the element's template builder, if it has a template. className DOMString Gets/sets the value of the element's class attribute. collapsed boolean true if the element's collapsed attribute is the string "true", otherwise false. Removes the attribute if you set it to false. contextMenu DOMString Gets/sets the value of the element's contextmenu attribute. controllers nsIControllers Read only. Returns an nsIControllers object that additional controllers may be appended to so as to provide focus-specific actions for commands. database nsIRDFCo...
...plate. datasources DOMString Gets/sets the value of the element's datasources attribute. dir DOMString Gets/sets the value of the element's dir attribute. flex DOMString Gets/sets the value of the element's flex attribute. flexGroup DOMString Gets/sets the value of the element's flexgroup attribute. height DOMString Gets/sets the value of the element's height attribute. hidden boolean true if the element's hidden attribute is the string "true", otherwise false. Removes the attribute if you set it to false. id DOMString Gets/sets the value of the element's id attribute. left DOMString Gets/sets the value of the element's left attribute. maxHeight DOMString Gets/sets the value of the element's maxheight attribute. maxWidth DOMString Gets/sets the value of the element's maxwid...
nsIEventListenerService
nal] out unsigned long aCount, [retval, array, size_is(aCount)] out nsIEventListenerInfo aOutArray ); Parameters aEventTarget The nsIEventTarget for which to obtain a list of listeners. aCount On return, the number of returned listener descriptors. aOutArray An array of nsIEventListenerInfo objects describing the listeners. hasListenersFor() Returns true if a event target has any listener for the given type. boolean hasListenersFor( in nsIDOMEventTarget aEventTarget, in DOMString aType ); Parameters aEventTarget The nsIDOMEventTarget for which to check if this has any listener for aType. aType An event name. addSystemEventListener() Add a system-group eventlistener to a event target. System-group eventlisteners...
... in system-group. void addSystemEventListener( in nsIDOMEventTarget target, in DOMString type, in nsIDOMEventListener listener, in boolean useCapture ); Parameters target The nsIDOMEventTarget for the event target to listen an event. type The event name to listen. listener The nsIDOMEventListener which listens the event. useCapture True if to listen the event in capture phase, otherwise, false. removeSystemEventListener() Remove a system-group eventlistener from a event target. void removeSystemEventListener( in nsIDOMEventTarget target, in DOMString type, in nsIDOMEventListener listener, in boolean useCapture ); Parameters target The nsIDOMEventTarget for the event target listening the event. ty...
... target. void removeSystemEventListener( in nsIDOMEventTarget target, in DOMString type, in nsIDOMEventListener listener, in boolean useCapture ); Parameters target The nsIDOMEventTarget for the event target listening the event. type The listening event name. listener The nsIDOMEventListener which is listening the event. useCapture True if listening the events in capture phase, otherwise, false. Remarks nsIEventListenerService was introduced with bug 448602. See also nsIEventListenerInfo nsIEventTarget ...
nsIExternalProtocolService
ers in either the nsIHandlerService datastore or registered with the OS. boolean externalProtocolHandlerExists( in string aProtocolScheme ); Parameters aProtocolScheme The scheme from a url: http, ftp, mailto, and so on. Note: aProtocolScheme should not include a trailing colon, which is part of the URI syntax, not part of the scheme itself. That is, pass "mailto" not "mailto:". Return value true if we have a handler and false otherwise. getApplicationDescription() Gets a human-readable description for the application responsible for handling a specific protocol. AString getApplicationDescription( in AUTF8String aScheme ); Parameters aScheme The scheme to look up. For example, "mms". Return value This code makes little sense and needs to be cleaned up. -Nickolay <pre> // first constr...
...If neither the application nor the OS knows about a handler for the protocol, the object this method returns will represent a default handler for unknown content. Note: AProtocolScheme should not include a trailing colon, which is part of the URI syntax, not part of t...
...be used internally by the application. For example, a non-exposed protocol would not be loaded by the application in response to a link click or a X-remote openURL command. Instead, it would be deferred to the system's external protocol handler. boolean isExposedProtocol( in string aProtocolScheme ); Parameters aProtocolScheme The scheme from a url: http, ftp, mailto, and so on. Return value true if the protocol is exposed, false otherwise. loadURI() Used to load a URI via an external application. Might prompt the user for permission to load the external application. void loadURI( in nsIURI aURI, [optional] in nsIInterfaceRequestor aWindowContext ); Parameters aURI The URI to load. aWindowContext The window to parent the dialog against, and, if a web handler is chosen, it is loaded ...
nsIFileView
;1. To create an instance, use: var fileView = Components.classes["@mozilla.org/filepicker/fileview;1"] .createInstance(Components.interfaces.nsIFileView); Method overview void setDirectory(in nsIFile directory); void setFilter(in AString filterString); void sort(in short sortType, in boolean reverseSort); Attributes Attribute Type Description reverseSort boolean If true results will be sorted in ascending order. Read only. selectedFiles nsIArray An nsIArray of selected files, which contains nsIArray instances. Read only. showHiddenFiles boolean If true hidden files will be shown. showOnlyDirectories boolean If true only directory entries will be returned. sortType short The current sort type in effect. Read only. Constants Constant Value Descriptio...
...o be browsed. setFilter() Set the filter to be applied to the file list, for example "*.jpg" would only return jpg files. void setFilter( in AString filterString ); Parameters filterString The filter to be applied to the file list. sort() Set the method used for sorting. void sort( in short sortType, in boolean reverseSort ); Parameters sortType One of the sort* constants. reverseSort true, results will be sorted in ascending order. Example <?xml version="1.0" ?> <?xml-stylesheet href="chrome://global/skin/" type="text/css" ?> <window id="test" title="Test" width="640" height="480" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <tree flex="1" id="ftree"> <treecols> <-- The default Column type is size unless an appropriate id...
... id="test" title="Test" width="640" height="480" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <tree flex="1" id="ftree"> <treecols> <-- The default Column type is size unless an appropriate id is passed, nsIFileView relies on the treecols section --> <treecol id="FilenameColumn" label="Name" flex="1" primary="true"/> <treecol id="LastModifiedColumn" label="Date" flex="1"/> <treecol id="Size" label="Size" flex="1"/> </treecols> <treechildren/> </tree> <script> var DIR="/home/"; //The directory to be opened var ftree = document.getElementById("ftree"); //The XUL tree element var lfile = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILoca...
nsIFocusManager
usedElementForWindow() nsIDOMElement getFocusedElementForWindow( in nsIDOMWindow aWindow, in PRBool aDeep, out nsIDOMWindow aFocusedWindow ); Parameters aWindow If equal to the current value of focusedWindow, then the returned element will be the application-wide focused element (the value of focusedElement). The return value will be null if no element is focused. aDeep If true, then child frames are traversed and the return value may be the element within a child descendant window that is focused. 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. This will be set even if no element is focused. Return value...
...be 0, FLAG_BYMOUSE or FLAG_BYKEY. moveCaretToFocus() Moves the selection caret within aWindow to the current focus. void moveCaretToFocus( in nsIDOMWindow aWindow ); Parameters aWindow elementIsFocusable() Check if given element is focusable. boolean elementIsFocusable(in nsIDOMElement aElement, in unsigned long aFlags); Parameters aElement aFlags Return value True if aElement is focusable. moveFocus() Move the focus to another element. If aStartElement is specified, then movement is done relative to aStartElement. If aStartElement is null, then movement is done relative to the currently focused element. If no element is focused, focus the first focusable element within the document (or the last focusable element if aType is MOVEFOCUS_END). This met...
...ndow aWindow ); Parameters aWindow Native code only!windowRaised Called when a window has been raised. void windowRaised( in nsIDOMWindow aWindow ); Parameters aWindow Native code only!windowShown Called when a new document in a window is shown. void windowShown( in nsIDOMWindow aWindow, in PRBool aNeedsFocus ); Parameters aWindow aNeedsFocus If true, then focus events are expected to be fired on the window if this window is in the focused window chain. ...
nsIInputStream
NS_BASE_STREAM_CLOSED If the stream is closed normally. close() Close the stream. This method causes subsequent calls to read() and readSegments() to return 0 bytes read to indicate end-of-file. Note: The close method may be called more than once, but subsequent calls are ignored. void close(); Parameters None. isNonBlocking() boolean isNonBlocking(); Parameters None. Return value true if stream is non-blocking. Native code only!read This method copies data from the stream into a buffer. unsigned long read( in charPtr aBuf, in unsigned long aCount ); Parameters aBuf The buffer into which the data from the stream is copied. aCount The size of the buffer, or the maximum number of bytes to copy from the stream. Return value This method returns the number of bytes...
...tream. Return value This method returns the number of bytes copied from the stream (may be less than aCount). It returns 0 to indicate end-of-file. Exceptions thrown <other-error> On failure. NS_BASE_STREAM_WOULD_BLOCK Indicates that reading from the input stream would block the calling thread for indeterminate amount of time. This exception may only be thrown if isNonBlocking() returns true. Native code only!readSegments This method provides direct access to the stream's internal buffer. Note: A nsIInputStream is not required to implement this method. In some contexts, readSegments may be guaranteed to be implemented, but in general it is not. This method serves as an optimization. unsigned long readSegments( in nsWriteSegmentFun aWriter, in voidPtr aClosure, in unsigned ...
...eturns 0 to indicate end-of-file. Exceptions thrown <other-error> On failure. NS_ERROR_NOT_IMPLEMENTED Indicates that the stream does not have an internal buffer that can be accessed directly. NS_BASE_STREAM_WOULD_BLOCK Indicates that reading from the input stream would block the calling thread for indeterminate amount of time. This exception may only be thrown if isNonBlocking() returns true. Example Consume all data from an input stream using read(). nsresult ConsumeStream(nsIInputStream* aStream) { nsresult rv; uint32_t numRead; char buf[512]; while (1) { rv = aStream->Read(buf, sizeof(buf), &numRead); if (NS_FAILED(rv)) { printf("### error reading stream: %x\n", rv); break; } if (numRead == 0) break; // buf now contains num...
nsIJumpListBuilder
stBuild(); Parameters None. addListToBuild() Adds a list and if required, a set of items for the list. boolean addListToBuild( in short aCatType, in nsIArray items, Optional in AString catName Optional ); Parameters aCatType The type of list to add. items Optional An array of nsIJumpListItem items to add to the list. catName Optional For custom lists, the title of the list. Return value true if the operation completed successfully. Exceptions thrown NS_ERROR_UNEXPECTED On internal errors. NS_ERROR_ILLEGAL_VALUE If an item is added that was removed since the last commit. NS_ERROR_INVALID_ARG If incorrect parameters are passed for a particular category or item type. commitListBuild() Commits the current jump list build to the Taskbar. boolean commitListBuild(); Parameters None. Retu...
...peration completed successfully. Exceptions thrown NS_ERROR_UNEXPECTED On internal errors. NS_ERROR_ILLEGAL_VALUE If an item is added that was removed since the last commit. NS_ERROR_INVALID_ARG If incorrect parameters are passed for a particular category or item type. commitListBuild() Commits the current jump list build to the Taskbar. boolean commitListBuild(); Parameters None. Return value true if the operation completed successfully. deleteActiveList() Deletes any currently applied taskbar jump list for this application. Common uses would be the enabling of a privacy mode and uninstallation. boolean deleteActiveList(); Parameters None. Return value true if the operation completed successfully. Exceptions thrown NS_ERROR_UNEXPECTED On internal errors. initListBuild() Initializes a ju...
... ...
nsILoginManager
The number of logins matching the parameters passed. fillForm() Fills out a form with login information, if appropriate information is available. Note: This method will attempt to fill out the form regardless of the setting of the signon.autofillForms preference. boolean fillForm( in nsIDOMHTMLFormElement aForm ); Parameters aForm The HTMLform to attempt to fill out. Return value true if the form was successfully filled out; otherwise false. findLogins() Searches for logins matching the specified criteria. Called when looking for logins that might be applicable to a given form or authentication request. void findLogins( out unsigned long count, in AString aHostname, in AString aActionURL, in AString aHttpRealm, [retval, array, size_is(count)] out nsILoginInfo logi...
...is method from JavaScript like this: var logins = myLoginMgr.getAllLogins({}); getLoginSavingEnabled() Reports whether or not saving login information is enabled for a host. boolean getLoginSavingEnabled( in AString aHost ); Parameters aHost The hostname to check. This argument should be in the origin URL format, with no pathname. For example: "https://www.site.com". Return value true if login saving is enabled for the host, otherwise false. modifyLogin() Modifies an existing login by replacing it with a new one. If newLoginData is a nsILoginInfo, all of the old login's nsILoginInfo properties are changed to the values from newLoginData (but the old login's nsILoginMetaInfo properties are unmodified). If newLoginData is a nsIPropertyBag, only the specified properties will ...
...ost. When login storing is disabled, the Login Manager won't prompt the user to store logins for that host. Existing logins are not affected. void setLoginSavingEnabled( in AString aHost, in boolean isEnabled ); Parameters aHost The hostname to adjust the setting for. This argument should be in the origin URL format, with no pathname. For example: "https://www.site.com". isEnabled If true, login saving is enabled for the specified host. If false, login saving is disabled. See also nsILoginInfo Using nsILoginManager ...
nsILoginManagerStorage
Read only. Methods addLogin() Called by the Login Manager to store a new login. Gecko 1.9.1 note Default values for the nsILoginMetaInfo properties are created if the specified login doesn't explicitly specify them. void addLogin( in nsILoginInfo aLogin ); Parameters aLogin The login to add to the login storage. countLogins() Implement ...
... must be an empty array, not null. getLoginSavingEnabled() Implement to report whether or not login saving has been disabled for a specific host. boolean getLoginSavingEnabled( in AString aHost ); Parameters aHost The hostname whose login saving status should be returned. This string will be in the origin URL format, without a pathname. For example, "http://mozilla.com". Return value Return true if login saving is enabled for the specified host; otherwise, return false. init() Implement this method to initialize the component. This is not called automatically; you must call it yourself if needed. void init(); Parameters None. initWithFile() Implement this method to initialize the component, overriding the default filename locations with those specified. This method is primarily used for...
...Manager will not propt the user for permission to store logins for that host. Existing logins for the host should not be affected when setting this. void setLoginSavingEnabled( in AString aHost, in boolean isEnabled ); Parameters aHost The host for which to enable or disable login saving. The argument is in origin URL format, without a pathname (for example: "http://mozilla.com"). isEnabled true if logins should be enabled for the host, or false if they should be disabled. Remarks For methods returning count, JavaScript callers can simply use the length property on the returned array to find out how many logins were returned in the array, for example: var logins = pwmgr.searchLogins({}, matchData); var numLogins = logins.length; See also Creating a Login Manager storage module nsILogin...
nsIMsgSearchCustomTerm
name; needsBody /// Does this term need the message body? readonly attribute boolean needsBody; Methods getEnabled /** * Is this custom term enabled? * * @param scope search scope (nsMsgSearchScope) * @param op search operator (nsMsgSearchOp). If null, determine * if term is available for any operator. * * @return true if enabled */ boolean getEnabled(in nsMsgSearchScopeValue scope, in nsMsgSearchOpValue op); getAvailable /** * Is this custom term available? * * @param scope search scope (nsMsgSearchScope) * @param op search operator (nsMsgSearchOp). If null, determine * if term is available for any operator. * * @re...
... boolean getEnabled(in nsMsgSearchScopeValue scope, in nsMsgSearchOpValue op); getAvailable /** * Is this custom term available? * * @param scope search scope (nsMsgSearchScope) * @param op search operator (nsMsgSearchOp). If null, determine * if term is available for any operator. * * @return true if available */ boolean getAvailable(in nsMsgSearchScopeValue scope, in nsMsgSearchOpValue op); getAvailableOperators /** * List the valid operators for this term. * * @param scope search scope (nsMsgSearchScope) * @param length object to hold array length * * @return array of operators */ void getAvailableOperat...
...array, size_is(length)] out nsMsgSearchOpValue operators); match /** * Apply the custom search term to a message * * @param msgHdr header database reference representing the message * @param searchValue user-set value to use in the search * @param searchOp search operator (Contains, IsHigherThan, etc.) * * @return true if the term matches the message, else false */ boolean match(in nsIMsgDBHdr msgHdr, in AUTF8String searchValue, in nsMsgSearchOpValue searchOp); ...
nsINavHistoryQuery
t the currently loaded reference points + offset resolve to. absoluteEndTime PRTime Read only: Retrieves the end time value that the currently loaded reference points + offset resolve to. annotation AUTF8String The annotation name. annotationIsNot boolean Test for existance or non-existance of a given annotation. We don't currently support >1 annotation name per query. If annotationIsNot is true, we test for the non-existance of the specified annotation. Testing for not annotation will do the same thing as a normal query and remove everything that doesn't have that annotation. Asking for things that DO have a given annotation is a little different. It also includes things that have never been visited. This allows place queries to be returned (which might include bookmark folders -- use t...
...e, it will return anything whose host name ends in domain. This one is a little different than most. Setting it to an empty string is a real query and will match any URI that has no host name (local files and such). Set this to NULL (in C++ use SetIsVoid) if you don't want domain matching. domainIsHost boolean This controls the meaning of domain, and whether it is an exact match domainIsHost = true, or hierarchical (= false). endTime PRTime End time range for results (INCLUSIVE). endTimeReference long One of the constants TIME_RELATIVE_* which indicates how to interpret the corresponding end time value. folderCount long Read only: Count of folders. hasAnnotation boolean Read only: Whether or not, annotation exists. hasBeginTime boolean Read only: Whether or not, the corresponding ...
...urned. When called as a getter, this returns an array of strings sorted in ascending lexicographical (alphabetical) order. This array may be empty, in which case no filtering by tags is performed. To search for items that are tagged with any given tags instead of all, multiple queries may be passed to the nsINavHistoryService method nsINavHistoryService.executeQueries(). tagsAreNot boolean If true, the results include only items that are not tagged with the specified tags. If false, only tags in the tags list are included in the results. uri nsIURI This is a URI to match, to, for example, find out every time you visited a given URI. Use uriIsPrefix to control whether this is an exact match. uriIsPrefix boolean Controls the interpretation of uri. When unset (default), the URI will reque...
nsIPlacesImportExportService
alFile indicating where to save the new bookmarks.html file. importHTMLFromFile() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11) Note: This method has been removed; use the BookmarkHTMLUtils.jsm JavaScript code module instead. 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). Three nsIObserverService notifications are fired as a result of the import. "bookmarks-restore-begin" is fired just before the import is started. "bookmarks-restore-success" is fired right after the bookmarks are successfully imported. "bookmarks-restore-failed" is fired right after a failure occurs when importing the bookmarks. Observers will be pa...
...port. "bookmarks-restore-begin" is fired just before the import is started. "bookmarks-restore-success" is fired right after the bookmarks are successfully imported. "bookmarks-restore-failed" is fired right after a failure occurs when importing the bookmarks. Observers will be passed through their data parameters either "html" if aIsInitialImport is false or "html-initial" if aIsInitialImport is true. The observer subject will be null. void importHTMLFromFile( in nsILocalFile aFile, in boolean aIsInitialImport ); Parameters aFile The HTML file to import into Places. aIsInitialImport Whether this is an initial import or not. importHTMLFromFileToFolder() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11) Note: This method has b...
...port. "bookmarks-restore-begin" is fired just before the import is started. "bookmarks-restore-success" is fired right after the bookmarks are successfully imported. "bookmarks-restore-failed" is fired right after a failure occurs when importing the bookmarks. Observers will be passed through their data parameters either "html" if aIsInitialImport is false or "html-initial" if aIsInitialImport is true. The observer subject will be an nsISupportsPRInt64 whose value is aFolder. void importHTMLFromFileToFolder( in nsILocalFile aFile, in PRInt64 aFolder, in boolean aIsInitialImport ); Parameters aFile The file to import. aFolder The ID of the bookmarks folder into which to import the bookmarks. aIsInitialImport Whether or not this is an initial import. importHTMLFromURI() Obs...
Component; nsIPrefBranch
oot" prefbranch and calling addObserver("foo.bar.", ...) will observe changes to foo.bar.baz and foo.bar.bzip. aObserver The object to be notified if the preference changes. The structure of aObserver is any object with an observe function. See nsIObserver and here is a quick snippet: var myObserver = { observe: function(aSubject, aTopic, aData) { //do stuff here } } aHoldWeak true holds a weak reference to aObserver. The object must implement the nsISupportsWeakReference interface or this will fail. false holds a strong reference to aObserver. clearUserPref() Called to clear a user set value from a specific preference. This will, in effect, reset the value to the default value. If no default value exists the preference will cease to exist. Note: This method does nothin...
... value, then the preference no longer has a user set value, i.e. it is considered reset to its default value. In particular, this method will return false for such a preference and the preference will not be saved to a file by nsIPrefService.savePrefFile(). boolean prefHasUserValue( in string aPrefName ); Parameters aPrefName The preference to be tested. Return value Returns boolean - true The preference has a user set value. false The preference only has a default value. prefIsLocked() Called to check if a specific preference is locked. If a preference is locked calling its Get method will always return the default value. Note: This method can be called on either a default or user branch but, in effect, always operates on the default branch. boolean prefIsLocked( in string a...
...Called to check if a specific preference is locked. If a preference is locked calling its Get method will always return the default value. Note: This method can be called on either a default or user branch but, in effect, always operates on the default branch. boolean prefIsLocked( in string aPrefName ); Parameters aPrefName The preference to be tested. Return value Returns boolean - true The preference is locked. false The preference is not locked. removeObserver() Remove a preference change observer. Note: You must call removeObserver method on the same nsIPrefBranch instance on which you called addObserver method in order to remove aObserver; otherwise, the observer will not be removed. void removeObserver( in string aDomain, in nsIObserver aObserver ); Para...
nsIProcessScriptLoader
wDelayedLoad) void removeDelayedProcessScript(in AString aURL); jsval getDelayedProcessScripts(); loadProcessScript() Load a script in the child process. Process scripts are loaded as soon as loadProcessScript() is called. If this function is called on a ChromeMessageBroadcaster, : it will load the process script into all child processes. if aAllowDelayedLoad is true, then the script will also be loaded into any new child processes created after the loadProcessScript() call. Otherwise it will only be loaded into child processes that exist at the time of the call. If this function is called on a ChromeMessageSender: it will load the process script only into this ChromeMessageSender's child process aAllowDelayedLoad should always be true. It's possible th...
...aURL must be the absolute URL. data: URLs are also supported. ...
...ameters Name Type Description aURL String URL for the script to load. aURL must be the absolute URL. data: URLs are also supported. 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. If this flag is true, the process script will be loaded into any new child processes created after the loadProcessScript() call, until removeDelayedProcessScript() is called for that script. If you are calling loadProcessScript() on a ChromeMessageSender, you should always pass true here. removeDelayedProcessScript() Removes aURL from the list of scripts which support delayed load. This cancels the ...
nsIPropertyBag
rown NS_ERROR_FAILURE If a property with that name doesn't exist. Examples Get User Agent Information (Operating System Specifics. The window scope is not always accessible so the window.navigator cannot be accessed. ...
...bled:true doNotTrack:"yes" geolocation:Geolocation language:"en-US" mimeTypes:MimeTypeArray mozAlarms:null mozApps:XPCWrappedNative_NoHelper mozCameras:CameraManager mozConnection:MozConnection mozContacts:ContactManager mozId:null mozKeyboard:XPCWrappedNative_NoHelper mozPay:null mozPermissionSettings:null mozPhoneNumberService:PhoneNumberService mozPower:MozPowerManager mozTCPSocket:null onLine:true oscpu:"Windows NT 5.1" platform:"Win32" plugins:PluginArray product:"Gecko" productSub:"20100101" userAgent:"Mozilla/5.0 (Windows NT 5.1; rv:30.0) Gecko/20100101 Firefox/30.0" vendor:"" vendorSub:"" __proto__:NavigatorPrototype From here we can easily see the Operating System version. Services.appinfo.OS simply tells us WINNT only, this is not helpful to differentiate between Windows XP, Vista, ...
...ersion. Services.appinfo.OS simply tells us WINNT only, this is not helpful to differentiate between Windows XP, Vista, 7, etc. 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. Also pay attention to their platform-specific meaning (e.g. on Android there is version and kernel_version). ...
nsISelection
table, the caret will blink there. void collapseToEnd(); Parameters None collapseToStart() Collapses the whole selection to a single point at the start of the current selection (regardless of direction). If content is focused and editable, the caret will blink there. void collapseToStart(); containsNode() Indicates whether the nsIDOMNode is part of the selection. If partlyContained is set to PR_TRUE, the function returns true when some part of the node is part of the selection. If partlyContained is set to PR_FALSE, the function only returns true when the entire node is part of the selection. boolean containsNode( in nsIDOMNode node, in boolean partlyContained ); Parameters node The nsIDOMNode to look for partlyContained If partlyContained is set to PR_FALSE, the functi...
... Return value Whether or not the range contains the requested noe. deleteFromDocument() Deletes this selection from the document the nodes belong to. void deleteFromDocument(); extend() Extends the selection by moving the selection end to the specified nsIDOMNode and offset, preserving the selection begin position. ...
...AllChildren() Adds all children of the specified node to the selection. void selectAllChildren( in nsIDOMNode parentNode ); Parameters parentNode The parent of the children to be added to the selection. selectionLanguageChange() Modifies the cursor Bidi level after a change in keyboard direction. 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. toString() Returns the whole selection into a plain text string. DOMString toString(); Remarks See also ...
nsITreeColumn
st); Native code only! nsITreeColumn getNext(); nsITreeColumn getPrevious(); void invalidate(); Attributes Attribute Type Description atom nsIAtom The atom attribute of nsITreeColumn which returns an nsIAtom for the column, making it fast to do comparisons. Read only. Native code only! columns nsITreeColumns The nsITreeColumns containing this column. Read only. cycler boolean If true, then the column is a cycler column. If the cycler attribute is not set, the column cells are regular text cells. Read only. editable boolean If true the nsITreeColumn content is editable. If the editable attribute is not set, the column cells are not editable. Read only. element nsIDOMElement The treecol element. Read only. id AString The id attribute of the nsITreeColumn. Read only. in...
...If the selectable attribute is not set, the column cells are not selectable. Read only. type short The type of the column, see constants. ...
...If the selectable attribute is not set, the column cells are not selectable. Read only. ...
nsIURI
nsIURI cloneIgnoringRef(); Parameters None. Return value An nsIURI object that represents the same URI as the current nsIURI without the 'ref' attribute. equals() Compares the current URI with another URI. Note: This is more than a string comparison, as two different URI strings can represent the same location. For example, comparing "http://foo.com:80/" and "http://foo.com/" will return true. boolean equals( in nsIURI other ); Parameters other Another nsIURI to compare to. Return value true if the two URIs represent the same location; otherwise false. equalsExceptRef() Compares the current URI with another URI, ignoring the value of the .ref member. Note: This is more than a string comparison, as two different URI strings can represent the same location. For example, c...
... if the two URIs represent the same location; otherwise false. equalsExceptRef() Compares the current URI with another URI, ignoring the value of the .ref member. Note: This is more than a string comparison, as two different URI strings can represent the same location. For example, comparing "http://foo.com/#" and "http://foo.com/" or "http://foo.com/#aaa" and "http://foo.com/#bbb" will return true. boolean equalsExceptRef( in nsIURI other ); Parameters other Another nsIURI to compare to. Return value true if the two URIs represent the same location; otherwise false. resolve() Resolves a relative URI string, using this URI as the base. Note: Some implementations may have no concept of a relative URI. AUTF8String resolve( in AUTF8String relativePath ); Parameters relat...
...hether the nsIURI represents a URI with the specified scheme. This comparison is case-insensitive. Note: This is an optimization, allowing you to check the scheme of the URI without having to get the scheme and do the comparison yourself; this saves memory allocations. boolean schemeIs( in string scheme ); Parameters scheme A string representing the scheme to compare to. Return value true if the URI is for the specified scheme; otherwise false. See also Code snippets:URI parsing ...
nsIWindowMediator
Below will be ignored for zLevelTop and zLevelBottom.) inBelow If inPosition is set to zLevelBelow, the window below which inWindow wants to be placed. Otherwise this variable is ignored. outPosition Constrained position, values like inPosition. outBelow The window below which inWindow should be placed, if outPosition equals zLevelBelow. Otherwise this value will be null. Return value PR_TRUE if the position returned is different from the position given. getEnumerator() Return an enumerator which iterates over all windows of type aWindowType from the oldest window to the youngest. nsISimpleEnumerator getEnumerator( in wstring aWindowType ); Parameters aWindowType The returned enumerator will enumerate only windows of this type. ("type" is the |windowtype| attribute of the X...
...visited if windows are re-ordered while z-order enumerators are active. nsISimpleEnumerator getZOrderDOMWindowEnumerator( in wstring aWindowType, in boolean aFrontToBack ); Parameters aWindowType The returned enumerator will enumerate only windows of this type. ("type" is the |windowtype| attribute of the XML <window> element.) If null, all windows will be enumerated. aFrontToBack If true, the enumerator enumerates windows in order from front to back. Back to front if false. Return value An enumerator of nsIDOMWindows. This method may not work on Linux or Mac (bug 462222) nor on OS2 (bug 370134) - please check those bugs before relying on it. More information can be found by searching mxr for BROKEN_WM_Z_ORDER) getZOrderXULWindowEnumerator() Identical to getZOrderDOMWindo...
...rderDOMWindowEnumerator() except returns an enumerator of nsIXULWindow. nsISimpleEnumerator getZOrderXULWindowEnumerator( in wstring aWindowType, in boolean aFrontToBack ); Parameters aWindowType The returned enumerator will enumerate only windows of this type. ("type" is the |windowtype| attribute of the XML <window> element.) If null, all windows will be enumerated. aFrontToBack If true, the enumerator enumerates windows in order from front to back. Back to front if false. Return value An enumerator of nsIXULWindows. Native code only!registerWindow Add the window to the list of known windows. Listeners (see addListener()) will be notified through their onOpenWindow method. void registerWindow( in nsIXULWindow aWindow ); Parameters aWindow The window to add. remov...
nsIWindowsRegKey
dex of the requested value. Return value The name of the n'th value under this key. getValueType() This method returns the type of the value with the given name. unsigned long getValueType( in AString name ); Parameters name The name of the value to query. Return value One of the "TYPE_" constants. hasChanged() boolean hasChanged(); Parameters None. 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. hasChild() This method checks to see if the key has a child by the given name. boolean hasChild( in AString name ); Parameters name The name of the requested child key. Return value true if the key has a child by the given name. hasValue() This method checks to see if t...
...see if the key has a child by the given name. boolean hasChild( in AString name ); Parameters name The name of the requested child key. Return value true if the key has a child by the given name. hasValue() This method checks to see if the key has a value by the given name. boolean hasValue( in AString name ); Parameters name The name of the requested value. Return value true if the key has a value by the given name. isWatching() This method returns true if the key is being watched for changes (that is, if startWatching() was called). boolean isWatching(); Parameters None. Return value true if the key is being watched for changes. open() This method opens an existing key. This method fails if the key does not exist. Note: On 32-bit Windows, it is valid to pass any HK...
...The relative path from this key to the key to be removed. removeValue() This method removes the value with the given name. void removeValue( in AString name ); Parameters name The name of the value to be removed. startWatching() This method starts watching the key to see if any of its values have changed. The key must have been opened with mode including ACCESS_NOTIFY. If recurse is true, then this key and any of its descendant keys are watched. Otherwise, only this key is watched. void startWatching( in boolean recurse ); Parameters recurse Indicates whether or not to also watch child keys. stopWatching() This method stops any watching of the key initiated by a call to startWatching(). This method does nothing if the key is not being watched. void stopWatching(); P...
nsIXMLHttpRequest
from C++, unless you're aware of all the security implications. And then think twice about it. ...
...you only want this if your url is to a zip file or some file you want to download and make a nsIArrayBufferInputStream out of it...
...you only want this if your url is to a zip file or some file you want to download and make a nsIArrayBufferInputStream out of it or something xhr.send(null...
nsIXPCScriptable
Implementations may skip writing to *_retval unless they want to return PR_FALSE. js/src/xpconnect/idl/nsIXPCScriptable.idlNot scriptable Please add a summary to this article. ...
...ate. JSENUMERATE_DESTROY This function should destroy the opaque iterator state previously allocated in statep by this function when enum_op was JSENUMERATE_INIT. statep An in/out pointer to a jsval whose meaning depends on the value of enum_op. idp An in/out pointer to a jsid whose meaning depends on the value of enum_op. Return value This should (although does not need to) return PR_TRUE to indicate success or must return PR_FALSE to indicate failure. newResolve() This method is called when the WANT_NEWRESOLVE flag is set. When this method is called, XPConnect is attempting to resolve a lazy property named by id on obj. The JS engine will check if the property named by id is defined after this method has been called. This is very similar to JSNewResolveOp. If an implementation ...
...ssed as a jsval. flags The flags that describe the access to the property named by id. See JS_LookupProperty for the flags and their meaning. objp An out parameter that, on success, points to the JSObject that the property named by id has been defined on. If the property named by id was not defined, this should be set to NULL. Return value This should (although does not need to) return PR_TRUE to indicate success or must return PR_FALSE to indicate failure. convert() PRBool convert( in nsIXPConnectWrappedNative wrapper, in JSContextPtr cx, in JSObjectPtr obj, in PRUint32 type, in JSValPtr vp ); Parameters wrapper cx obj type vp Return value finalize() void finalize( in nsIXPConnectWrappedNative wrapper, in JSContextPtr cx, in JSObjectPtr obj ...
Mail and RDF
ges. Eventually we'll probably hang mail filters, annotations, etc, off of nodes in the graph. Here is an example of how this might be set up: In this tree-style representation of an RDF graph, I've made arcs italic and resources bold. ...
...ome.netscape.com/NC-rdf#MessageChild --> | | imap_message://alecf@imap.mywork.com/INBOX#3 | +-- http://home.netscape.com/NC-rdf#MessageChild --> | imap_message://alecf@imap.mywork.com/INBOX#4 | etc... ...
... resource named mailbox://alecf@pop.myisp.com/INBOX and the property node is named http://home.netscape.com/NC-rdf#TotalMessages. This is basically what happens, behind the scenes: var target = RDF.GetResource("mailbox://alecf@pop.myisp.com/INBOX"); var property = RDF.GetResource("http://home.netscape.com/NC-rdf#TotalMessages"); var resultNode = dataSource.GetTarget(target, property, true); In the folder datasource's GetTarget(), target would be QueryInterfaced to a nsIMsgFolder. To get the total messages, the datasource would then call nsIMsgFolder.GetTotalMessages(). Finally, it would convert the result of this call to an RDF Literal, and pass it back through the return parameter of GetTarget(). An example of how this might work inside the datasource: var msgCountArc...
Using tab-modal prompts
Even if you set it to the browser window ("var theWindow = window") the modal alert will be shown in the current tab. From then on, you can use the nsIPrompt object, prompt, as usual. For example: var factory = Components.classes["@mozilla.org/prompter;1"] .getService(Components.interfaces.nsIPromptFactory); var prompt = factory.getPr...
...hen on, you can use the nsIPrompt object, prompt, as usual. For example: var factory = Components.classes["@mozilla.org/prompter;1"] .getService(Components.interfaces.nsIPromptFactory); var prompt = factory.getPrompt(gBrowser.contentWindow, Components.interfaces.nsIPrompt); var bag = prompt.QueryInterface(Components.interfaces.nsIWritablePropertyBag2); bag.setPropertyAsBool("allowTabModal", true); var promptArgs = ["Devmo Alert", "OMG! An alert!"]; prompt.alert.apply(null, promptArgs); nsIPrompt will automatically fall back to window-modal prompts when necessary (such as in situations in which tab-modal prompts aren't supported, or for prompts displayed outside the context of a tab).le To use other forms of the prompts of nsIPromptService interface see the Example Code. Then apply it,...
...re we apply the prompt with a checkbox: var window = gBrowser.contentWindow; var promptfact = Components.classes['@mozilla.org/prompter;1'].getService(Components.interfaces.nsIPromptFactory); var prompt = promptfact.getPrompt(window, Components.interfaces.nsIPrompt); var promptbag = prompt.QueryInterface(Components.interfaces.nsIWritablePropertyBag2); promptbag.setPropertyAsBool('allowTabModal', true); var check = {value: false}; //initial state of checkbox, however if no text is supplied the checkbox is not shown var input = {value: 'pre filled value'}; var ok = prompt.prompt.apply(null, ['Title - but not shown in tab modal', 'Text goes here', input, 'Check text, if no text, checkbox is not shown', check]); //this here is just an alert, showing the values of the prompt prompt.alert.apply(...
Plug-in Basics - Plugins
ment in a document, it attempts to find and display the file represented by the data and src attributes, respectively. The height and width attributes of the object element determine the size of the embedded plug-in in the HTML page. For example, this object element calls a plug-in that displays video: <object data="newave.avi" type="video/avi" width="320" height="200" autostart="true" loop="true"> </object> A hidden plug-in is a type of embedded plug-in that is not drawn on the screen when it is invoked. It is created by using the hidden attribute of the embed element. Here's an example: <embed src="audiplay.aiff" type="audio/x-aiff" hidden="true"> Note: Whether a plug-in is windowed or windowless is not meaningful if the plug-in is invoked with the hidden attribute. ...
...GIF or JPEG images are, except that a plug-in can be live and respond to user events, such as mouse clicks. 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" > ... </embed> You must include either the src attribute or the type attribute in an embed element. If you do not, then there is no way of determining the media type, and so no plug-in loads. The src attribute is the URL of the file to run. The type attribute specifies the MIME type o...
... attributes to the plug-in, allowing the plug-in to examine the list for any private attributes that could modify its behavior. For example, a plug-in that displays video could have private attributes that determine whether to start the plug-in automatically or loop the video automatically on playback, as in the following embed element: <embed src="myavi.avi" width="100" height="125" autostart="true" loop="true"> With this embed element, Gecko passes the values to the plug-in, using the arg parameters of the NPP_New call that creates the plug-in instance. argc = 5 argn = {"src", "width", "height", "autostart", "loop"} argv = {"movie.avi", "100", "125", "true", "true"} Gecko interprets the attributes as follows: src: Load the data file and determine the MIME type of the data. width...
Version, UI, and Status Information - Plugins
ess method finds out whether the current version of the API supports windowless plug-ins. This method for detecting support is only useful on MS Windows and Mac OS X. It starts by using NPN_Version to get the version numbers. It then uses the netscape_minor version number to find out if the windowless feature, represented by the NPVERS_HAS_WINDOWLESS constant, is supported. If the method returns true, a windowless plug-in can confidently proceed. If false is returned, windowless plug-ins will not work, and the developer must provide alternatives. Bool has_windowless() { int plugin_major, plugin_minor; int netscape_major, netscape_minor; /* Find the version numbers. */ NPN_Version(&plugin_major, &plugin_minor, &netscape_major, &netscape_minor); /* Use the netscape_minor...
...e netscape_minor version number: */ /* Does this version support the windowless feature? */ if (netscape_minor < NPVERS_HAS_WINDOWLESS) { /* Plug-in is running in a version of the Navigator */ /* that does not support windowless plug-ins. */ 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...
... << PreviousNext >> ...
Debugger.Environment - Firefox Developer Tools
nt instances protect their referents from the garbage collector; as long as the Debugger.Environment instance is live, the referent remains live. Garbage collection has no visible effect on Debugger.Environment instances. Accessor Properties of the Debugger.Environment Prototype Object A Debugger.Environment instance inherits the following accessor properties from its prototype: inspectable True if this environment is a debuggee environment, and can therefore be inspected. False otherwise. All other properties and methods of Debugger.Environment instances throw if applied to a non-inspectable environment. type The type of this environment object, one of the following values: "declarative", indicating that the environment is a declarative environment record. Function calls, c...
...have object properties that provide the object whose properties they reflect as variable bindings. callee If this environment represents the variable environment (the top-level environment within the function, which receives var definitions) for a call to a functionf, then this property's value is a Debugger.Object instance referring tof. Otherwise, this property's value is null. optimizedOut True if this environment is optimized out. False otherwise. For example, functions whose locals are never aliased may present optimized-out environments. When true, getVariable returns an ordinary JavaScript object whose optimizedOut property is true on all bindings, and setVariable throws a ReferenceError. Function Properties of the Debugger.Environment Prototype Object The methods described below...
...name.Name must be a string that is a valid ECMAScript identifier name. The result is a debuggee value. JavaScript engines often omit variables from environments, to save space and reduce execution time. If the given variable should be in scope, but getVariable is unable to produce its value, it returns an ordinary JavaScript object (not a Debugger.Object instance) whose optimizedOut property is true. This is not an invocation function; if this call would cause debuggee code to run (say, because the environment is a "with" environment, andname refers to an accessor property of the with statement's operand), this call throws a Debugger.DebuggeeWouldRun exception. setVariable(name,value) Storevalue as the value of the variable bound toname in this environment.Name must be a string that ...
Debugger.Frame - Firefox Developer Tools
ible frames When inspecting the call stack, Debugger does not reveal all the frames that are actually present on the stack: while it does reveal all frames running debuggee code, it omits frames running the debugger's own code, and omits most frames running non-debuggee code. We call those stack frames a Debugger does reveal visible frames. A frame is a visible frame if any of the following are true: it is running debuggee code; its immediate caller is a frame running debuggee code; or it is a "debugger" frame, representing the continuation of debuggee code invoked by the debugger. The "immediate caller" rule means that, when debuggee code calls a non-debuggee function, it looks like a call to a primitive: you see a frame for the non-debuggee function that was accessible t...
...in WebAssembly baseline JIT. this The value of this for this frame (a debuggee value). For a wasmcall frame, this property throws a TypeError. older The next-older visible frame, in which control will resume when this frame completes. If there is no older frame, this is null. depth The depth of this frame, counting from oldest to youngest; the oldest frame has a depth of zero. 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. script The script being executed in this frame (a Debugger.Script instance), or null on frames that do not represent calls to debuggee code. On frames whose callee property is not null, this is equal to callee.script. offset The offset of the bytecod...
...ypeError. environment The lexical environment within which evaluation is taking place (a Debugger.Environment instance), or null on frames that do not represent the evaluation of debuggee code, like calls non-debuggee functions, host functions or "debugger" frames. callee The function whose application created this frame, as a debuggee value, or null if this is not a "call" frame. 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. arguments The arguments passed to the current frame, or null if this is not a "call" frame. When non-null, this is an object, allocated in the same global as the debugger, with Array.prototype on its prototype chain, a non-writable length property, a...
Intensive JavaScript - Firefox Developer Tools
t the top of the stack is a function called calculatePrimes(), and we can see its filename and line number. ...
...lity for each number in a separate function: function doPointlessComputationsWithRequestAnimationFrame() { function testCandidate(index) { // finishing condition if (index == iterations) { console.log(primes); pointlessComputationsButton.disabled = false; return; } // test this number var candidate = index * (multiplier * Math.random()); var isPrime = true; for (var c = 2; c <= Math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isPrime = false; break; } } if (isPrime) { primes.push(candidate); } // schedule the next var testFunction = testCandidate.bind(this, index + 1); window.requestAnimationFrame(testFunction); } var primes = []; var testFunctio...
...The code that actually performs t...
about:debugging - Firefox Developer Tools
ion to your remote device. This Firefox Provides information about temporary extensions you have loaded for debugging, extensions that are installed in Firefox, the tabs that you currently have open, and service workers running on Firefox. If your about:debugging page is different from the one displayed here, go to about:config, find and set the option devtools.aboutdebugging.new-enabled to true. Setup tab Connecting to a remote device Firefox supports debugging over USB with Android devices, using the about:debugging page. Before you connect: Enable Developer settings on your Android device. Enable USB debugging in the Android Developer settings. Enable Remote Debugging via USB in the Advanced Settings in Firefox on the Android device. Connect the Android device to your comput...
...rkers, Shared Workers, and Other Workers There are three sections on this page that deal with Service Workers, Shared Workers, and Other Workers. Whether internal extensions appear in the list on this page depends on the setting of the devtools.aboutdebugging.showHiddenAddons preference. If you need to see these extensions, navigate to about:config and make sure that the preference is set to true. Extensions Loading a temporary extension With the Load Temporary Add-on button you can temporarily load a web extension from a directory on disk. Click the button, navigate to the directory containing the add-on and select its manifest file. The temporary extension is then displayed under the Temporary Extensions header. You don't have to package or sign the extension before loading it, and ...
...for Android Nightly If you prefer to test with the main release of Firefox for Android (i.e., based on release 68), you can do so with the desktop Firefox Extended Support Release (ESR), which is also based on version 68. Note that about:debugging is not enabled by default in Firefox ESR. To enable it, open the Configuration Editor (about:config) and set devtools.aboutdebugging.new-enabled to true. If you used a higher version of Firefox prior to installing Firefox ESR, you will be prompted to create a new user profile, in order to protect your user data. For more information, see What happens to my profile if I downgrade to a previous version of Firefox? ...
Attr - Web APIs
Web › API › Attr
ualified name of the attribute. prefix Read only A DOMString representing the namespace prefix of the attribute, or null if no prefix is specified. ownerElement Read only The element holding the attribute. Note: DOM Level 4 removed this property. The assumption was that since you get an Attr object from an Element, you should already know the associated element. As that doesn't hold true in cases like Attr objects being returned by Document.evaluate, the DOM Living Standard reintroduced the property. Gecko outputs a deprecation note starting from Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4). This note was removed again in Gecko 49.0 (Firefox 49.0 / Thunderbird 49.0 / SeaMonkey 2.46). specified Read only This property always returns true. Originally, it retur...
...cases like Attr objects being returned by Document.evaluate, the DOM Living Standard reintroduced the property. Gecko outputs a deprecation note starting from Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4). This note was removed again in Gecko 49.0 (Firefox 49.0 / Thunderbird 49.0 / SeaMonkey 2.46). specified Read only This property always returns true. Originally, it returned true if the attribute was explicitly specified in the source code or by a script, and false if its value came from the default one defined in the document's DTD. value The attribute's value. Note: DOM Level 3 defined namespaceURI, localName and prefix on the Node interface. In DOM4 they were moved to Attr. This change is implemented in Chrome since version 46.0 and Firefox since version 48.0. ...
...s NULL. previousSibling This property now always returns NULL. schemaTypeInfo Read only The type information associated with this attribute. While the type information contained in this attribute is guaranteed to be correct after loading the document or invoking Document.normalizeDocument, this property may not be reliable if the node was moved. specified This property now always returns true. textContent Use Attr.value instead. The following methods have been deprecated: appendChild() Obsolete since Gecko 14 Modify the value of Attr.value instead. cloneNode() You shouldn't have been using this in the first place, so you probably don't care that this is going away. createAttribute() Use Element.setAttribute() instead. createAttributeNS() Use Element.setAttributeNS() inst...
AudioBufferSourceNode.loop - Web APIs
The loop property of the AudioBufferSourceNode interface is a Boolean indicating if the audio asset must be replayed when the end of the AudioBuffer is reached. 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. When looping is enabled, the sound begins playing at the time specified as the start point when start() is called. When the time specified by the loopEnd property is reached, playback continues at the time specified by loopStart Example In this example, the AudioContext.decodeAudioData function is used to decode an audio track and put it into an AudioBufferSourceNode. Buttons are provided to play and ...
...nto an AudioBufferSourceNode. Buttons are provided to play and stop the audio playback, and a slider control is used to change the playbackRate property value on the fly. When the audio is played, it loops. ...
...request.open('GET', 'viper.ogg', true); request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { myBuffer = buffer; source.buffer = myBuffer; source.playbackRate.value = playbackControl.value; source.connect(audioCtx.destination); source.loop = true; }, function(e){"Error with decoding audio data" + e.err}); } request.send(); } // wire up buttons to stop and play audio, and range slider control play.onclick = function() { getData(); source.start(0); play.setAttribute('disabled', 'disabled'); playbackControl.removeAttribute('disabled'); } Specification Specification Status Comment Web...
AudioBufferSourceNode.loopEnd - Web APIs
The loopEnd property of the AudioBufferSourceNode interface specifies is a floating point number specifying, in seconds, at what offset into playing the AudioBuffer playback should loop back to the time indicated by the loopStart property. This is only used if the loop property is true. Syntax AudioBufferSourceNode.loopEnd = endOffsetInSeconds; var endOffsetInSeconds = AudioBufferSourceNode.loopEnd; Value A floating-point number indicating the offset, in seconds, into the audio buffer at which each loop will loop return to the beginning of the loop (that is, the current play time gets reset to AudioBufferSourceNode.loopStart). This property is only used if the loop property is true. The default value is 0. Example In this example, the AudioContext.decodeAudioData() function is used...
... the 25 second mark. Then the current play position will loop back to the 20 second mark and continue playing until the 25 second mark, ad infinitum (or at least until stop() is called). For a full working example, see this code running live, or view the source. ...
... loopstartControl.oninput = function() { source.loopStart = loopstartControl.value; loopstartValue.innerHTML = loopstartControl.value; } loopendContr...
AudioBufferSourceNode.loopStart - Web APIs
ffer the restart of the play must happen. The loopStart property's default value is 0. Syntax AudioBufferSourceNode.loopStart = startOffsetInSeconds; startOffsetInSeconds = AudioBufferSourceNode.loopStart; Value A floating-point number indicating the offset, in seconds, into the audio buffer at which each loop should begin during playback. This value is only used when the loop parameter is true. Example In this example, the AudioContext.decodeAudioData() function is used to decode an audio track and put it into an AudioBufferSourceNode. Buttons are provided to play and stop the audio playback, and slider controls are used to change the playbackRate, loopStart, and loopEnd properties on the fly. When the audio is played to the end, it loops, but you can control how long the loops last...
...the loops last by altering loopStart and loopEnd. For example, if you set their values to 20 and 25, respectively, the audio will start to loop between 20 and 25 seconds in to the track. For a full working example, see this code running live, or view the source. ...
... loopstartControl.oninput = function() { source.loopStart = loopstartControl.value; loopstartValue.innerHTML = loopstartControl.value; } loopendContr...
Cache.delete() - Web APIs
Web › API › Cache › delete
The delete() method of the Cache interface finds the Cache entry whose key is the request, and if found, deletes the Cache entry and returns a Promise that resolves to true. If no Cache entry is found, it resolves to false. Syntax cache.delete(request, {options}).then(function(found) { // your cache entry has been deleted if found }); Parameters request The Request you are looking to delete. This can be a Request object or a URL. options Optional An object whose properties control how matching is done in the delete operation. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. If set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. It defaul...
...l An object whose properties control how matching is done in the delete operation. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. If set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. 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. ignoreVary: A Boolean that, when set to true, tells the matching operation not to perform VARY header matching. In other words, if the URL matches you will get a match regardless of whether the Response object has a VARY header. It defaults to false. cacheNam...
... Examples caches.open('v1').then(function(cache) { cache.delete('/images/image.png').then(function(response) { someUIUpdateFunction(); }); }) Specifications Specification Status Comment Service WorkersThe definition of 'Cache: delete' in that specification. ...
CacheStorage.has() - Web APIs
Web › API › CacheStorage › has
Examples The following example first checks whether a cache called 'v1' exists. If so, we add a list of assets to it. If not then we run some kind of cache set-up function. ...
... Examples The following example first checks whether a cache called 'v1' exists. If so, we add a list of assets to it. If not then we run some kind of cache set-up function. ...
... Examples The following example first checks whether a cache called 'v1' exists. If so, we add a list of assets to it. If not then we run some kind of cache set-up function. ...
ChildNode.after() - Web APIs
Web › API › ChildNode › after
argItem : document.createTextNode(String(argItem))); }); ...
...argItem : document.createTextNode(String(argItem))); }); this.parentNode.insertB...
...argItem : document.createTextNode(String(argItem))); }); this.parentNode.insertBefore(docFrag, this.ne...
ChildNode.before() - Web APIs
Web › API › ChildNode › before
argItem : document.createTextNode(String(argItem))); }); ...
...argItem : document.createTextNode(String(argItem))); }); this.parentNode.insert...
...argItem : document.createTextNode(String(argItem))); }); this.parentNode.insertBefore(docFrag, this);...
ChildNode.remove() - Web APIs
Web › API › ChildNode › remove
Living Standard Initial definition. ...
... Living Standard Initial definition. ...
... Living Standard Initial definition. ...
DOMImplementation.hasFeature() - Web APIs
Syntax const flag = document.implementation.hasFeature(feature, version); Parameters feature A DOMString representing the feature name. version A DOMString representing the version of the specification defining the feature. ...
... Syntax const flag = document.implementation.hasFeature(feature, version); Parameters feature A DOMString representing the feature name. version A DOMString representing the version of the specification defining the feature. ...
...implementation.hasFeature(feature, version); Parameters feature A DOMString representing the feature name. version A DOMString representing the version of the specification defining the feature. Specifications Specification Status Comment DOMThe definition of 'DOMImplementation.hasFeature' in that specification. Living Standard Modified to always return true except for SVG features. Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'DOMImplementation.hasFeature' in that specification. Obsolete No change from Document Object Model (DOM) Level 2 Core Specification Document Object Model (DOM) Level 2 Core SpecificationThe definition of 'DOMImplementation.hasFeature' in that specification. Obsolete No c...
Element.getAnimations() - Web APIs
this element or which are scheduled to do so in future. It can optionally return Animation objects for descendant elements too. Note: This array includes CSS Animations, CSS Transitions, and Web Animations. Syntax const animations = Element.getAnimations(options); Parameters options Optional An options object containing the following property: subtree A boolean value which, if true, causes animations that target descendants of Element to be returned as well. This includes animations that target any CSS pseudo-elements attached to Element or one of its descendents. Defaults to false. Return value An Array of Animation objects, each representing an animation currently targetting the Element on which this method is called, or one of its descendant elements if { subtree:...
... causes animations that target descendants of Element to be returned as well. This includes animations that target any CSS pseudo-elements attached to Element or one of its descendents. Defaults to false. ...
...alue An Array of Animation objects, each representing an animation currently targetting the Element on which this method is called, or one of its descendant elements if { subtree: true } is specified. Examples The following code snippet will wait for all animations on elem and its descendants to finish before removing the element from the document. Promise.all( elem.getAnimations({ subtree: true }) .map(animation => animation.finished) ).then(() => elem.remove()); Specifications Specification Status Comment Web AnimationsThe definition of 'Animatable.getAnimations()' in that specification. Working Draft Editor's draft. ...
Element: paste event - Web APIs
The paste event is fired when the user has initiated a "paste" action through the browser's user interface. Bubbles Yes Cancelable Yes Interface ClipboardEvent Event handler property onpaste If the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to true) then the default action is to insert the contents of the clipboard into the document at the cursor position. A handler for this event can access the clipboard contents by calling getData() on the event's clipboardData property. To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventDefault(...
...vior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventDefault(), and then insert its desired data manually. It's possible to construct and dispatch a synthetic paste event, but this will not affect the document's contents. ...
...d contents) an event handler must cancel the default action using event.preventDefault(), and then insert its desired data manually. It's possible to construct and dispatch a synthetic paste event, but this will not affect the document's contents. ...
Element.toggleAttribute() - Web APIs
Parameters name A DOMString specifying the name of the attribute to be toggled. The attribute name is automatically converted to all lower-case when toggleAttribute() is called on an HTML element in an HTML document. force Optional A boolean value to determine whether the attribute should be added or removed, no matter whether the attribute is present or not at the moment. Return value true if attribute name is eventually present, and false otherwise. Exceptions InvalidCharacterError The specified attribute name contains one or more characters which are not valid in attribute names. Example In the following example, toggleAttribute() is used to toggle the readonly attribute of a <input>. HTML <input value="text"> <button>toggleAttribute("readonly")</button> JavaScript va...
... Living Standard ...
... Living Standard ...
Event.composed - Web APIs
Web › API › Event › composed
The read-only composed property of the Event interface returns a Boolean which indicates whether or not the event will propagate across the shadow DOM boundary into the standard DOM. Note: This property was formerly named scoped. Syntax const isComposed = Event.composed; Value A Boolean which is true if the event will cross from the shadow DOM into the standard DOM after reaching the shadow root. (That is, the first node in the shadow DOM in which the event began to propagate.) All UA-dispatched UI events are composed (click/touch/mouseover/copy/paste, etc.). Most other types of events are not composed, and so will return false. For example, this includes synthetic events that are created without their composed option wil set to true. Propagation only occurs if the bubbles property i...
...at is, the first node in the shadow DOM in which the event began to propagate.) All UA-dispatched UI events are composed (click/touch/mouseover/copy/paste, etc.). Most other types of events are not composed, and so will return false. For example, this includes synthetic events that are created without their composed option wil set to true. Propagation only occurs if the bubbles property is also true. However, capturing only composed events are also handled at host as if they were in AT_TARGET phase. You can determine the path the event will follow through the shadow root to the DOM root by calling composedPath(). If this value is false, the shadow root will be the last node to be offered the event. Examples In our composed-composed-path example (see it live), we define two trivial custom ...
...sed-shadow text="I have a closed shadow root"></closed-shadow> Then include a click event listener on the <html> element: document.querySelector('html').addEventListener('click',function(e) { console.log(e.composed); console.log(e.composedPath()); }); When you click on the <open-shadow> element and then the <closed-shadow> element, you'll notice two things. The composed property returns true beause the click event is always able to propagate across shadow boundaries. You'll notice a difference in the value of composedPath for the two elements. The <open-shadow> element's composed path is this: Array [ p, ShadowRoot, open-shadow, body, html, HTMLDocument https://mdn.github.io/web-components-examples/composed-composed-path/, Window ] Whereas the <closed-shadow> element's composed ...
Event.eventPhase - Web APIs
Web › API › Event › eventPhase
rs registered for this phase are called at this time. If Event.bubbles is false, processing the event is finished after this phase is complete. Event.BUBBLING_PHASE 3 The event is propagating back up through the target's ancestors in reverse order, starting with the parent, and eventually reaching the containing Window. This is known as bubbling, and occurs only if Event.bubbles is true. Event listeners registered for this phase are triggered during this process. For more details, see section 3.1, Event dispatch and DOM event flow, of the DOM Level 3 Events specification. Example HTML <h4>Event Propagation Chain</h4> <ul> <li>Click 'd1'</li> <li>Analyse event propagation chain</li> <li>Click next div and repeat the experience</li> <li>Change Capturing mode</li>...
...ElementById('divInfo') divs = document.getElementsByTagName('div') chCapture = document.getElementById('chCapture') chCapture.onclick = function () { RemoveListeners() AddListeners() } Clear() AddListeners() } function RemoveListeners() { for (let i = 0; i < divs.length; i++) { let d = divs[i] if (d.id != "divInfo") { d.removeEventListener("click", OnDivClick, true) d.removeEventListener("click", OnDivClick, false) } } } function AddListeners() { for (let i = 0; i < divs.length; i++) { let d = divs[i] if (d.id != "divInfo") { if (chCapture.checked) { d.addEventListener("click", OnDivClick, true) } else { d.addEventListener("click", OnDivClick, false) d.onmousemove = function ...
..."none" : e.eventPhase == 1 ? "capturing" : e.eventPhase == 2 ? "target" : e.eventPhase == 3 ? "bubbling" : "error"; divInfo.innerHTML += e.currentTarget...
GamepadEvent - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 22 Full support 22 No support 15 -- 21Prefixed Prefixed Implemented with the vendor prefix: webkitSafari Full support ...
...To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 22Safari Full support 10.1WebView Android No support NoChrome Android Full support Y...
...To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 22 Full support 22 No support 15 -- 21Prefixed Prefixed Implemented with the vendor prefix: webkitSafari Full support ...
HTMLElement.hidden - Web APIs
This is quite different from using the CSS property display to control the visibility of an element. The hidden property applies to all presentation modes and should not be used to hide content that is meant to be directly accessible to the user. ...
...s reused by other parts of the page in a template-like fashion Creating an offscreen canvas as a drawing buffer Inappropriate use cases include: Hiding panels in a tabbed dialog box Hiding content in one presentation while intending it to be visible in others Elements that are not hidden must not link to elements which are. 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. Example Here's an example where a hidden block is used to contain a thank you message that is displayed after a user agrees to an unusual request. JavaScript document.getElementById("okButton") .addEventListener("click", function() { document.getElementById("welcome").hidden =...
... HTML The HTML for the two boxes are shown here. ...
HTMLImageElement.sizes - Web APIs
dia queries. Syntax let sizes = htmlImageElement.sizes; htmlImageElement.sizes = sizes; Value A USVString containing a comma-separated list of source size descriptors followed by an optional fallback size. Each source size descriptor is comprised of a media condition, then at least one whitespace character, then the source size value to use for the image when the media condition evaluates to true. Media conditions Each source size descriptor consists of a media condition as defined by the media queries standard. Because a source size descriptor is used to specify the width to use for the image during layout of the page, the media condition is typically (but not necessarily) based entirely on width information. See Syntax in Using media queries for details on how to construct a media con...
...To change preferences in Firefox, visit about:config.IE No support NoOpera Full support YesSafari No support NoWebView Android Full support 45Chrome Android Full support 45...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS No support NoSamsung Internet Android Full support 5.0Legend Full support Full support ...
HTMLInputElement - Web APIs
n (willvalidate is false), or it satisfies its constraints. This value can be set by the setCustomValidity method. willValidate Read only Boolean: Returns whether the element is a candidate for constraint validation. 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. Properties that apply only to elements of type checkbox or radio checked Boolean: Returns / Sets the current state of the element when type is checkbox or radio. defaultChecked Boolean: Returns / Sets the default state of a radio button or checkbox as originally specified in HTML that created this object. indeterminate Boolean: Returns whether the chec...
...dard Directory Upload API; indicates whether or not to allow directories and files both to be selected in the file list. Implemented only in Firefox and is hidden behind a preference. files Returns/accepts a FileList object, which contains a list of File objects representing the files selected for upload. webkitdirectory Boolean: Returns the webkitdirectory attribute; if true, the file system picker interface only accepts directories instead of files. webkitEntries Array of FileSystemEntry objects: Describes the currently selected files or directories. Properties that apply only to text/number-containing or elements autocomplete string: Returns / Sets the element's autocomplete attribute, indicating whether the value of the control ca...
...ts a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. checkValidity() Returns a Boolean that is false if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an invalid event at the element. It returns true if the element is not a candidate for constraint validation, or if it satisfies its constraints. reportValidity() Runs the checkValidity() method, and if it returns false (for an invalid input or no pattern attribute provided), then it reports to the user that the input is invalid in the same manner as if you submitted a form. HTMLInputElement.stepDown() Decrements the value...
IDBKeyRange.lower - Web APIs
Web › API › IDBKeyRange › lower
The lower read-only property of the IDBKeyRange interface returns the lower bound of the key range. Note: This feature is available in Web Workers. Syntax var lower = myKeyRange.lower Value The lower bound of the key range (can be any type.) Example The following example illustrates how you'd use a key range. Here we declare keyRangeValue = IDBKeyRange.upperBound("F", "W", true, true); -- a range that includes everything between "F" and "W" but not including them -- since both the upper and lower bounds have been declared as open (true). We open a transaction (using IDBTransaction) and an object store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. After declaring the key range, we log its lower property value to the consol...
...rsor, declaring keyRangeValue as its optional key range value. After declaring the key range, we log its lower property value to the console, which should appear as "F". ...
...declaring keyRangeValue as its optional key range value. After declaring the key range, we log its lower property value to the console, which should appear as "F". ...
IDBKeyRange.upper - Web APIs
Web › API › IDBKeyRange › upper
The upper read-only property of the IDBKeyRange interface returns the upper bound of the key range. Note: This feature is available in Web Workers. Syntax var upper = myKeyRange.upper Value The upper bound of the key range (can be any type.) Example The following example illustrates how you'd use a key range. Here we declare keyRangeValue = IDBKeyRange.upperBound("F", "W", true, true); -- a range that includes everything between "F" and "W" but not including them -- since both the upper and lower bounds have been declared as open (true). We open a transaction (using IDBTransaction) and an object store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. After declaring the key range, we log its upper property value to the consol...
...rsor, declaring keyRangeValue as its optional key range value. After declaring the key range, we log its upper property value to the console, which should appear as "W". ...
...declaring keyRangeValue as its optional key range value. After declaring the key range, we log its upper property value to the console, which should appear as "W". ...
KeyboardEvent.initKeyEvent() - Web APIs
keyCodeArg, charCodeArg) Parameters type Is a DOMString representing the type of event. bubbles Is a Boolean indicating whether the event should bubble up through the event chain or not (see bubbles). cancelable Is a Boolean i indicating whether the event can be canceled (see cancelable). viewArg Specifies the UIEvent.view; this value may be null. ...
...dicating whether the event should bubble up through the event chain or not (see bubbles). cancelable Is a Boolean i indicating whether the event can be canceled (see cancelable). viewArg Specifies the UIEvent.view; this value may be null. ctrlKeyArg Is a Boolean that is true if the virtual key to be generated is a combination of keys containing the Ctrl key. altKeyArg Is a Boolean that is true if the virtual key to be generated is a combination of keys containing the Alt key. shiftKeyArg A Boolean that is true if the virtual key to be generated is a combination of keys containing the Shift key. metaKeyArg Is a Boolean that is true if the virtual key to be generated is a combination of keys containing the Meta key. keyCodeArg Is a unsigned long representing the virtual key code va...
... key code value of the key which was depressed, otherwise 0. See KeyboardEvent.keyCode for the list of key codes. charCodeArg Is a unsigned long representingthe Unicode character associated with the depressed key otherwise 0. Example var event = document.createEvent('KeyboardEvent'); // create a key event // define the event event.initKeyEvent("keypress", // typeArg, true, // canBubbleArg, true, // cancelableArg, null, // viewArg, Specifies UIEvent.view. This value may be null. false, // ctrlKeyArg, false, // altKeyArg, false, // shiftKeyArg, false, // metaKeyArg, ...
KeyboardEvent.key - Web APIs
Web › API › KeyboardEvent › key
pre-determined sequence. For a given key press, the sequence of KeyboardEvents fired is as follows assuming that Event.preventDefault is not called: A keydown event is first fired. If the key is held down further and the key produces a character key, then the event continues to be emitted in a platform implementation dependent interval and the KeyboardEvent.repeat read only property is set to true. If the key produces a character key that would result in a character being inserted into possibly an <input>, <textarea> or an element with HTMLElement.contentEditable set to true, the beforeinput and input event types are fired in that order. Note that some other implementations may fire keypress event if supported. The events will be fired repeatedly while the key is held down. A keyup event...
...d the key property value for the event is set to be the string @ for the U.S keyboard type and " for the UK keyboard type, because of the active modifier shift key. The beforeinput and inputbeforeinput and input events are fired next because a character key has been produced. As we keep holding the key, the keydown event continues to fire repeatedly and the KeyboardEvent.repeat property is set to true. The beforeinput and input events are fired repeatedly as well. As we release the shift key, a keyup event is fired for it, and the key attribute value remains Shift. At this point, notice that the key property value for the repeating keydown event of the key 2 key press is now "2" because the modifier shift key is no longer active. The same goes for the InputEvent.data property of the beforeinp...
...ey press. break; case "Enter": // Do something for "enter" or "return" key press. break; case "Esc": // IE/Edge specific value case "Escape": // Do something for "esc" key press. break; default: return; // Quit when this doesn't handle the key event. } // Cancel the default action to avoid it being handled twice event.preventDefault(); }, true); Specification Specification Status Comment UI EventsThe definition of 'KeyboardEvent.key' in that specification. Working Draft Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.key' in that specification. Obsolete Initial definition, included key values. ...
MediaCapabilitiesInfo - Web APIs
whether encoding or decoding such media would be smooth and power efficient. Properties The MediaCapabilitiesInfo interface contains three Boolean attribues: supported: Given the properties defined in the MediaConfiguration, can the specified piece of media content be encoded (if MediaEncodingConfiguration is set) or decode (if MediaDecodingConfiguration is set) at all? If yes, supported is true. Otherwise, it is false. smooth: Given the properties defined in the MediaConfiguration, will the playback of the specified piece of media be high quality? Will it be smooth? If supported is true, and playback will be smooth, smooth is true, Otherwise, is it false. powerEfficient: Given the properties defined in the MediaConfiguration, will the playback of the specified piece of media be power...
... Browsers will report a supported media configuration as smooth and powerEfficient until stats on this device have been recorded. ...
... Browsers will report a supported media configuration as smooth and powerEfficient until stats on this device have been recorded. All supported audio codecs are reported to be power efficient. ...
active - Web APIs
Example In this example, a new stream whose source is the user's local camera and microphone is requested using getUserMedia(). ...
... Example In this example, a new stream whose source is the user's local camera and microphone is requested using getUserMedia(). ...
...ve; otherwise, the value is false. Example In this example, a new stream whose source is the user's local camera and microphone is requested using getUserMedia(). When that stream becomes available (that is, when the returned Promise is fulfilled, a button on the page is updated based on whether or not the stream is currently active. var promise = navigator.mediaDevices.getUserMedia({ audio: true, video: true }); promise.then(function(stream) { var startBtn = document.querySelector('#startBtn'); startBtn.disabled = stream.active; };) Specifications Specification Status Comment Media Capture and StreamsThe definition of 'active' in that specification. Candidate Recommendation Initial definition. ...
MediaStreamConstraints.video - Web APIs
The MediaStreamConstraints dictionary's video property is used to indicate what kind of video track, if any, should be included in the MediaStream returned by a call to getUserMedia(). To learn more about how constraints work, see Capabilities, constraints, and settings. Syntax var videoConstraints = true | false | MediaTrackConstraints; Value The value of the video property can be specified as either of two types: Boolean If a Boolean value is specified, it simply indicates whether or not a video track should be included in the 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. MediaTrackConstraints A constrai...
...e, the call to getUserMedia() will fail. If false, no video track is included. MediaTrackConstraints A constraints dictionary detailing the preferable and/or required values or ranges of values for the track's constrainable properties. If you specify constraints, a video track meeting these constraints is required. Examples Using a Boolean value In this example, we provide a simple value of true for the video property. This tells getUserMedia() that we require a video track, but we don't care about any specifics beyond that. HTML content <p>Click the start button below to begin the demonstration.</p> <div id="startButton" class="button"> Start </div> <video id="video" width="160" height="120" autoplay></video><br> <div id="log"></div> CSS content body { font: 14px "Open Sans", "...
... Result Using a MediaTrackConstraints object Now let's lo...
Transcoding assets for Media Source Extensions - Web APIs
lt ffmpeg does not include libfdk_aac due to licensing reasons. Bento4 uses this by default, so you need to compile ffmpeg if necessary. If you don't need it, add --audio-codec=aac to the mp4-dash-encode.py command line. Container and Codec Support As specified in section 1.1 of the MSE spec: Goals, MSE is designed not to require support for any particular media format or codec. ...
...While the MIME type is fairly simple to figure out, we can get the codec string using the mp4info utility. ...
...rue on paper, browser support varies for specific container/codec combinations. To check if the browser supports a particular container, you can pass a string of the MIME type to the MediaSource.isTypeSupported method: MediaSource.isTypeSupported('audio/mp3'); // false MediaSource.isTypeSupported('video/mp4'); // true MediaSource.isTypeSupported('video/mp4; codecs="avc1.4D4028, mp4a.40.2"'); // true The string is the MIME type of the container, optionally followed by a list of codecs. While the MIME type is fairly simple to figure out, we can get the codec string using the mp4info utility. Currently, MP4 containers with H.264 video and AAC audio codecs have support across all modern browsers, while others don't. To convert our sample media from a QuickTime MOV container to an MP4 containe...
MutationObserver.observe() - Web APIs
Error Thrown in any of the following circumstances: The options are configured such that nothing will actually be monitored. (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). Usage notes Reusing MutationObservers You can call observe() multiple times on the same MutationObserver to watch for changes to different parts of the DOM tree and/or different types of changes. There ar...
... Living Standard ...
... Living Standard ...
MutationObserver - Web APIs
Array of MutationRecord objects. Mutation Observer & customize resize event listener & demo https://codepen.io/webgeeker/full/YjrZgg/ Example The following example was adapted from this blog post. ...
...Record objects. Mutation Observer & customize resize event listener & demo https://codepen.io/webgeeker/full/YjrZgg/ Example The following example was adapted from this blog post. ...
... Mutation Observer & customize resize event listener & demo https://codepen.io/webgeeker/full/YjrZgg/ Example The following example was adapted from this blog post. ...
MutationObserverInit.attributeOldValue - Web APIs
The MutationObserverInit dictionary's optional attributeOldValue property is used to specify whether or not to record the prior value of the altered attribute in MutationRecord objects denoting attribute value changes. Syntax var options = { attributeOldValue: true | false } Value A Boolean value indicating whether or not the prior value of a changed attribute should be included in the MutationObserver.oldValue property when reporting attribute value changes. If true, oldValue is set accordingly. If false, it is not. When using attributeOldValue, setting the attributes option to true is optional. Example In this example, a Mutation Observer is set up to watch for changes to the status and username attributes in any elements contained within a subtree that displays the names of users...
...For any items representing an attribute change (which can be detected by the value of MutationRecord.type being "attributes"), a function called notifyUser() is used to tell the user the name of the attribute ...
...For any items representing an attribute change (which can be detected by the value of MutationRecord.type being "attributes"), a function called notifyUser() is used to tell the user the name of the attribute that changed as well as the...
MutationObserverInit.characterDataOldValue - Web APIs
The MutationObserverInit dictionary's optional characterDataOldValue property is used to specify whether or not the MutationRecord.oldValue property for DOM mutations should be set to the previous value of text nodes which changed. If you set the MutationObserverInit.characterData property to true but don't set characterDataOldValue to true as well, the MutationRecord will not include information describing the prior state of the text node's contents. ...
...e MutationObserverInit.characterData property to true but don't set characterDataOldValue to true as well, the MutationRecord will not include information describing the prior state of the text node's contents. Character data changes are detectable on any text node, including nodes based on the Text, ProcessingInstruction, and Comment interfaces. 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. By default, only changes to the text of the node specified as the target parameter when you called observe() are monitored. To watch for changes to the text contents ...
...r 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. By default, only changes to the text of the node specified as the target parameter when you called observe() are monitored. To watch for changes to the text contents of all descendants of target, set the subtree option to true. If you set characterDataOldValue to true, characterData is automatically assumed to be true, even if you don't expressly set it as such. Example Specifications Specification Status Comment DOMThe definition of 'MutationObserverInit.characterDataOldValue' in that specification. Living Standard ...
MutationObserverInit.childList - Web APIs
The MutationObserverInit dictionary's optional childList property indicates whether or not to monitor the specified node or nodes for the addition or removal of new child nodes. If childList is false (the default), adding or removing new nodes does not trigger mutation callbacks. By setting childList to true, your callback will be invoked any time nodes are added to or removed from the DOM node or nodes being watched. ...
...erty indicates whether or not to monitor the specified node or nodes for the addition or removal of new child nodes. If childList is false (the default), adding or removing new nodes does not trigger mutation callbacks. By setting childList to true, your callback will be invoked any time nodes are added to or removed from the DOM node or nodes being watched. ...
...ed to or removed from the DOM node or nodes being watched. Syntax var options = { childList: true | false } Value A Boolean value indicating whether or not to invoke the callback function when new nodes are added to or removed from the section of the DOM being monitored.. If subtree is false, only the node indicated by the observer's target node is monitored for changes. Setting subtree to true causes addition or removal of nodes anywhere within the subtree rooted at target to be reported. Example Specifications Specification Status Comment DOMThe definition of 'MutationObserverInit.childList' in that specification. Living Standard ...
Node.cloneNode() - Web APIs
Web › API › Node › cloneNode
de() method returns a duplicate of the node on which this method was called. Syntax let newClone = node.cloneNode([deep]) node The node to be cloned. newClone The new node, cloned from node. The newClone has no parent and is not part of the document, until it is added to another node that is part of the document (using Node.appendChild() or a similar method). deep Optional* If true, then node and its whole subtree--including text that may be in child Text nodes--is also copied. If false, only node will be cloned. Any text that node contains is not cloned, either (since text is contained by one or more child Text nodes). deep has no effect on empty elements (such as the <img> and <input> elements). *Note: In the DOM4 specification (since Gecko 13.0 (Firefox 13 / Thun...
... Text nodes--is also copied. If false, only node will be cloned. Any text that node contains is not cloned, either (since text is contained by one or more child Text nodes). deep has no effect on empty elements (such as the <img> and <input> elements). *Note: In the DOM4 specification (since Gecko 13.0 (Firefox 13 / Thunderbird 13 / SeaMonkey 2.10)), the optional deep argument defaults to true. This behavior has been changed in the latest spec! Although deep it still optional, it now defaults to false. You should always provide an explicit value for backward and forward compatibility. With Gecko 28.0 (Firefox 28 / Thunderbird 28 / SeaMonkey 2.25 / Firefox OS 1.3)), the console warned developers not to omit the argument. Starting with Gecko 29.0 (Firefox 29 / Thunderbird 29 ...
...ue for backward and forward compatibility. With Gecko 28.0 (Firefox 28 / Thunderbird 28 / SeaMonkey 2.25 / Firefox OS 1.3)), the console warned developers not to omit the argument. Starting with Gecko 29.0 (Firefox 29 / Thunderbird 29 / SeaMonkey 2.26)), a shallow clone is defaulted instead of a deep clone. Example let p = document.getElementById("para1") let p_prime = p.cloneNode(true) Notes Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties (e.g., node.onclick = someFunction). Additionally, for a <canvas> element, the painted image is not copied. Warning: cloneNode() may lead to duplicate element IDs in a document! If...
Node.isConnected - Web APIs
Web › API › Node › isConnected
The isConnected read-only property of the Node interface returns a boolean indicating whether the node is connected (directly or indirectly) to the context object, for example the Document object in the case of the normal DOM, or the ShadowRoot in the case of a shadow DOM. ...
...a shadow DOM. Syntax var isItConnected = nodeObjectInstance.isConnected Return value A Boolean that is true if the node is connected to its relevant context object, and false if not. ...
... * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. */ if (!('isConnected' in Node.prototype)) { Object.defineProperty(Node.prototype, 'isConnected', { get() { r...
ParentNode.append() - Web APIs
Web › API › ParentNode › append
argItem : document.createTextNode(String(argItem))); }); ...
...argItem : document.createTextNode(String(argItem))); }); this.appendChild(docFr...
...argItem : document.createTextNode(String(argItem))); }); this.appendChild(docFrag); } }); ...
ParentNode.prepend() - Web APIs
argItem : document.createTextNode(String(argItem))); }); ...
...argItem : document.createTextNode(String(argItem))); }); this.insertBefore(doc...
...argItem : document.createTextNode(String(argItem))); }); this.insertBefore(docFrag, this.firstChild)...
PaymentRequest.PaymentRequest() - Web APIs
d submit it with the payment request. The default is false. requestPayerPhone A Boolean indicating whether the user agent should collect the payer's phone number and submit it with the payment request. The default is false. requestShipping A Boolean indicating whether the user agent should collect the payer's shipping address and submit it with the payment request. If you set this type to true, you should select an appropriate shippingType. The default is false. shippingType Lets you specify how the user interface refers to shipping when the word 'shipping' isn't appropriate for your use case. For example, in English speaking countries you would say "pizza delivery" not "pizza shipping". Valid values are "shipping", "delivery", and "pickup". Quotation marks must be included. The de...
... // Call show() to trigger the browser's payment flow. request.show().then(function(instrumentResponse) { // Do something with the response from the UI. }) .catch(function(err) { // Do something with the error from re...
... // Call show() to trigger the browser's payment flow. request.show().then(function(instrumentResponse) { // Do something with the response from the UI. }) .catch(function(err) { // Do something with the error from request.show(). }); } catch (e) { // Catch any ot...
PaymentRequest.canMakePayment() - Web APIs
, and if it won't, you could fall back to another payment method, or offer a list of methods that aren't handled by Payment Request API (or even provide instructions for paying by mail or by phone). Syntax paymentRequest.canMakePayment() .then( canPay => { ... }) .catch( error => { ... }) canPay = await paymentRequest.canMakePayment(); Returns A Promise to a Boolean that resolves to true if the user agent supports any of the payment methods supplied when instantiating the request using the PaymentRequest constructor. If the payment can't be processed, the promise receives a value of false. Note: If you call this too often, the browser may reject the returned promise with a DOMException. Parameters None Examples In the following example, is excerpted from a demo that asynch...
...To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support 11.1WebView Android No support NoChrome Android Full support 53F...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support 11.3Samsung Internet Android Full support 6.0Legend Full support Full support ...
PaymentRequest.onshippingoptionchange - Web APIs
tialization of PaymentRequest arguments are excerpted for clarity. ...
...To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support 11.1WebView Android No support NoChrome Android Full support 53F...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support 11.3Samsung Internet Android Full support 6.0Legend Full support Full support ...
PaymentRequest.shippingOption - Web APIs
The shippingOption read-only attribute of the PaymentRequest interface returns either the id of a selected shipping option, null (if no shipping option was set to be selected) or a shipping option selected by the user. It is initially null by when no "selected" shipping options are provided. This attribute is only populated if the constructor is called with the requestShipping flag set to true. If requestShipping was false (or missing), shippingOption returns null, even the developer provides a selected a shipping option. Syntax // Returns the id of the selected PaymentShippingOption var shippingOption = request.shippingOption; Example In the example below, the PaymentRequest.onshippingoptionchange and the PaymentRequest.onshippingaoptionchange events are dispatched. In each calls ...
...To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support 11.1WebView Android No support NoChrome Android Full support 53F...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support 11.3Samsung Internet Android Full support 6.0Legend Full support Full support ...
PaymentResponse.payerEmail - Web APIs
Syntax var payerEmail = PaymentResponse.payerEmail; Specifications Specification Status Comment Payment Request API Candidate Recommendation Initial definition. Browser Compatibility The compatibility table on this page is generated from structured data. ...
...To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support YesWebView Android No support NoChrome Android Full support 56 ...
...eds to be set to Enabled). To change preferences in Chrome, visit chrome://flags.Firefox Android Full support 56Notes Disabled Full support 56Notes Disabled Notes Available only in nightly builds.Disabled From version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support YesSamsung Internet Android Full support 6.0Legend Full support Full support ...
PaymentRequest.payerName - Web APIs
Syntax var payerName = PaymentResponse.payerName; Value A string containing the payer name. Specifications Specification Status Comment Payment Request APIThe definition of 'payerName' in that specification. Candidate Recommendation Initial definition. ...
...To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support YesWebView Android No support NoChrome Android Full support 58Fi...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support YesSamsung Internet Android Full support 7.0Legend Full support Full support ...
PaymentResponse - Web APIs
d in the BasicCardResponse dictionary. PaymentResponse.methodName Read only Secure context Returns the payment method identifier for the payment method that the user selected, for example, Visa, Mastercard, Paypal, etc.. PaymentResponse.payerEmail Read only Secure context Returns the email address supplied by the user. This option is only present when the requestPayerEmail option is set to true in the options parameter of the PaymentRequest() constructor. PaymentResponse.payerName Read only Secure context Returns the name supplied by the user. This option is only present when the requestPayerName option is set to true in the options parameter of the PaymentRequest() constructor. PaymentResponse.payerPhone Read only Secure context Returns the phone number supplied by the user. This...
... PaymentResponse.requestId Read only Secure context Returns the identifier of the PaymentRequest that produced the current response. ...
... PaymentResponse.requestId Read only Secure context Returns the identifier of the PaymentRequest that produced the current response. This is the same value supplied in the PaymentRequest() constructor by details.id. PaymentResponse.shippingAddress Read only Secure context Returns the shipping Address supplied by the user. This option is only present when the requestShipping option is set to true in the options parameter of the PaymentRequest() constructor. PaymentResponse.shippingOption Read only Secure context Returns the ID attribute of the shipping option selected by the user. This option is only present when the requestShipping option is set to true in the options parameter of the PaymentRequest() constructor. Methods PaymentResponse.retry() Secure context If something is wr...
PerformanceEventTiming - Web APIs
s://github.com/w3c/page-visibility/issues/29 // NOTE: ideally this check would be performed in the document <head> // to avoid cases where the visibility state changes before this code runs. let firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity; document.addEventListener('visibilitychange', (event) => { firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp); }, {once: true}); // Sends the passed data to an analytics endpoint. This code // uses `/analytics`; you can replace it with your own URL. function sendToAnalytics(data) { const body = JSON.stringify(data); // Use `navigator.sendBeacon()` if available, falling back to `fetch()`. (navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) || fetch('/analytics', {body, method: 'POST', keepaliv...
... // Sends the passed data to an analytics endpoint. This code // uses `/analytics`; you can replace it with your own URL. function sendToAnalytics(data) { const body = JSON.stringify(data); // Use `navigator.sendBeacon()` if available, falling back to `fetch()`. (navigator.sendBeacon && navigator.sendBeacon('/analytics', body)) || fetch('/analytics', {body, method: 'POST', keepalive: true}); } // Use a try/catch instead of feature detecting `first-input` // support, since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { function onFirstInputEntry(entry) { // Only report FID if the page wasn't hidden prior to // the entry being dispatched. This typically happens when a // page is loaded in a background tab.
... } } // Create a PerformanceObserver that calls `onFirstInputEntry` for each entry. const po = new PerformanceObserver((entryList) => { entryList.getEntries().forEach(onFirstInputEntry); }); // Observe entries of type `first-input`, including buffered entries, // i.e. entries that occurred before calling `observe()` below. po.observe({ type: 'first-input', buffered: true, }); } catch (e) { // Do nothing if the browser doesn't support this API. } Specifications Specification Status Comment UnknownThe definition of '[[Member]]' in that specification. Unknown Initial definition. ...
PointerEvent.PointerEvent() - Web APIs
e. ...
...onal and defaulting to false, of type Boolean, that sets the value of the instance's PointerEvent.isPrimary. ...
...ce's PointerEvent.isPrimary. ...
PublicKeyCredentialCreationOptions - Web APIs
", displayName: "John P. ...
...Name: "John P. ...
... // Timeout after 1 minute timeout: 60000, // Do not send the authenticator's origin attestation attestation: "none", extensions: { uvm: true, exts: true }, // Filter out authenticators which are bound to the device authenticatorSelection:{ authenticatorAttachment: "cross-platform", requireResidentKey: true, userVerification: "preferred" }, // Exclude already existing credentials for the user excludeCredentials: [ { type: "public-key", // the id for john.doe@example.com id : new Uint8Array(26) /* this actually is given by the server */ }, { type: "public-key", // the id for jo...
PublicKeyCredentialRequestOptions.extensions - Web APIs
mage or some non-textual content on the authenticator before verifying the user or testing their presence. The contentType gives the MIME type of the resource to be displayed while content gives its actual content. The client outputs the hash of the content which was displayed (hashing with the same algorithm which is used for the signature). uvi Boolean User verification index. If true, the client outputs an ArrayBuffer which contains a value uniquely identifying a user verification data record. In other words, this may be used server side to check if the current operation is based on the same biometric data that the previous authentication. loc Boolean Location. If true, the client outputs a Coordinates object representing the geolocation of the authenticator. ...
...lue uniquely identifying a user verification data record. In other words, this may be used server side to check if the current operation is based on the same biometric data that the previous authentication. loc Boolean Location. If true, the client outputs a Coordinates object representing the geolocation of the authenticator. uvm Boolean User verification method. If true, the client outputs an array of arrays with 3 values containing information about how the user was verified (e.g. fingerprint, pin, pattern), how the key is protected, how the matcher (tool used for the authentication operation) is protected. Note: Extensions are optional and different browsers may recognize different extensions. All extensions are optional for the client to process them:...
...matcher (tool used for the authentication operation) is protected. Note: Extensions are optional and different browsers may recognize different extensions. All extensions are optional for the client to process them: if a browser does not know a given extension, that will not cause any failure, the extension simply will not be processed. ...
RTCIceCandidateStats.deleted - Web APIs
The RTCIceCandidateStats dictionary's deleted property indicates whether or not the candidate has been deleted or released. Syntax isDeleted = rtcIceCandidateStats.deleted; Value A Boolean value indicating whether or not the candidate has been deleted or released. If this value is true, the candidate described by the RTCIceCandidateStats object is no longer under consideration. ...
...t the candidate has been deleted or released. Syntax isDeleted = rtcIceCandidateStats.deleted; Value A Boolean value indicating whether or not the candidate has been deleted or released. If this value is true, the candidate described by the RTCIceCandidateStats object is no longer under consideration. dThe exact meaning varies depending on the type of candidate: Local candidate A value of true means the candidate has been deleted as described by RFC 5245: 8.3. Host candidate A value of true indicates that the candidate's network resources have been released. This generally mean sthat any associated socket(s) have been closed and released. Remote (TURN) candidate A value of true means the candidate's TURN allocation is no longer active. The net result is the same; the candidate is...
... Example In this example, setInterval() is used to set up a function that runs periodically to display the latest statistics for candidates. Only candidates which have not been deleted are included in the output. ...
RTCOfferOptions.iceRestart - Web APIs
The iceRestart property of the RTCOfferOptions dictionary is a Boolean value which, when true, tells the RTCPeerConnection to start ICE renegotiation. Note: Rather than manually creating and submitting an offer with iceRestart set to true, you should consider calling the RTCPeerConnection method restartIce() instead. Syntax var options = { iceRestart: trueOrFalse }; Value A Boolean value indicating whether or not the RTCPeerConnection should generate new values for the connection's ice-ufrag and ice-pwd values, which will trigger ICE renegotiation on the next message sent to the remote peer. Usage notes When the RTCPeerConnection object's ICE connection state changes to failed, you should try to trigger an ICE restart. You should ideally do this by calling the RTCPeerConnection's ...
...or the iceconnectionstatechange event. It watches for the ICE connection state to transition to "failed", which indicates that an ICE restart should be tried in order to attempt to bring the connection back up. ...
...After that, the offer is sent to the server by calling a custom function sendOfferToServer(). Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCOfferOptions.iceRestart' in that specification. ...
RTCPeerConnection.addStream() - Web APIs
t ICE negotiation must be repeated to consider the new stream. Syntax rtcPeerConnection.addStream(mediaStream); Parameters mediaStream A MediaStream object indicating the stream to add to the WebRTC peer connection. Return value None. Example This simple example adds the audio and video stream coming from the user's camera to the connection. ...
...ation must be repeated to consider the new stream. Syntax rtcPeerConnection.addStream(mediaStream); Parameters mediaStream A MediaStream object indicating the stream to add to the WebRTC peer connection. Return value None. Example This simple example adds the audio and video stream coming from the user's camera to the connection. ...
...mple This simple example adds the audio and video stream coming from the user's camera to the connection. navigator.mediaDevices.getUserMedia({video:true, audio:true}, function(stream) { var pc = new RTCPeerConnection(); pc.addStream(stream); }); Migrating to addTrack() Compatibility allowing, you should update your code to instead use the addTrack() method: navigator.getUserMedia({video:true, audio:true}, function(stream) { var pc = new RTCPeerConnection(); stream.getTracks().forEach(function(track) { pc.addTrack(track, stream); }); }); The newer addTrack() API avoids confusion over whether later changes to the track-makeup of a stream affects a peer connection (they do not). The exception is in Chrome, where addStream() does make the peer connection sensitive to later st...
SVGSVGElement - Web APIs
fore magnification and panning) of the current innermost SVG document fragment can be either the "standard" view, i.e., based on attributes on the <svg> element such as viewBox) or on a "custom" view (i.e., a hyperlink into a particular <view> or other element). If the initial view is the "standard" view, then this attribute is false. If the initial view is a "custom" view, then this attribute is true. SVGSVGElement.currentView An SVGViewSpec defining the initial view (i.e., before magnification and panning) of the current innermost SVG document fragment. The meaning depends on the situation: If the initial view was a "standard" view, then: the values for viewBox, preserveAspectRatio and zoomAndPan within currentView will match the values for the corresponding DOM attributes that are on ...
...ing to this <svg> element, causing the animation clock corresponding to this document fragment to stand still until it is unpaused. SVGSVGElement.unpauseAnimations() Unsuspends (i.e., unpauses) currently running animations that are defined within the SVG document fragment, causing the animation clock to continue from the time at which it was suspended. SVGSVGElement.animationsPaused() Returns true if this SVG document fragment is in a paused state. SVGSVGElement.getCurrentTime() Returns the current time in seconds relative to the start time for the current SVG document fragment. If getCurrentTime() is called before the document timeline has begun (for example, by script running in a <script> element before the document's SVGLoad event is dispatched), then 0 is returned. SVGSVGElement.se...
...fined in pointer-events processing. SVGSVGElement.getEnclosureList() Returns a NodeList of graphics elements whose rendered content is entirely contained within the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in pointer-events processing. SVGSVGElement.checkIntersection() Returns true if the rendered content of the given element intersects the supplied rectangle. Each candidate graphics element is to be considered a match only if the same graphics element can be a target of pointer events as defined in pointer-events processing. SVGSVGElement.checkEnclosure() Returns true if the rendered content of the given element is entirely contained within the supplied rectangle. Each c...
SubtleCrypto.generateKey() - Web APIs
air and its privateKey.usages attribute is empty. Examples Note: You can try the working examples on GitHub. RSA key pair generation This code generates an RSA-OAEP encryption key pair. See the complete code on GitHub. let keyPair = window.crypto.subtle.generateKey( { name: "RSA-OAEP", modulusLength: 4096, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["encrypt", "decrypt"] ); Elliptic curve key pair generation This code generates an ECDSA signing key pair. See the complete code on GitHub. let keyPair = window.crypto.subtle.generateKey( { name: "ECDSA", namedCurve: "P-384" }, true, ["sign", "verify"] ); HMAC key generation This code generates an HMAC signing key. See the complete code on GitHub. let key = window.crypto...
...enerates an ECDSA signing key pair. See the complete code on GitHub. let keyPair = window.crypto.subtle.generateKey( { name: "ECDSA", namedCurve: "P-384" }, true, ["sign", "verify"] ); HMAC key generation This code generates an HMAC signing key. See the complete code on GitHub. let key = window.crypto.subtle.generateKey( { name: "HMAC", hash: {name: "SHA-512"} }, true, ["sign", "verify"] ); AES key generation This code generates an AES-GCM encryption key. See the complete code on GitHub. ...
...This code generates an HMAC signing key. See the complete code on GitHub. let key = window.crypto.subtle.generateKey( { name: "HMAC", hash: {name: "SHA-512"} }, true, ["sign", "verify"] ); AES key generation This code generates an AES-GCM encryption key. See the complete code on GitHub. let key = window.crypto.subtle.generateKey( { name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"] ); Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.generateKey()' in that specification. Recommendation Initial definition. ...
TextTrack.mode - Web APIs
Web › API › TextTrack › mode
The TextTrack interface's mode property is a string specifying and controlling the text track's mode: disabled, hidden, or showing. You can read this value to determine the current mode, and you can change this value to switch modes. Safari additionally requires the default boolean attribute to be set to true when implementing your own video player controls in order for the subtitles cues to be shown. Syntax var mode = textTrack.mode; textTrack.mode = "disabled" | "hidden" | "showing"; Value A DOMString which indicates the track's current mode. The text track mode is one of the values listed below, under Text track mode constants. Text track mode constants The text track mode--sometimes identified using the IDL enum TextTrackMode--must be one of the following values: disabled The ...
...rs, where each cue in the list represents a chapter in the media. The user can then navigate to the desired chapter, which begins at the cue's start position and ends at the cue's end position. Example In this example, we configure the text track's cues so that every time a cue is finished, the video automatically pauses playback. This is done by setting the pauseOnExit property on each cue to true. ...
... the pauseOnExit property on each cue to true. However, to ensure that the track's cues are available, we first set mode to showing. window.addEventListener("load", event => { let trackElem = document.querySelector("track"); let track = trackElem.track; track.mode = "showing"; for (let index=0; index < track.cues.length; index++) { let cue = track.cues[index]; cue.pauseOnExit = true; }; }); Specifications Specification Status Comment HTML Living StandardThe definition of 'mode' in that specification. Living Standard ...
msManipulationViewsEnabled - Web APIs
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. ...
...not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The msManipulationViewsEnabled read-only property returns true if manipulation features are support available, such as touch panning and zooming using CSS rules. This proprietary property is specific to Internet Explorer and Microsoft Edge. ...
...sEnabled read-only property returns true if manipulation features are support available, such as touch panning and zooming using CSS rules. This proprietary property is specific to Internet Explorer and Microsoft Edge. Value Returns true if manipulation features are support available, such as touch panning and zooming using CSS rules. ...
ValidityState.patternMismatch - Web APIs
ted by the user, does not conform to the constraints set by the element's pattern attribute. If the field supports the pattern attribute -- which means the <input> is of type text, tel, email, url, password, or search -- and the pattern value is set to a valid regular expression, if the value don't doesn't conform to the constraints set by the pattern value, the patternMismatch property will be true. Examples Given the following: <p> <label>Enter your phone number in the format (123)456-7890 (<input name="tel1" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit area code" size="2"/>)- <input name="tel2" type="tel" pattern="[0-9]{3}" placeholder="###" aria-label="3-digit prefix" size="2"/> - <input name="tel3" type="tel" pattern="[0-9]{4}" placeholder="####" aria-...
...-label="4-digit number" size="3"/> </label> </p> Here we have 3 sections for a north American phone number with an implicit label encompassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by the pattern attribute set on each. If the values are too long or too short, or contain characters that aren't digits, patternMismatch will be true. When true, the element matches the :invalid CSS pseudo-classes. input:invalid { border: red solid 3px; } Note, in this case, we get a patternMismatch not a validityState.tooLong or validityState.tooShort if the values are too long or too short because it is the pattern that is dictating the length of the value. Had we used minlength and maxlength attributes instead, we may have seen validi...
...S pseudo-classes. input:invalid { border: red solid 3px; } Note, in this case, we get a patternMismatch not a validityState.tooLong or validityState.tooShort if the values are too long or too short because it is the pattern that is dictating the length of the value. Had we used minlength and maxlength attributes instead, we may have seen validityState.tooLong or validityState.tooShort being true. Note: The email input type requires, at minimum, a match of x@y and the url type requires, at minimum, a match to x:, with no pattern attribute present. When invalid, the validityState.typeMismatch will be true, if there is no pattern attribute (or if the pattern attribute is not valid for that input type). Specifications Specification Status Comment HTML Living Stan...
WebGLRenderingContext.makeXRCompatible() - Web APIs
*/ outputCanvas.addEventListener("webglcontextrestored", (event) => { loadSceneResources(currentScene); }); async function onStartedXRSession(xrSession) { try { await gl.makeXRCompatible(); } catch(err) { switch(err) { case AbortError: showSimpleMessageBox("Unable to transfer t...
...These both use the handleStartButtonClick() function as their event handler. T...
...ir event handler. The function determines that the button clicked was the one requesting immersive-vr mode by checking to see if the button has the use-webxr class on it. If the button clicked by the user has that class (and we've confirmed that WebXR is available by ensuring that the navigator.xr property exists), we use requestSession() to request a new WebXR session and set the usingXR flag to true. If the other button was clicked, we ensure that xrSession is NULL and clear usingXR to false. Then the startGame() function is called to trigger the beginning of gameplay. Handlers are provided for both webglcontextlost and webglcontextrestored; in the first case, we make sure we're aware that the state can be recovered, while in the latter we actually reload the scene to ensure we have the c...
Taking still photos with WebRTC - Web APIs
references to the major elements we need to be able to access. 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). It returns a promise which we attach success and failure callbacks to. The success callback receives a stre...
...bject have been configured based on the stream's format. 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. If this is indeed the first run, we set the video's height based on the size difference between the video's actual size, video.videoWidth, and the width at which we're going to render i...
...t based on the size difference between the video's actual size, video.videoWidth, and the width at which we're going to render it, width. Finally, the width and height of both the video and the canvas are set to match each other by calling Element.setAttribute() on each of the two properties on each element, and setting widths and heights as appropriate. Finally, we set the streaming variable to true to prevent us from inadvertently running this setup code again. 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 e...
Using DTMF with WebRTC - Web APIs
cript code next. Keep in mind that the process of establishing the connection is somewhat contrived here; you normally don't build both ends of the connection in the same document. Global variables First, we establish global variables. 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. callerPC and receiverPC The RTCPeerConnection objects representing the caller and the receiver, respectively. These will be initialized when the ...
...ermine whether or not the user agent supports addTrack(); if it doesn't, we'll fall back to addStream(). This gets figured out in connectAndDial(), as shown in Starting the connection process. mediaConstraints An object conforming to the MediaConstraints dictionary specifying the constraints to use when starting the connection. We want an audio-only connection, so video is false, while audio is true. offerOptions An RTCOfferOptions object providing options to specify when calling RTCPeerConnection.createOffer(). In this case, we state that we want to receive audio but not video. dialButton and logElement These variables will be used to store references to the dial button and the <div> into which logging information will be written. They'll get set up when the page is first loaded. See In...
...hasAddTrack) { receiverPC.ontrack = handleReceiverTrackEvent; } else { receiverPC.onaddstream = handleReceiverAddStreamEvent; } navigator.mediaDevices.getUserMedia(mediaConstraints) .then(gotStream) .catch(err => log(err.message)); } After creating the RTCPeerConnection for the caller (callerPC), we look to see if it has an addTrack() method. If it does, we set hasAddTrack to true; otherwise, we set it to false. This variable will let the example operate even on browsers not yet implementing the newer addTrack() method; we'll do so by falling back to the older addStream() method. Next, the event handlers for the caller are established. We'll cover these in detail later. Then a second RTCPeerConnection, this one representing the receiving end of the call, is created and s...
Using the Web Speech API - Web APIs
he list as a SpeechGrammar object instance. speechRecognitionList.addFromString(grammar, 1); We then add the SpeechGrammarList to the speech recognition instance by setting it to the value of the SpeechRecognition.grammars property. 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). SpeechRecognition.lang: Sets the language of the recognition. Setting this is good practice, and therefore recommended. SpeechRecognition.interimResults: Defines whether the speech recognition system should return interim results, or just final results. Final results are good enough for this simple demo. SpeechRecognition.maxA...
...he live demo URL in a supporting mobile browser like Chrome, or Firefox OS. Browser support Support for Web Speech API speech synthesis is still getting there across mainstream browsers, and is currently limited to the following: Firefox desktop and mobile support it in Gecko 42+ (Windows)/44+, without prefixes, and it can be turned on by flipping the media.webspeech.synth.enabled flag to true in about:config. Firefox OS 2.5+ supports it, by default, and without the need for any permissions. Chrome for Desktop and Android have supported it since around version 33, without prefixes. HTML and CSS The HTML and CSS are again pretty trivial, simply containing a title, some instructions for use, and a form with some simple controls. The <select> element is initially empty, b...
...ynthesisVoice objects. We then loop through this list -- for each voice we create an <option> element, set its text content to display the name of the voice (grabbed from SpeechSynthesisVoice.name), the language of the voice (grabbed from SpeechSynthesisVoice.lang), and -- DEFAULT if the voice is the default voice for the synthesis engine (checked by seeing if SpeechSynthesisVoice.default returns true.) We also create data- attributes for each option, containing the name and language of the associated voice, so we can grab them easily later on, and then append the options as children of the select. function populateVoiceList() { voices = synth.getVoices(); for(i = 0; i < voices.length ; i++) { var option = document.createElement('option'); option.textContent = voices[i].name + '...
window.location - Web APIs
Web › API › Window › location
r a new value is assigned to the location object, a document will be loaded using the URL as if location.assign() had been called with the modified URL. Note that security settings, like CORS, may prevent this to effectively happen. ...
... scroll: var showBookmark = (function () { var _useHash, _scrollX, _scrollY, _nodeX, _nodeY, _itFrame, _scrollId = -1, _bookMark, /* * nDuration: the duration in milliseconds of each frame * nFrames: number of frames for each scroll */ nDuration = 200, nFrames = 10; function _next () { if (_itFrame > nFrames) { clearInterval(_scrollId); _scrollId = -1; return; } _isBot = true; document.documentElement.scrollTop = Math.round(_scrollY + (_nodeY - _scrollY) * _itFrame / nFrames); document.documentElement.scrollLeft = Math.round(_scrollX + (_nodeX - _scrollX) * _itFrame / nFrames); if (_useHash && _itFrame === nFrames) { location.hash = _bookMark; } _itFrame++; } function _chkOwner () { if (_isBot) { _isBot = false; return; } if (_scrollId > -1) { clearIn...
... Living Standard No change from HTML5. HTML5The d...
XRPose.emulatedPosition - Web APIs
The emulatedPosition read-only attribute of the XRPose interface is a Boolean value indicating whether or not both the the position component of the pose's transform is directly taken from the XR device, or it's simulated or computed based on other sources. Syntax let emulated = xrPose.emulatedPosition; Value A Boolean which is true if the pose's position is computed based on estimates or is derived from sources other than direct sensor data. If the position is precisely gbased on direct sensor inputs, the value is false. Usage notes There are two basic categories of XR tracking systems. A basic XR headset provides three degrees of freedom (3DoF), tracking the pitch, yaw, and roll of the user's head. No information is available about movement forward, backward, or to the sides...
...XR tracking systems. A basic XR headset provides three degrees of freedom (3DoF), tracking the pitch, yaw, and roll of the user's head. No information is available about movement forward, backward, or to the sides. Any such data is taken from other sources, such as keyboard or mouse inputs or game controllers. As such, the position is considered to be emulated, so the emulatedPosition property is true. 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. The same notion applies not just to the user's head, but to any object. A hand controller that can directly report its position would ...
...mine the user's position, so the value of emulatedPosition is false. The same notion applies not just to the user's head, but to any object. A hand controller that can directly report its position would have a value of false for this property as well. If its position is computed as an offset from another object (such as by basing it off the model representing the user's body), then this value is true. This information is important because devices whose position is emulated are prone to their offset drifting relative to the real world space over time. This is because emulating a position based on accelerometer inputs and models tends to introduce minor errors which accumulate over time. Specifications Specification Status Comment WebXR Device APIThe definition of...
XRView.eye - Web APIs
Web › API › XRView › eye
primary purpose of this property is to allow the correct area of any pre-rendered stereo content to be presented to the correct eye. For dynamically-rendered 3D content, you can usually ignore this and simply render each of the viewer's views, one after another. Examples This code, from the viewer pose's renderer, iterates over the pose's views and renders them. However, we have flags which, if true, indicate that a particular eye has been injured during gameplay. When rendering that eye, if the flag is true, that view is skipped instead of being rendered. 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) { le...
...If the result is false, indicating that the eye is now healthy, we render the s...
...If the result is false, indicating that the eye is now healthy, we render the scene for that eye. Otherwise, we don't. ...
XRWebGLLayer() - Web APIs
ontext identifying the WebGL drawing context to use for rendering the scene for the specified WebXR session. layerInit Optional An object conforming to the XRWebGLLayerInit dictionary, providing configuration options for the new XRWebGLLayer. The options available are: alpha Optional The frame buffer's color buffer will be established with an alpha channel if the alpha Boolean property is true. Otherwise, the color buffer will not have an alpha channel. The default value is true. antialias Optional A Boolean value which is true if anti-aliasing is to be used when rendering in the context; otherwise false. The browser selects the anti-aliasing method to use; there is no support for requesting a specific mode yet. The default value is true. depth Optional A Boolean value which, if t...
... framebufferScaleFactor Optional A floating-point value which is used to scale the image during compositing, with a value of 1.0 represents the default pixel size for the frame buffer. ...
...amebufferScaleFactor() returns the scale that would result in a 1:1 pixel ratio, thereby ensuring that the rendering is occurring at the device's native resolution. The default is 1.0. ignoreDepthValues Optional A Boolean value which indicates whether or not to ignore the contents of the depth buffer while compositing the scene. The default is false. stencil Optional A Boolean value which, if true, requests that the new layer include a stencil buffer. Otherwise, no stencil buffer is allocated. The default is false. Return value A newly-created XRWebGLLayer which links the specified XRSession to the WebGL context given by context, which will be used as the renderer for the session. Any options specified in layerInit are used to tailor the rendering system's configuration. Exceptions ...
XRWebGLLayer.ignoreDepthValues - Web APIs
The read-only XRWebGLLayer property ignoreDepthValues is a Boolean value which is true if the session has been configured to ignore the values in the depth buffer while rendering the scene. If the depth buffer is being used to determine the position of vertices, this property is false. The value of ignoreDepthValues can only be set when the XRWebGLLayer is instantiated, by setting the corresponding value in the XRWebGLLayerInit object specified as the constructor's layerInit parameter. As a parameter you're likely to set yourself, it is unlikely you'll need to read it later, but it's available if the need arises. ...
... only be set when the XRWebGLLayer is instantiated, by setting the corresponding value in the XRWebGLLayerInit object specified as the constructor's layerInit parameter. As a parameter you're likely to set yourself, it is unlikely you'll need to read it later, but it's available if the need arises. Syntax let ignoringDepthBuffer = xrWebGLLayer.ignoreDepthValues; Value A Boolean value which is true if the WebGL context's depth buffer is being used while computing the locations of points in the 3D world. Otherwise, if this is true, the depth buffer's values are being used to assist in placing objects in the scene. 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(). ...
...he depth, in tandem with the coordinates of each point being rendered, makes it possible to more accurately represent the scene in the 3D space. Examples If the Web application which is using WeXR is rendering its content without using a depth buffer--or if the depth buffer's contents are invalid--you should disable the use of the depth buffer for WebXR rendering by setting ignoreDepthValues to true when creating the XRWebGLLayer. This is demonstrated in the snippet of code below: const glLayerOptions = { ignoreDepthValues: true }; let glLayer = new XRWebGLLayer(xrSession, gl, glLayerOptions); Specifications Specification Status Comment WebXR Device APIThe definition of 'XRWebGLLayer.ignoreDepthValues' in that specification. Working Draft Initial definitio...
Using the aria-required attribute - Accessibility
Description The aria-required attribute is used to indicate that user input is required on an element before a form can be submitted. This attribute can be used with any typical HTML form element; it is not limited to elements that have an ARIA role assigned. HTML5 now has the required attribute, but aria-required is still useful for user agents that do not yet support HTML5. Value true or false (Default: false) Possible effects on user agents and assistive technology Screen readers should announce the field as required. Note that this attribute will not automatically change the presentation of the field. Note: Opinions may differ on how assistive technology should handle this technique. The information provided above is one of those opinions and therefore not normative. Ex...
...ibute will not automatically change the presentation of the field. Note: Opinions may differ on how assistive technology should handle this technique. The information provided above is one of those opinions and therefore not normative. ...
...gy should handle this technique. The information provided above is one of those opinions and therefore not normative. ...
ARIA: feed role - Accessibility
and trigger the loading of feed content while in reading mode. A feed is a container element whose children are <article>s or have role article. Each article within a feed should be focusable, with tabindex of 0 or -1. An article should be scrolled into view when it, or a descendant element, receives focus. 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. To ensure good user experience, avoid inserting or removing articles in the middle of a feed, load new articles before the user has reached the end of the feed, and provide keyboard commands for moving focus among articles so that keyboard users can navigate through your feed. Se...
...ia-labelled If the feed has no visible title, the feed element has a label specified with aria-label. If it does, see aria-labelledby. aria-labelledby If the feed has a visible title, the feed element has aria-labelledby referring to the element containing the title. If not, add an aria-label. aria-busy When busy, such as when articles are being added or removed from the feed, set aria-busy="true" during the update operation. Make sure it's reset to false when the operation is complete or the changes may not become visible. article Each section of content in a feed should be contained in an <article> or element with role article. Each article should have an aria-labelledby referring to the article title or other child that can serve as a distinguishing label. Each article should prefera...
... its position in the feed and an aria-setsize set to a value that represents either the total number of articles that have been loaded or the total number in the feed, depending on which value is more helpful to users. If the total number in the feed is not known, set aria-setsize="-1". Required JavaScript features None, except as required by any attributes. For example, setting aria-busy to true during the update operation if needed, and then to false upon completion. Examples Example Implementation of Feed Pattern Specifications Specification Status Accessible Rich Internet Applications (WAI-ARIA) 1.1The definition of 'feed' in that specification. Recommendation Screen reader support Coming soon ...
Operable - Accessibility
board -- all functionality (AAA) This is a further step beyond criterion 2.1.1. To achieve AAA conformance, all functionality should be accessible using keyboard controls -- with no exceptions. See UI controls and Building keyboard accessibility back in 2.1.4 Character Key Shortcuts (A) added in 2.1 If a single character key shortcut exists, then at least one of the following is true: single character key shortcuts can be turned off, remapped or are only active when the relevant user interface component is in focus. Understanding Character Key Shortcuts Note: Also see the WCAG description for Guideline 2.1 Keyboard Accessible: Make all functionality available from a keyboard. Guideline 2.2 -- Enough Time: Provide users enough time to read and use content This gu...
...) added in 2.1 All functionality that can be operated with a pointer can be operated with single-point actions. Path-based or multi-point gestures are not required to operate any functionality. Exceptions exist. Understanding Pointer Gestures 2.5.2 Pointer Cancellation (A) added in 2.1 For functionality that can be operated using a single-pointer at least one of the following is true: no down-event, abort/undo, up reversal or essential. Understanding Pointer Cancellation 2.5.3 Label in Name (A) added in 2.1 For each user interface component that includes a visible text label, make sure the accessible name matches (or includes) the visible text in the label. Understanding Label in Name 2.5.4 Motion Actuation (A) added in 2.1 Ensure that for functi...
...nt that includes a visible text label, make sure the accessible name matches (or includes) the visible text in the label. Understanding Label in Name 2.5.4 Motion Actuation (A) added in 2.1 Ensure that for functionality that can be triggered by a) device motion (like shaking, tilting) or b) user gestures detected by device sensors (including a camera) that both of the following are true: 1) motion actuation can be disabled, and 2) the functionality can be operated without using device motion or user gestures. Exceptions exist. Understanding Motion Actuation 2.5.5 Target Size (AAA) added in 2.1 The size of an actionable item's touch target must be at least 44 CSS pixels in both width and height. Exceptions exist. Understanding Target Size 2.5.6 Concurr...
::slotted() - CSS: Cascading Style Sheets
Web › CSS › ::slotted
This allows them to stand out better next to the slots that haven't been successfully filled. The element looks like this when inserted into the page: <person-details> <p slot="person-name">Dr. Shazaam</p> <span slot="person-age">Imm...
...To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 37Safari Full support 10WebView Android Full support 50Chrome Android Full support 5...
...To change preferences in Firefox, visit about:config.Opera Android Full support 37Safari iOS Full support 10Samsung Internet Android Full support 5.0Legend Full support Full support ...
:indeterminate - CSS: Cascading Style Sheets
The :indeterminate CSS pseudo-class represents any form element whose state is indeterminate, such as checkboxes which have their HTML indeterminate attribute set to true, radio buttons which are members of a group in which all radio buttons are unchecked, and indeterminate <progress> elements. ...
... which have their HTML indeterminate attribute set to true, radio buttons which are members of a group in which all radio buttons are unchecked, and indeterminate <progress> elements. /* Selects any <input> whose state is indeterminate */ input:indeterminate { background: lime; } Elements targeted by this selector are: <input type="checkbox"> elements whose indeterminate property is set to true by JavaScript <input type="radio"> elements, when all radio buttons with the same name value in the form are unchecked <progress> elements in an indeterminate state Syntax :indeterminate Examples Checkbox & radio button This example applies special styles to the labels associated with indeterminate form fields. HTML <div> <input type="checkbox" id="checkbox"> <label for="checkbox">T...
... Living Standard No change. HTML5The defini...
@font-face - CSS: Cascading Style Sheets
g; font-weight A font-weight value. Since Firefox 61 (and in other modern browsers) this also accepts two values to specify a range that is supported by a font-face, for example font-weight: 100 400; font-variant A font-variant value. font-feature-settings Allows control over advanced typographic features in OpenType fonts. font-variation-settings Allows low-level control over OpenType or TrueType font variations, by specifying the four letter axis names of the features to vary, along with their variation values. src Specifies the resource containing the font data. This can be a URL to a remote font file location or the name of a font on the user's computer. To provide the browser with a hint as to what format a font resource is -- so it can select a suitable one -- it is possibl...
... resource containing the font data. This can be a URL to a remote font file location or the name of a font on the user's computer. To provide the browser with a hint as to what format a font resource is -- so it can select a suitable one -- it is possible to include a format type inside a format() function: src: url(ideal-sans-serif.woff) format("woff"), url(basic-sans-serif.ttf) format("truetype"); The available types are: "woff", "woff2", "truetype", "opentype", "embedded-opentype", and "svg". unicode-range The range of Unicode code points to be used from the font. Description If the local() function is provided, specifying a font name to look for on the user's computer, and the user agent finds a match, that local font is used. Otherwise, the font resource specified using ...
...nection. It's common to use both url() and local() together, so that the user's installed copy of the font is used if available, falling back to downloading a copy of the font if it's not found on the user's device. The @font-face at-rule may be used not only at the top level of a CSS, but also inside any CSS conditional-group at-rule. Font MIME Types Format MIME type TrueType font/ttf OpenType font/otf Web Open Font Format font/woff Web Open Font Format 2 font/woff2 Notes Web fonts are subject to the same domain restriction (font files must be on the same domain as the page using them), unless HTTP access controls are used to relax this restriction. @font-face cannot be declared within a CSS selector. For example, ...
-webkit-animation - CSS: Cascading Style Sheets
false The browser doesn't support these prefixed CSS animations. ...
... false The browser doesn't support these prefixed CSS animations. ...
... 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. Examples Basic example @media (-webkit-transform-2d) { div { -webkit-transform: translate(100px, 100px); } } This media feature is only supported by WebKit. ...
... false The 2D CSS transforms prefixed with -webkit are not supported by the browser. Examples Basic example @media (-webkit-transform-2d) { div { -webkit-transform: translate(100px, 100px); } } This media feature is only supported by WebKit. ...
... false The 2D CSS transforms prefixed with -webkit are not supported by the browser. Examples Basic example @media (-webkit-transform-2d) { div { -webkit-transform: translate(100px, 100px); } } This media feature is only supported by WebKit. ...
-webkit-transform-3d - CSS: Cascading Style Sheets
false The 3D CSS transforms prefixed with -webkit are not supported by the browser. ...
... false The 3D CSS transforms prefixed with -webkit are not supported by the browser. ...
... false The 3D CSS transforms prefixed with -webkit are not supported by the browser. ...
Audio and video manipulation - Developer guides
video and the output greyscale frames. Ordinarily, if you were implementing a "play video in greyscale" feature, you'd probably add display: none to the style for the <video> element, to keep the source video from being drawn to the screen while showing only the canvas showing the altered frames. HTML We can set up our video player and <canvas> element like this: <video id="my-video" controls="true" width="480" height="270" crossorigin="anonymous"> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <canvas id="my-canvas" width="480" height="270"></canvas> JavaScript This code handles altering the frames. var processor = { timerCallback: function()...
... speed but not the pitch. To manipulate the audio's pitch you need to use the Web Audio API. See the AudioBufferSourceNode.playbackRate property. ...
...deo> JavaScript var context = new AudioContext(), audioSource = context.createMediaElementSource(document.getElementById("my-video")), filter = context.createBiquadFilter(); audioSource.connect(filter); filter.connect(context.destination); // Configure filter filter.type = "lowshelf"; filter.frequency.value = 1000; filter.gain.value = 25; Playable code <video id="my-video" controls="true" width="480" height="270" crossorigin="anonymous"> <source src="https://udn.realityripple.com/samples/5b/8cd6da9c65.webm" type="video/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code"...
Creating and triggering events - Developer guides
e additional data in the event listener: function eventHandler(e) { console.log('The time is: ' + e.detail); } The old-fashioned way The older approach to creating events uses APIs inspired by Java. The following shows an example with document.createEvent(): // Create the event. const event = document.createEvent('Event'); // Define that the event name is 'build'. event.initEvent('build', true, true); // Listen for the event. elem.addEventListener('build', function (e) { // e.target matches elem }, false); // target can be any Element or other EventTarget. elem.dispatchEvent(event); Event bubbling It is often desirable to trigger an event from a child element, and have an ancestor catch it; optionally, with data: <form> <textarea></textarea> </form> const form = document.q...
...to trigger an event from a child element, and have an ancestor catch it; optionally, with data: <form> <textarea></textarea> </form> const form = document.querySelector('form'); const textarea = document.querySelector('textarea'); // Create a new event, allow bubbling, and provide any data you want to pass to the "detail" property const eventAwesome = new CustomEvent('awesome', { bubbles: true, detail: { text: () => textarea.value } }); // The form element listens for the custom "awesome" event and then consoles the output of the passed text() method form.addEventListener('awesome', e => console.log(e.detail.text())); // As the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point textarea.addEventListener('input', e =...
...tor('textarea'); form.addEventListener('awesome', e => console.log(e.detail.text())); textarea.addEventListener('input', function() { // Create and dispatch/trigger an event on the fly // Note: Optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element this.dispatchEvent(new CustomEvent('awesome', { bubbles: true, detail: { text: () => textarea.value } })) }); Triggering built-in events This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. View the example in action. function simulateClick() { const event = new MouseEvent('click', { view: window, bubbles: true, cancelable: true }); const cb = document.getElem...
User input and controls - Developer guides
tionality is a bad idea. The following is a set of recommendations and best practices for using such tools in Open Web Apps. Decide what input mechanism you're using Keyboard Keyboard input can be controlled by your app. For example if you want to add controls when any key gets pressed, you need to add an event listener on the window object: window.addEventListener("keydown", handleKeyDown, true); window.addEventListener("keyup", handleKeyUp, true); where handleKeyDown and handleKeyUp are the functions implementing the controls about the keydown and keyup events. Note: Have a look at the Events reference and KeyboardEvent guide to find out more about keyboard events. Mouse The events occurring when the user interacts with a pointing device such as a mouse are represented by the Mou...
...e out about adding fullscreen functionality your application, read our documentation about using fullscreen mode. Drag & Drop Drag & Drop allows your application's users to click and hold the mouse button down over an element, drag it to another location, and release the mouse button to drop the element there. Here is an example that allows a section of content to be dragged. ...
... mouse button down over an element, drag it to another location, and release the mouse button to drop the element there. Here is an example that allows a section of content to be dragged. <div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">? This text <strong>may</strong> be dragged. ?</div> in which we: Set the draggable attribute to true on the element that you wish to make draggable Add a listener for the dragstart event and set the drag data within this listener Note: You can find more information in the MDN Drag & Drop documentation. contentEditable In open web apps any DOM element can be made directly editable using the contenteditable attribute. <div contenteditable="true">? This text can be edited by the user. <...
HTML attribute: pattern - HTML: Hypertext Markup Language
The pattern attribute is an attribute of the text, tel, email, url, password, and search input types. The pattern attribute, when specified, is a regular expression which the input's value must match in order for the value to pass constraint validation. ...
...tch the pattern. You should also include other explanatory text nearby. Some of the input types supporting the pattern attribute, notably the email and url input types, have expected value syntaxes that must be matched. If the pattern attribute isn't present, and the value doesn't match the expected syntax for that value type, the ValidityState object's read-only typeMismatch property will be true. Usability When including a pattern, provide a description of the pattern in visible text near the control. Additionally, include a title attribute which gives a description of the pattern. User agents may use the title contents during constraint validation to tell the user that the pattern is not matched. Some browsers show a tooltip with title contents, improving usability for sighted users. ...
...el="4-digit number" size="3"/> </label> </p> Here we have 3 sections for a north American phone number with an implicit label encompassing all three components of the phone number, expecting 3-digits, 3-digits and 4-digits respectively, as defined by the pattern attribute set on each. If the values are too long or too short, or contain characters that aren't digits, the patternMismatch will be true. When true, the element matches the :invalid CSS pseudo-classes. input:invalid { border: red solid 3px; } Had we used minlength and maxlength attributes instead, we may have seen validityState.tooLong or validityState.tooShort being true. Specifying a pattern You can use the pattern attribute to specify a regular expression that the inputted value must match in order to be considered val...
<input type="submit"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › submit
rver. <input type="submit" value="Send Request"> Value A DOMString used as the button's label Events click Supported common attributes type and value IDL attributes value Methods None Value An <input type="submit"> element's value attribute contains a DOMString which is displayed as the button's label. Buttons do not have a true value otherwise. <input type="submit" value="Send Request"> If you don't specify a value, the button will have a default label, chosen by the user agent. This label is likely to be something along the lines of "Submit" or "Submit Query." Here's an example of a submit button with a default label in your browser: <input type="submit"> Additional attributes In addition to the attributes...
...submit some text</label> <input id="example" type="text" name="text"> </div> <div> <input type="submit" value="Send" accesskey="s"> </div> </form> For example, in Firefox for Mac, pressing Control-Option-S triggers the Send button, while Chrome on Windows uses Alt+S. The problem with the above example is that the user will not know what the access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the title attribute) can also help, although it's not a complete solu...
... Adding a tooltip to the button (using the title attribute) can also help, although it's not a complete solution for accessibility purposes. 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. See the <input type="button"> page for more ideas about enabling and disabling buttons. Validation Submit buttons don't participate in constraint validation; they have no real value to be constrained. Examples We've included simple examples above. There isn't really anything more to say about submit button...
spellcheck - HTML: Hypertext Markup Language
The spellcheck global attribute is an enumerated attribute defines whether the element may be checked for spelling errors. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. 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. Note: The spellcheck attribute is an enumerated one and not a Boolean one. 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. T...
...sible, checked for spelling errors; false, which indicates that the element should not be checked for spelling errors. Note: The spellcheck attribute is an enumerated one and not a Boolean one. This means that the explicit usage of one of the values true or false is mandatory, and that a shorthand like <textarea spellcheck></textarea> is not allowed. The correct usage is <textarea spellcheck="true"></textarea>. If this attribute is not set, its default value is element-type and browser-defined. This default value may also be inherited, which means that the element content will be checked for spelling errors only if its nearest ancestor has a spellcheck state of true. This attribute is merely a hint for the browser: browsers are not required to check for spelling errors. Typically non-ed...
... Specifications Specification Status Comment HTML Living StandardThe definition of 'spellcheck' in that specification. ...
SyntaxError: missing ) after condition - JavaScript
There is an error with how an if condition is written. In any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. The if statement executes a statement if a specified condition is truthy. In JavaScript, this condition must appear in parenthesis after the if keyword, like this: if (condition) { // do something if the condition is true } Examples Missing parenthesis It might just be an oversight, carefully check all you parenthesis in your code. if (3 > Math.PI { console.log("wait what?"); } // SyntaxError: missing ) after condition To fix this code, you would need to add a parenthesis that closes the condition. if (3 > Math.PI) { console.log("wait what?"); } Misused is keyword If you are coming from another progr...
...h.PI { console.log("wait what?"); } // SyntaxError: missing ) after condition To fix this code, you would need to add a parenthesis that closes the condition. ...
... (3 > Math.PI) { console.log("wait what?"); } Misused is keyword If you are coming from another programming language, it is also easy to add keywords that don't mean the same or have no meaning at all in JavaScript. if (done is true) { console.log("we are done!"); } // SyntaxError: missing ) after condition Instead you need to use a correct comparison operator. For example: if (done === true) { console.log("we are done!"); } ...
TypeError: "x" is not a constructor - JavaScript
an object called mycar as follows: var mycar = new Car('Eagle', 'Talon TSi', 1993); In Promises When returning an immediately-resolved or immediately-rejected Promise, you do not need to create a new Promise(...) and act on it. ...
...ou do not need to create a new Promise(...) and act on it. ...
...legal (the Promise constructor is not being called correctly) and will throw a TypeError: this is not a constructor exception: return new Promise.resolve(true); Instead, use the Promise.resolve() or Promise.reject() static methods: // This is legal, but unnecessarily long: return new Promise((resolve, reject) => { resolve(true); }) // Instead, return the static method: return Promise.resolve(true); return Promise.reject(false); ...
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
s, or in numbers, or other primitive types. Examples Searching in strings Unlike in other programming languages (e.g. Python), you can't search in strings using the in operator. "Hello" in "Hello World"; // TypeError: cannot use 'in' operator to search for 'Hello' in 'Hello World' Instead you will need to use String.prototype.indexOf(), for example. "Hello World".indexOf("Hello") !== -1; // true The operand can't be null or undefined Make sure the object you are inspecting isn't actually null or undefined. var foo = null; "bar" in foo; // TypeError: cannot use 'in' operator to search for 'bar' in 'foo' (Chrome) // TypeError: right-hand side of 'in' should be an object, got null (Firefox) The in operator always expects an object. var foo = { baz: "bar" }; "bar" in foo; // false "PI...
...can't be null or undefined Make sure the object you are inspecting isn't actually null or undefined. ...
... object, got null (Firefox) The in operator always expects an object. 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. ...
Array.prototype.filter() - JavaScript
e source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax let newArray = arr.filter(callback(element[, index, [array]])[, thisArg]) Parameters callback Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise. It accepts three arguments: element The current element being processed in the array. indexOptional The index of the current element being processed in the array. arrayOptional The array filter was called upon. thisArgOptional Value to use as this when executing callback. Return value A new array with the elements that pass the test.
... called upon. thisArgOptional Value to use as this when executing callback. Return value A new array with the elements that pass the test. If no elements pass the test, an empty array will be returned. Description filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array. callback is invoked with three arguments: the value of the element the index of the element the Array object...
...ltering 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. let frui...
Array.prototype.findIndex() - JavaScript
bute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. See also the find() method, which returns the value of an array element, instead of its index. Syntax arr.findIndex(callback( element[, index[, array]] )[, thisArg]) Parameters callback A function to execute on each value in the array until the function returns true, indicating that the satisfying element was found. It takes three arguments: element The current element being processed in the array. index Optional The index of the current element being processed in the array. array Optional The array findIndex() was called upon. thisArg Optional Optional object to use as this when executing callback. Return value The index of the fir...
...If thisArg was supplied, let T be thisArg; else let T be undefined. var thisArg = arguments[1]; // 5. Let k be 0. var k = 0; // 6. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). // b. Let kValue be ? Get(O, Pk). // c. Let testResult be ToBoolean(? Call(predicate, T, << kValue, k, O >>)). // d. ...
... // b. Let kValue be ? Get(O, Pk). // c. Let testResult be ToBoolean(? Call(predicate, T, << kValue, k, O >>)). // d. If testResult is true, return k. var kValue = o[k]; if (predicate.call(thisArg, kValue, k, o)) { return k; } // e. Increase k by 1. k++; } // 7. Return -1. return -1; }, configurable: true, writable: true }); } If you need to support truly obsolete JavaScript engines that do not support Object.defineProperty, it is best not to polyfill Array.prototype methods at all, as you cannot make them non-enumerable. Examples Find the index of a prime number in an array The following example returns the index of the first element in the array that is a prime number, or -1 if there ...
Array.prototype.join() - JavaScript
...
... ...
... ...
BigInt64Array - JavaScript
all elements in the array pass the test provided by a function. See also Array.prototype.every(). BigInt64Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). BigInt64Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). BigInt64Array.prototype.find() Returns the found value in the array if an element in the array satisfies the provided testing function, or undefined if not found. See also Array.prototype.find(). BigInt64Array.prototype.findIndex() Returns the found index in the array if an element in the array satisfies the provided testing function, or -1 if not found. Se...
...Index() Returns the found index in the array if an element in the array satisfies the provided testing function, or -1 if not found. See also Array.prototype.findIndex(). BigInt64Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). BigInt64Array.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). BigInt64Array.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). BigInt64Array.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). BigInt64Array.prototype.keys() Ret...
...nts of an array -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). BigInt64Array.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. BigInt64Array.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). BigInt64Array.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). BigInt64Array.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). BigInt64Array.prototype.subarray() Returns a new BigUint64Array from the given start and end element index. BigInt64Array.prototype.values() Returns a new...
BigUint64Array - JavaScript
ll elements in the array pass the test provided by a function. See also Array.prototype.every(). BigUint64Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). BigUint64Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). BigUint64Array.prototype.find() Returns the found value in the array if an element in the array satisfies the provided testing function, or undefined if not found. See also Array.prototype.find(). BigUint64Array.prototype.findIndex() Returns the found index in the array if an element in the array satisfies the provided testing function, or -1 if not found. ...
...dex() Returns the found index in the array if an element in the array satisfies the provided testing function, or -1 if not found. See also Array.prototype.findIndex(). BigUint64Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). BigUint64Array.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). BigUint64Array.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). BigUint64Array.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). BigUint64Array.prototype.keys() ...
... of an array -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). BigUint64Array.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. BigUint64Array.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). BigUint64Array.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). BigUint64Array.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). BigUint64Array.prototype.subarray() Returns a new BigUint64Array from the given start and end element index. BigUint64Array.prototype.values() Returns a ...
Float32Array - JavaScript
er all elements in the array pass the test provided by a function. See also Array.prototype.every(). Float32Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). Float32Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Float32Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. See also Array.prototype.find(). Float32Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See ...
...ndIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Float32Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Float32Array.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). Float32Array.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). Float32Array.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). Float32Array.prototype.keys() Return...
...ements of an array -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). Float32Array.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. Float32Array.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). Float32Array.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). Float32Array.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). Float32Array.prototype.subarray() Returns a new Float32Array from the given start and end element index. Float32Array.prototype.values() Returns a new Arra...
Float64Array - JavaScript
er all elements in the array pass the test provided by a function. See also Array.prototype.every(). Float64Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). Float64Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Float64Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. See also Array.prototype.find(). Float64Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See ...
...ndIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Float64Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Float64Array.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). Float64Array.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). Float64Array.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). Float64Array.prototype.keys() Return...
...ements of an array -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). Float64Array.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. Float64Array.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). Float64Array.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). Float64Array.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). Float64Array.prototype.subarray() Returns a new Float64Array from the given start and end element index. Float64Array.prototype.values() Returns a new Arra...
Function.prototype.bind() - JavaScript
The corollary is that you need not do anything special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using new. // Example can be run d...
... The corollary is that you need not do anything special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using new. // Example can be run directly in your JavaScript console // ...continu...
... polyfill below, // works fine with native bind: const YAxisPoint = Point.bind(null, 0/*x*/); const emptyObj = {}; const YAxisPoint = Point.bind(emptyObj, 0/*x*/); const axisPoint = new YAxisPoint(5); axisPoint.toString(); // '0,5' axisPoint instanceof Point; // true axisPoint instanceof YAxisPoint; // true new YAxisPoint(17, 42) instanceof Point; // true Note that you need not do anything special to create a bound function for use with new. The corollary is that you need not do anything special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using new. // Example can be run directly in your JavaScript console // ...continued from above // Can still be called as a norma...
Generator.prototype.next() - JavaScript
eter to the next method to send a value to the generator. Syntax gen.next(value) Parameters value The value to send to the generator. The value will be assigned as a result of a yield expression. For example, in variable = yield expression, the value passed to the .next() function will be assigned to variable. Return value An Object with two properties: done (boolean) Has the value true if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. value Any JavaScript value returned by the iterator. Can be omitted when done is true. Examples Using next...
...xt() The following example shows a simple generator and the object that the next method returns: function* gen() { yield 1; yield 2; yield 3; } const g = gen(); // "Generator { }" g.next(); // "Object { value: 1, done: false }" g.next(); // "Object { value: 2, done: false }" g.next(); // "Object { value: 3, done: false }" g.next(); // "Object { value: undefined, done: true }" Using next() with a list function* getPage(pageSize = 1, list) { let output = []; let index = 0; while (index < list.length) { output = []; for (let i = index; i < index + pageSize; i++) { if (list[i]) { output.push(list[i]); } } yield output; index += pageSize; } } list = [1, 2, 3, 4, 5, 6, 7, 8] var page = getPage(3, list); /...
...] 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. Note that the first call does not log anything, because the generator was not yielding anything initially. 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 }" ...
Int16Array - JavaScript
hether all elements in the array pass the test provided by a function. See also Array.prototype.every(). Int16Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). Int16Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Int16Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. See also Array.prototype.find(). Int16Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also...
...e.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Int16Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Int16Array.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). Int16Array.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). Int16Array.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). Int16Array.prototype.keys() Returns a ne...
...the elements of an array -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). Int16Array.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. Int16Array.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). Int16Array.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). Int16Array.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). Int16Array.prototype.subarray() Returns a new Int16Array from the given start and end element index. Int16Array.prototype.values() Returns a new Array Iterat...
Int32Array - JavaScript
hether all elements in the array pass the test provided by a function. See also Array.prototype.every(). Int32Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). Int32Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Int32Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. See also Array.prototype.find(). Int32Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also...
...e.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Int32Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Int32Array.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). Int32Array.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). Int32Array.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). Int32Array.prototype.keys() Returns a ne...
...the elements of an array -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). Int32Array.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. Int32Array.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). Int32Array.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). Int32Array.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). Int32Array.prototype.subarray() Returns a new Int32Array from the given start and end element index. Int32Array.prototype.values() Returns a new Array Iterat...
Int8Array - JavaScript
whether all elements in the array pass the test provided by a function. See also Array.prototype.every(). Int8Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). Int8Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Int8Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. See also Array.prototype.find(). Int8Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also A...
...ype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Int8Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Int8Array.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). Int8Array.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). Int8Array.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). Int8Array.prototype.keys() Returns a new A...
...of the elements of an array -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). Int8Array.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. Int8Array.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). Int8Array.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). Int8Array.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). Int8Array.prototype.subarray() Returns a new Int8Array from the given start and end element index. Int8Array.prototype.values() Returns a new Array Iterator o...
Intl.Locale.prototype.numeric - JavaScript
The Intl.Locale.prototype.numeric property is an accessor property that returns whether the locale has special collation handling for numeric characters. Description Like Intl.Locale.caseFirst, numeric represents a modification to the collation rules utilized by the locale. numeric is a Boolean value, which means that it can be either true or false. If numeric is set to false, there will be no special handling of numeric values in strings. If numeric is set to true, then the locale will take numeric characters into account when collating strings. This special numeric handling means that sequences of decimal digits will be compared as numbers. For example, the string "A-21" will be considered less than "A-123". Examples Setting the numeric value via the locale string In the Unicode locale...
...ale identifiers by using the -u extension key. Thus, the numeric value can be added to the inital locale identifier string that is passed into the Locale constructor. To set the numeric value, first add the -u extension key to the string. Next, add the -kn extension key to indicate that you are adding a value for numeric. Finally, add the numeric value to the string. If you want to set numeric to true, simply adding the kn key will suffice. 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 ...
...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. Set the numeric property of the configuration object to your desired numeric value and pass it into the constructor. let numericViaObj= new Intl.Locale("en-Latn-US", {numeric: true}); console.log(us12hour.numeric); // Prints "true" Specifications Specification ECMAScript Internationalization API (ECMA-402) ...
Map - JavaScript
d in the Map for queries. 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. Static properties get Map[@@species] The constructor fu...
...ze) // 1 Constructor Map() Creates a new Map object. Static properties get Map[@@species] The constructor function that is used to create derived objects. Instance properties Map.prototype.size Returns the number of key/value pairs in the Map object. Instance methods Map.prototype.clear() Removes all key-value pairs from the 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. Map.prototype.has(key) will return false afterwards. Map.prototype.get(key) Returns the value associated to the key, or undefined if there is none. Map.prototype.has(key) Returns a boolean asserting whether a value has been associated to the key in the Map object or not. Map.prototype.set(ke...
...sociated with keyFunc" myMap.get('a string') // "value associated with 'a string'" // because keyString === 'a string' myMap.get({}) // undefined, because keyObj !== {} myMap.get(function() {}) // undefined, because keyFunc !== function () {} Using NaN as Map keys NaN can also be used as a key. ...
Math.clz32() - JavaScript
ero integer &= (integer << 16) | 0xffff; integer &= (integer << 8 ) | 0x00ff; integer &= (integer << 4 ) | 0x000f; integer &= (integer << 2 ) | 0x0003; integer &= (integer << 1 ) | 0x0001; // 2. Now, inversing the bits reveals the lowest zeros return 32 - clon(~integer) |0; */ } Make these helper functions into ASM.JS module; then, you have a true performance masterpiece. Situations like these are exactly what ASM.JS was designed for. var countTrailsMethods = (function(stdlib, foreign, heap) { "use asm"; var clz = stdlib.Math.clz32; function ctrz(integer) { // count trailing zeros integer = integer | 0; // coerce to an integer // 1. fill in all the higher bits after the first one // ASMjs for some reaso...
... ...
... ...
Math.hypot() - JavaScript
the magnitude of your numbers is very large. The largest number you can represent in JS is Number.MAX_VALUE, which is around 10308. If your numbers are larger than about 10154, taking the square of them will result in Infinity. For example, Math.sqrt(1e200*1e200 + 1e200*1e200) = Infinity . If you use hypot() instead, you get better answer: Math.hypot(1e200, 1e200) = 1.4142...e+200 . This is also true with very small numbers. Math.sqrt(1e-200*1e-200 + 1e-200*1e-200) = 0, but Math.hypot(1e-200, 1e-200) =1.4142...e-200. Because hypot() is a static method of Math, you always use it as Math.hypot(), rather than as a method of a Math object you created (Math is not a constructor). If no arguments are given, the result is +0. If any of the arguments is +-Infinity, the result is Infinity. If any o...
...onverted to a number, the result is NaN. With one argument, Math.hypot() is equivalent to Math.abs(). ...
...0 : (arg / max) * (arg / max); } return containsInfinity ? Infinity : (max === 1 / 0 ? ...
Number.isSafeInteger() - JavaScript
alue The value to be tested for being a safe integer. Return value A Boolean indicating whether or not the given value is a number that is a safe integer. ...
...t the given value is a number that is a safe integer. ...
... ...
Object.freeze() - JavaScript
frozen with Object.freeze() are made immutable. Examples Freezing objects var obj = { prop: function() {}, foo: 'bar' }; // Before freezing: new properties may be added, // and existing properties may be changed or removed obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; // Freeze. var o = Object.freeze(obj); // The return value is just the same object we passed in. ...
...g objects var obj = { prop: function() {}, foo: 'bar' }; // Before freezing: new properties may be added, // and existing properties may be changed or removed obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; // Freeze. var o = Object.freeze(obj); // The return value is just the same object we passed in. o === obj; // true // The object has become frozen. ...
... become frozen. Object.isFrozen(obj); // === true // Now any changes will fail obj.foo = 'quux'; // silently does nothing // silently doesn't add the property obj.quaxxor = 'the friendly duck'; // In strict mode such attempts will throw TypeErrors function fail(){ 'use strict'; obj.foo = 'sparky'; // throws a TypeError delete obj.foo; // throws a TypeError delete obj.quaxxor; // returns true since attribute 'quaxxor' was never added obj.sparky = 'arf'; // throws a TypeError } fail(); // Attempted changes through Object.defineProperty; // both statements below throw a TypeError. Object.defineProperty(obj, 'ohai', { value: 17 }); Object.defineProperty(obj, 'foo', { value: 'eit' }); // It's also impossible to change the prototype // both statements below will throw a TypeError. Obj...
Object.preventExtensions() - JavaScript
avior is specific to the internal [[prototype]] property, other properties of the target object will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. Examples Using Object.preventExtensions // Object.preventExtensions returns the object // being made non-extensible. ...
... will remain mutable. There is no way to make an object extensible again once it has been made non-extensible. Examples Using Object.preventExtensions // Object.preventExtensions returns the object // being made non-extensible. var obj = {}; var obj2 = Object.preventExtensions(obj); obj === obj2; // true // Objects are extensible by default. var empty = {}; Object.isExtensible(empty); // === true // ...but that can be changed. ...
... obj = {}; var obj2 = Object.preventExtensions(obj); obj === obj2; // true // Objects are extensible by default. var empty = {}; Object.isExtensible(empty); // === true // ...but that can be changed. Object.preventExtensions(empty); Object.isExtensible(empty); // === false // Object.defineProperty throws when adding // a new property to a non-extensible object. var nonExtensible = { removable: true }; Object.preventExtensions(nonExtensible); Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // throws a TypeError // In strict mode, attempting to add new properties // to a non-extensible object throws a TypeError. function fail() { 'use strict'; // throws a TypeError nonExtensible.newProperty = 'FAIL'; } fail(); A non-extensible object's prototype is immutable: var ...
Object.prototype.propertyIsEnumerable() - JavaScript
h the exception of properties inherited through the prototype chain. If the object does not have the specified property, this method returns false. ...
...e prototype chain. If the object does not have the specified property, this method returns false. Examples A basic use of propertyIsEnumerable The following example shows the use of propertyIsEnumerable on objects and arrays: var o = {}; var a = []; o.prop = 'is enumerable'; a[0] = 'is enumerable'; o.propertyIsEnumerable('prop'); // returns true a.propertyIsEnumerable(0); // returns true User-defined vs. built-in objects The following example demonstrates the enumerability of user-defined vs. built-in properties: var a = ['is enumerable']; a.propertyIsEnumerable(0); // returns true a.propertyIsEnumerable('length'); // returns false Math.propertyIsEnumerable('random'); // returns false this.propertyIsEnumerable('Math'); // returns false Direct vs. inherite...
...le'; } firstConstructor.prototype.firstMethod = function() {}; function secondConstructor() { this.method = function() { return 'is enumerable'; }; } secondConstructor.prototype = new firstConstructor; secondConstructor.prototype.constructor = secondConstructor; var o = new secondConstructor(); o.arbitraryProperty = 'is enumerable'; o.propertyIsEnumerable('arbitraryProperty'); // returns true o.propertyIsEnumerable('method'); // returns true o.propertyIsEnumerable('property'); // returns false o.property = 'is enumerable'; o.propertyIsEnumerable('property'); // returns true // These return false as they are on the prototype which // propertyIsEnumerable does not consider (even though the last two // are iteratable with for-in) o.propertyIsEnumerab...
Object.prototype.__proto__ - JavaScript
e Object.prototype is consulted, that property will hide the one found on Object.prototype. Examples Using __proto__ var Circle = function () {}; var shape = {}; var circle = new Circle(); // Set the object prototype. // DEPRECATED. This is for example purposes only. DO NOT DO THIS in real code. ...
...ED. This is for example purposes only. DO NOT DO THIS in real code. ...
... // true // or var shape = function () {}; var p = { a: function () { console.log('a'); } }; var circle = new shape(); circle.__proto__ = p; circle.a(); // a console.log(shape.prototype === circle.__proto__); // false // or function test() {}; test.prototype.myname = function () { console.log('myname'); }; var a = new test(); console.log(a.__proto__ === test.prototype); // true a.myname(); // myname // or var fn = function () {}; fn.prototype.myname = function () { console.log('myname'); }; var obj = { __proto__: fn.prototype }; obj.myname(); // myname Specifications Specification ECMAScript (ECMA-262)The definition of 'Object.prototype.__proto__' in that specification. ...
Object - JavaScript
complex entities. Objects can be created using the Object() constructor or the object initializer / literal syntax. Description Nearly all objects in JavaScript are instances of Object; a typical object inherits properties (including methods) from Object.prototype, although these properties may be shadowed (a.k.a. overridden). However, an Object may be deliberately created for which this is not true (e.g. by Object.create(null)), or it may be altered so that this is no longer true (e.g. with Object.setPrototypeOf). Changes to the Object prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to overri...
...t. Object.prototype.watch() Adds a watchpoint to a property of the object. Examples Using Object given undefined and null types The following examples store an empty Object object in o: let o = new Object() let o = new Object(undefined) let o = new Object(null) Using Object to create Boolean objects The following examples store Boolean objects in o: // equivalent to o = new Boolean(true) let o = new Object(true) // equivalent to o = new Boolean(false) let o = new Object(Boolean()) Object prototypes When altering the behavior of existing Object.prototype methods, consider injecting code by wrapping your extension before or after the existing logic. For example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extens...
...super" in some other languages. // Even though valueOf() doesn't take arguments, some other hook may. return current.apply(this, arguments); } } Since JavaScript doesn't exactly have sub-class objects, prototype is a useful workaround to make a "base class" object of certain functions that act as objects. ...
handler.defineProperty() - JavaScript
ject.defineProperty(target, prop, descriptor) will not throw an exception. In strict mode, a false return value from the defineProperty() handler will throw a TypeError exception. Examples Trapping of defineProperty The following code traps Object.defineProperty(). ...
...) will not throw an exception. In strict mode, a false return value from the defineProperty() handler will throw a TypeError exception. Examples Trapping of defineProperty The following code traps Object.defineProperty(). ...
...n exception. In strict mode, a false return value from the defineProperty() handler will throw a TypeError exception. Examples Trapping of defineProperty The following code traps Object.defineProperty(). ...
handler.preventExtensions() - JavaScript
tExtensions() method must return a boolean value. Description The handler.preventExtensions() method is a trap for Object.preventExtensions(). ...
...ollowing invariants are violated, the proxy will throw a TypeError: Object.preventExtensions(proxy) only returns true if Object.isExtensible(proxy) is false. Examples Trapping of preventExtensions The following code traps Object.preventExtensions(). const p = new Proxy({}, { preventExtensions: function(target) { console.log('called'); Object.preventExtensions(target); return true; } }); console.log(Object.preventExtensions(p)); // "called" // false The following code violates the invariant. ...
...Extensions(). const p = new Proxy({}, { preventExtensions: function(target) { console.log('called'); Object.preventExtensions(target); return true; } }); console.log(Object.preventExtensions(p)); // "called" // false The following code violates the invariant. const p = new Proxy({}, { preventExtensions: function(target) { return true; } }); Object.preventExtensions(p); // TypeError is thrown Specifications Specification ECMAScript (ECMA-262)The definition of '[[PreventExtensions]]' in that specification. ...
Reflect.construct() - JavaScript
When using Object.cr...
...When using Object.create() and Function.prototype.apply(), the new.ta...
...ut: // OneClass // function OneClass { ... } let obj2 = Reflect.construct(OneClass, args, OtherClass) // Output: // OneClass // function OtherClass { ... } let obj3 = Object.create(OtherClass.prototype); OneClass.apply(obj3, args) // Output: // OneClass // undefined Examples Using Reflect.construct() let d = Reflect.construct(Date, [1776, 6, 4]) d instanceof Date // true d.getFullYear() // 1776 Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect.construct' in that specification. ...
Reflect.deleteProperty() - JavaScript
d. Exceptions A TypeError, if target is not an Object. Description The Reflect.deleteProperty method allows you to delete a property on an object. It returns a Boolean indicating whether or not the property was successfully deleted. It is almost identical to the non-strict delete operator. ...
... to delete a property on an object. It returns a Boolean indicating whether or not the property was successfully deleted. It is almost identical to the non-strict delete operator. ...
... not the property was successfully deleted. It is almost identical to the non-strict delete operator. Examples Using Reflect.deleteProperty() let obj = { x: 1, y: 2 } Reflect.deleteProperty(obj, 'x') // true obj // { y: 2 } let arr = [1, 2, 3, 4, 5] Reflect.deleteProperty(arr, '3') // true arr // [1, 2, 3, undefined, 5] // 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
ook for the property. propertyKey The name of the property to check. Return value A Boolean indicating whether or not the target has the property. Exceptions A TypeError, if target is not an Object. Description The Reflect.has method allows you to check if a property is in an object. It works like the in operator as a function. ...
...property to check. Return value A Boolean indicating whether or not the target has the property. Exceptions A TypeError, if target is not an Object. Description The Reflect.has method allows you to check if a property is in an object. It works like the in operator as a function. ...
...property is in an object. It works like the in operator as a function. Examples Using Reflect.has() Reflect.has({x: 0}, 'x') // true Reflect.has({x: 0}, 'y') // false // returns true for properties in the prototype chain Reflect.has({x: 0}, 'toString') // Proxy with .has() handler method obj = new Proxy({}, { has(t, k) { return k.startsWith('door') } }); Reflect.has(obj, 'doorbell') // true Reflect.has(obj, 'dormitory') // false Reflect.has returns true for any inherited properties, like the in operator: const a = {foo: 123} const b = {__proto__: a} const c = {__proto__: b} // The prototype chain is: c -> b -> a Reflect.has(c, 'foo') // true Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect.has' in that specification. ...
Reflect.set() - JavaScript
Return value A Boolean indicating whether or not setting the property was successful. Exceptions A TypeError, if target is not an Object. Description The Reflect.set method allows you to set a property on an object. It does property assignment and is like the property accessor syntax as a function. ...
...TypeError, if target is not an Object. Description The Reflect.set method allows you to set a property on an object. It does property assignment and is like the property accessor syntax as a function. Examples Using Reflect.set() // Object let obj = {} Reflect.set(obj, 'prop', 'value') // true obj.prop // "value" // Array let arr = ['duck', 'duck', 'duck'] Reflect.set(arr, 2, 'goose') // true arr[2] // "goose" // It can truncate an array. ...
...o set a property on an object. It does property assignment and is like the property accessor syntax as a function. Examples Using Reflect.set() // Object let obj = {} Reflect.set(obj, 'prop', 'value') // true obj.prop // "value" // Array let arr = ['duck', 'duck', 'duck'] Reflect.set(arr, 2, 'goose') // true arr[2] // "goose" // It can truncate an array. Reflect.set(arr, 'length', 1) // true arr // ["duck"] // With just one argument, propertyKey and value are "undefined". let obj = {} Reflect.set(obj) // true Reflect.getOwnPropertyDescriptor(obj, 'undefined') // { value: undefined, writable: true, enumerable: true, configurable: true } Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect.set' in that specification. ...
Set.prototype.has() - JavaScript
he specified value exists in a Set object or not. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax mySet.has(value); Parameters value The value to test for presence in the Set object. ...
...ters value The value to test for presence in the Set object. Return value Returns true if an element with the specified value exists in the Set object; otherwise false. Note: Technically speaking, has() uses the sameValueZero algorithm to determine whether the given element is found. ...
... in the Set object; otherwise false. Note: Technically speaking, has() uses the sameValueZero algorithm to determine whether the given element is found. Examples Using the has method var mySet = new Set(); mySet.add('foo'); mySet.has('foo'); // 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.endsWith() - JavaScript
The endsWith() method determines whether a string ends with the characters of a specified string, returning true or false as appropriate. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.endsWith(searchString[, length]) Parameters searchString The characters to be searched for at the end of str. length Optional If provided, it is used as the length of str. Defaults to str.length. Return value true if the given characters are found at the end of the string; otherwise, false. Description This method lets you determine whether or not a string ends with another string. This method is case-sensitiv...
... ...
... ...
String.prototype.localeCompare() - JavaScript
value 'check'.localeCompare('against'); // 2 or 1 (or some other positive value) // "a" and "a" are equivalent yielding a neutral value of zero 'a'.localeCompare('a'); // 0 Sort an array localeCompare() enables case-insensitive sorting for an array. let items = ['reserve', 'Premier', 'Cliche', 'communique', 'cafe', 'Adieu']; items.sort( (a, b) => a.localeCompare(b, 'fr', {ignorePunctuation: true})); // ['Adieu', 'cafe', 'Cliche', 'communique', 'Premier', 'reserve'] Check browser support for extended arguments The locales and options arguments are not supported in all browsers yet. 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() {...
... ECMAScript Internationalization API (ECMA-402)The definition of 'String.prototype.localeCompare' in that specification. ...
... ECMAScript Internationalization API (ECMA-402)The definition of 'String.prototype.localeCompare' in that specification. ...
String.prototype.normalize() - JavaScript
ze() using the "NFD" or "NFC" arguments to produce a form of the string that will be the same for all canonically equivalent strings. In the example below we normalize two representations of the character "n": let string1 = '\u00F1'; // n let string2 = '\u006E\u0303'; // n string1 = string1.normalize('NFD'); string2 = string2.normalize('NFD'); console.log(string1 === string2); // true console.log(string1.length); // 2 console.log(string2.length); // 2 Composed and decomposed forms Note that the length of the normalized form under "NFD" is 2. That's because "NFD" gives you the decomposed version of the canonical form, in which single code points are split into multiple combining ones. The decomposed canonical form for "n" is "\u006E\u0303". You can specify "NFC" t...
... the composed canonical form, in which multiple code points are replaced with single code points where possible. The composed canonical form for "n" is "\u00F1": let string1 = '\u00F1'; // n let string2 = '\u006E\u0303'; // n string1 = string1.normalize('NFC'); string2 = string2.normalize('NFC'); console.log(string1 === string2); // true console.log(string1.length); // 1 console.log(string2.length); // 1 console.log(string2.codePointAt(0).toString(16)); // f1 Compatibility normalization In Unicode, two sequences of code points are compatible if they represent the same abstract characters, and should be treated alike in some -- but not necessarily all -- applications. All canonically eq...
...In the example above the normalization is appropriate for search, because it enables a user to find the string by searching for "f". But it...
String.prototype.trimStart() - JavaScript
pe.padStart the standard method name is trimStart. However, for web compatibility reasons, trimLeft remains as an alias to trimStart. ...
...dStart the standard method name is trimStart. However, for web compatibility reasons, trimLeft remains as an alias to trimStart. ...
...(w){ var String=w.String, Proto=String.prototype; (function(o,p){ if(p in o?o[p]?false:true:true){ var r=/^\s+/; o[p]=o.trimLeft||function(){ return this.replace(r,'') } } })(Proto,'trimStart'); })(window); /* ES6: (w=>{ const String=w.String, Proto=String.prototype; ((o,p)=>{ if(p in o?o[p]?false:true:true){ const r=/^\s+/; o[p]=o.trimLeft||function(){ return this.replace(r,'') } } })(Proto,'trimStart'); })(window); */ Examples Using trimStart() The following example displays the lowercase string 'foo ': var str = ' foo '; console.log(str.length); // 8 str = str.trimStart(); console.log(str.length); // 5 console.log(st...
TypedArray.prototype.every() - JavaScript
every(callback[, thisArg]) Parameters callback Function to test for each element, taking three arguments: currentValue The current element being processed in the typed array. index The index of the current element being processed in the typed array. array The typed array every was called upon. thisArg Optional. Value to use as this when executing callback. 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. O...
... 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. Otherwise, if callback returned a true value for all elements, every will return true. callback is invoked with three arguments: the value of the element, the index of the element, and the array object being traversed. If a thisArg parameter is provided to every, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. The this value ultimately o...
...ry does not mutate the typed array on which it is called. Examples Testing size of all typed array elements The following example tests whether all elements in the typed array are bigger than 10. function isBigEnough(element, index, array) { return element >= 10; } new Uint8Array([12, 5, 8, 130, 44]).every(isBigEnough); // false new Uint8Array([12, 54, 18, 130, 44]).every(isBigEnough); // true Testing typed array elements using arrow functions Arrow functions provide a shorter syntax for the same test. new Uint8Array([12, 5, 8, 130, 44]).every(elem => elem >= 10); // false new Uint8Array([12, 54, 18, 130, 44]).every(elem => elem >= 10); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'TypedArray.prototype.every' in that specification. ...
TypedArray.prototype.includes() - JavaScript
This method has the same algorithm as Array.prototype.includes(). TypedArray is one of the typed array types here. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax typedarray.includes(searchElement[, fromIndex]); Parameters searchElement The element to search for. fromIndex Optional. The position in this array at which to begin searching for searchElement; defaults to 0. ...
...com/mdn/interactive-examples and send us a pull request. Syntax typedarray.includes(searchElement[, fromIndex]); Parameters searchElement The element to search for. fromIndex Optional. The position in this array at which to begin searching for searchElement; defaults to 0. Return value A Boolean. ...
...Element[, fromIndex]); Parameters searchElement The element to search for. fromIndex Optional. The position in this array at which to begin searching for searchElement; defaults to 0. Return value A Boolean. 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.prototype.includes' in that specification. ...
TypedArray - JavaScript
hether all elements in the array pass the test provided by a function. See also Array.prototype.every(). TypedArray.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). TypedArray.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). TypedArray.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function, or undefined if not found. See also Array.prototype.find(). TypedArray.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See als...
...e.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). TypedArray.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). TypedArray.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). TypedArray.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). TypedArray.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). TypedArray.prototype.keys() Returns a ne...
...the elements of an array -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). TypedArray.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. TypedArray.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). TypedArray.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). TypedArray.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). TypedArray.prototype.subarray() Returns a new TypedArray from the given start and end element index. TypedArray.prototype.values() Returns a new Array Iterat...
Uint16Array - JavaScript
ther all elements in the array pass the test provided by a function. See also Array.prototype.every(). Uint16Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). Uint16Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Uint16Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. See also Array.prototype.find(). Uint16Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See al...
...findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Uint16Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Uint16Array.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). Uint16Array.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). Uint16Array.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). Uint16Array.prototype.keys() Returns a...
... elements of an array -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). Uint16Array.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. Uint16Array.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). Uint16Array.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). Uint16Array.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). Uint16Array.prototype.subarray() Returns a new Uint16Array from the given start and end element index. Uint16Array.prototype.values() Returns a new Array It...
Uint32Array - JavaScript
ther all elements in the array pass the test provided by a function. See also Array.prototype.every(). Uint32Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). Uint32Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Uint32Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. See also Array.prototype.find(). Uint32Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See al...
...findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Uint32Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Uint32Array.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). Uint32Array.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). Uint32Array.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). Uint32Array.prototype.keys() Returns a...
... elements of an array -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). Uint32Array.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. Uint32Array.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). Uint32Array.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). Uint32Array.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). Uint32Array.prototype.subarray() Returns a new Uint32Array from the given start and end element index. Uint32Array.prototype.values() Returns a new Array It...
Uint8Array - JavaScript
hether all elements in the array pass the test provided by a function. See also Array.prototype.every(). Uint8Array.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). Uint8Array.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Uint8Array.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. See also Array.prototype.find(). Uint8Array.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also...
...e.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Uint8Array.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Uint8Array.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). Uint8Array.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). Uint8Array.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). Uint8Array.prototype.keys() Returns a ne...
...the elements of an array -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). Uint8Array.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. Uint8Array.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). Uint8Array.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). Uint8Array.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). Uint8Array.prototype.subarray() Returns a new Uint8Array from the given start and end element index. Uint8Array.prototype.values() Returns a new Array Iterat...
Uint8ClampedArray - JavaScript
ments in the array pass the test provided by a function. See also Array.prototype.every(). Uint8ClampedArray.prototype.fill() Fills all the elements of an array from a start index to an end index with a static value. See also Array.prototype.fill(). Uint8ClampedArray.prototype.filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. See also Array.prototype.filter(). Uint8ClampedArray.prototype.find() Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found. See also Array.prototype.find(). Uint8ClampedArray.prototype.findIndex() Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not f...
... Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found. See also Array.prototype.findIndex(). Uint8ClampedArray.prototype.forEach() Calls a function for each element in the array. See also Array.prototype.forEach(). Uint8ClampedArray.prototype.includes() Determines whether a typed array includes a certain element, returning true or false as appropriate. See also Array.prototype.includes(). Uint8ClampedArray.prototype.indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. See also Array.prototype.indexOf(). Uint8ClampedArray.prototype.join() Joins all elements of an array into a string. See also Array.prototype.join(). Uint8ClampedArray.prototype...
...ray -- the first becomes the last, and the last becomes the first. See also Array.prototype.reverse(). Uint8ClampedArray.prototype.set() Stores multiple values in the typed array, reading input values from a specified array. Uint8ClampedArray.prototype.slice() Extracts a section of an array and returns a new array. See also Array.prototype.slice(). Uint8ClampedArray.prototype.some() Returns true if at least one element in this array satisfies the provided testing function. See also Array.prototype.some(). Uint8ClampedArray.prototype.sort() Sorts the elements of an array in place and returns the array. See also Array.prototype.sort(). Uint8ClampedArray.prototype.subarray() Returns a new Uint8ClampedArray from the given start and end element index. Uint8ClampedArray.prototype.values()...
WeakMap - JavaScript
o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects. ...
...(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects. ...
...t(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects. ...
isFinite() - JavaScript
nteractive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax isFinite(testValue) Parameters testValue The value to be tested for finiteness. Return value false if the argument is positive or negative Infinity or NaN or undefined; otherwise, true. Description isFinite is a top-level function and is not associated with any object. You can use this function to determine whether a number is a finite number. The isFinite function examines the number in its argument. If the argument is NaN, positive infinity, or negative infinity, this method returns false; otherwise, it returns true. Examples Using isFinite isFinite(Infinity); // false...
.... You can use this function to determine whether a number is a finite number. The isFinite function examines the number in its argument. If the argument is NaN, positive infinity, or negative infinity, this method returns false; otherwise, it returns true. ...
...to determine whether a number is a finite number. The isFinite function examines the number in its argument. If the argument is NaN, positive infinity, or negative infinity, this method 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. ...
Logical NOT (!) - JavaScript
The logical NOT (!) operator (logical complement, negation) takes truth to falsity and vice versa. It is typically used with Boolean (logical) values. When used with non-Boolean values, it returns false if its single operand can be converted to true; otherwise, returns true. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax !expr Description Returns false if its single operand can be converted to true; otherwise, returns true. If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy. Examples of expressions that can be converted...
...at are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor. Examples Using NOT The following code shows examples of the ! (logical NOT) operator. n1 = !true // !t returns false n2 = !false // !f returns true n3 = !'' // !f returns true n4 = !'Cat' // !t returns false Double NOT (!!) It is possible to use a couple of NOT operators in series to explicitly force the conversion of any value to the corresponding boolean primitive. The conversion is based on the "truthyness" or "falsyness" of the va...
... // !f returns true n4 = !'Cat' // !t returns false Double NOT (!!) It is possible to use a couple of NOT operators in series to explicitly force the conversion of any value to the corresponding boolean primitive. The conversion is based on the "truthyness" or "falsyness" of the value (see truthy and falsy). The same conversion can be done through the Boolean function. n1 = !!true // !!truthy returns true n2 = !!{} // !!truthy returns true: any object is truthy... n3 = !!(new Boolean(false)) // ...even Boolean objects with a false .valueOf()! n4 = !!false // !!falsy returns false n5 = !!"" // !!falsy returns false n6 = !!Boolean(false) // !!falsy returns false Converting between NOTs The...
Object initializer - JavaScript
Object literal notation vs JSON The object literal notation is not the same as the JavaScript Object Notation (JSON). Although they look similar, there are differences between them: JSON permits only property definition using "property": value syntax. The property name must be double-quoted, and the definition cannot be a shorthand. In JSON the values can only be strings, numbers, arrays, true, false, null, or another (JSON) object. A function value (see "Methods" above) can not be assigned to a value in JSON. Objects like Date will be a string after JSON.parse(). JSON.parse() will reject computed property names and an error will be thrown. Examples Creating objects An empty object with no properties can be created like this: let object = {} However, the advantage of the liter...
...ariables in your code that you would like to put into an object. You will see code like this: let a = 'foo', b = 42, c = {}; let o = { a: a, b: b, c: c } With ECMAScript 2015, there is a shorter notation available to achieve the same: let a = 'foo', b = 42, c = {}; // Shorthand property names (ES2015) let o = {a, b, c} // In other words, console.log((o.a === {a}.a)) // true Duplicate property names When using the same name for your properties, the second property will overwrite the first. let a = {x: 1, x: 2} console.log(a) // {x: 2} In ECMAScript 5 strict mode code, duplicate property names were considered a SyntaxError. With the introduction of computed property names making duplication possible at runtime, ECMAScript 2015 has removed this restriction. fun...
...pt 5 strict mode code, duplicate property names were considered a SyntaxError. With the introduction of computed property names making duplication possible at runtime, ECMAScript 2015 has removed this restriction. function haveES2015DuplicatePropertySemantics() { 'use strict'; try { ({prop: 1, prop: 2}); // No error thrown, duplicate property names allowed in strict mode return true; } catch(e) { // Error thrown, duplicates prohibited in strict mode return false; } } Method definitions A property of an object can also refer to a function or a getter or setter method. let o = { property: function (parameters) {}, get property() {}, set property(value) {} } In ECMAScript 2015, a shorthand notation is available, so that the keyword "function" is no longer ...
yield - JavaScript
y after the yield. throw is used to throw an exception from the generator. This halts execution of the generator entirely, and execution resumes in the caller (as is normally the case when an exception is thrown). The end of the generator function is reached. In this case, execution of the generator ends and an IteratorResult is returned to the caller in which the value is undefined and done is true. A return statement is reached. In this case, execution of the generator ends and an IteratorResult is returned to the caller in which the value is the value specified by the return statement and done is true. If an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's current yield operation. Between the generator's code path, its...
...a generator function is defined, it can be used by constructing an iterator as shown. ...
...: 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. ...
Expressions and operators - JavaScript
ors take numerical values (either literals or variables) as their operands and return a single numerical value. + Addition operator. - Subtraction operator. / Division operator. * Multiplication operator. % Remainder operator. ** Exponentiation operator. Relational operators A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true. in The in operator determines whether an object has a given property. instanceof The instanceof operator determines whether an object is an instance of another object. < Less than operator. > Greater than operator. <= Less than or equal operator. >= Greater than or equal operator. Note: => is not an operator, but the notation for Arrow functions. Equality operators The result...
...anceof operator determines whether an object is an instance of another object. < Less than operator. > Greater than operator. <= Less than or equal operator. >= Greater than or equal operator. Note: => is not an operator, but the notation for Arrow functions. Equality operators The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true. == Equality operator. != Inequality operator. === Identity operator. !== Nonidentity operator. Bitwise shift operators Operations to shift all bits of the operand. << Bitwise left shift operator. >> Bitwise right shift operator. >>> Bitwise unsigned right shift operator. Binary bitwise operators Bitwise operators treat their operands as a set of 32 bits (zeros and ones) a...
...perators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values. & Bitwise AND. | Bitwise OR. ^ Bitwise XOR. Binary logical operators Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value. && Logical AND. || Logical OR. Conditional (ternary) operator (condition ? ifTrue : ifFalse) The conditional operator returns one of two values based on the logical value of the condition. Assignment operators An assignment operator assigns a value to its left operand based on the value of its right operand. = Assignment operator. *= Multiplication assignment. /= Division assignment. %= Remainder assignment. += Addition assignment. -= Subtraction assignme...
for - JavaScript
variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement. The result of this expression is discarded. condition An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct. final-expression An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the co...
...To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. To execute no statement within the loop, use an empty statement (;). Examples Using for The following for statement starts by declaring the variable i and initializing it to 0. ...
... If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop. for (let i = 0;; i++) { console.log(i); if (i > 3) break; // more statements } You can also omit all three blocks. Again, make sure to use a break statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point. var i = 0; for (;;) { if (i > 3) break; console.log(i); i++; } Using for without a statement The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead. function showOffsetPos(sId) { var nLeft = 0, nTop = 0; for ( var oItNode = ...
var - JavaScript
e property created on the global object for global variables, is set to be non-configurable because the identifier is to be treated as a variable, rather than a straightforward property of the global object. JavaScript has automatic memory management, and it would make no sense to be able to use the delete operator on a global variable. 'use strict'; var x = 1; globalThis.hasOwnProperty('x'); // true delete globalThis.x; // TypeError in strict mode. Fails silently otherwise. delete x; // SyntaxError in strict mode. Fails silently otherwise. Note that in both NodeJS CommonJS modules and native ECMAScript modules, top-level variable declarations are scoped to the module, and are not, therefore added as properties to the global object. Unqualified identifier assignments The global object si...
...n attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global.. So you can just type: function foo() { String('s') // Note the function `String` is implicitly visible } ...because globalThis.hasOwnProperty('String') // true So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String, you can just type the unqualified String. The corollary, in non-strict mode, is that assignment to unqualified identifiers will, if there is no variable of the same name declared in the scope chain, assume you want to create a property with that name on the global object. foo ...
...ype the unqualified String. The corollary, in non-strict mode, is that assignment to unqualified identifiers will, if there is no variable of the same name declared in the scope chain, assume you want to create a property with that name on the global object. foo = 'f' // In non-strict mode, assumes you want to create a property named `foo` on the global object globalThis.hasOwnProperty('foo') // true In ECMAScript 5, this behavior was changed for strict mode. Assignment to an unqualified identifier in strict mode will result in a ReferenceError, to avoid the accidental creation of properties on the global object. Note that the implication of the above, is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables, it merely has a syntax that looks l...
while - JavaScript
The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax while (condition) statement condition An expression evaluated before each pass through the loop. If this condition evaluates to true, statement is executed. When condition evaluates to false, execution continues with the statement after the while loop. statement An optional statement that is executed as long as the condition evaluates to true. To execute multiple statements wi...
... Examples Using while The following while loop iterates as long as n is less than three. ...
...loop iterates as long as n is less than three. var n = 0; var x = 0; while (n < 3) { n++; x += n; } Each iteration, the loop increments n and adds it to x. Therefore, x and n take on the following values: After the first pass: n = 1 and x = 1 After the second pass: n = 2 and x = 3 After the third pass: n = 3 and x = 6 After completing the third pass, the condition n < 3 is no longer true, so the loop terminates. Specifications Specification ECMAScript (ECMA-262)The definition of 'while statement' in that specification. ...
<munderover> - MathML
If false (default value), the underscript is a limit under the base expression. ...
... If false (default value), the underscript is a limit under the base expression. ...
...future. Use CSS text-align instead. class, id, style Provided for use with stylesheets. href Used to set a hyperlink to a specified URI. mathbackground The background color. You can use #rgb, #rrggbb and HTML color names. mathcolor The text color. You can use #rgb, #rrggbb and HTML color names. Examples Sample rendering: Rendering in your browser: ? 0 ? <math displaystyle="true"> <munderover > <mo> &#x222B; <!--INTEGRAL--> </mo> <mn> 0 </mn> <mi> &#x221E; <!--INFINITY--> </mi> </munderover> </math> Specifications Specification Status Comment MathML 3.0The definition of 'munderover' in that specification. Recommendation Current specification MathML 2.0The definition of 'munderover' in that specification. ...
externalResourcesRequired - SVG: Scalable Vector Graphics
referenced resources that are not part of the current document are required for proper rendering of the given container or graphics element. This attribute applies to all types of resource references, including style sheets, color profiles and fonts specified by a reference using a <font-face> element or a CSS @font-face specification. ...
...n element sets externalResourcesRequired="true", then all style sheets must be available since any style sheet might affect the rendering of that element. The externalResourcesRequired attribute is not inheritable (from a sense of attribute value inheritance), but if set on a container element, its value will apply to all elements within the container. Because setting externalResourcesRequired="true" on a container element will have the effect of disabling progressive display of the contents of that container, if that container includes elements that reference external resources, authors should avoid simply setting externalResourcesRequired="true" on the outermost <svg> element on a universal basis. ...
...g externalResourcesRequired="true" on a container element will have the effect of disabling progressive display of the contents of that container, if that container includes elements that reference external resources, authors should avoid simply setting externalResourcesRequired="true" on the outermost <svg> element on a universal basis. Instead, it is better to specify externalResourcesRequired="true" on those particular graphics elements or container elements which specifically need the availability of external resources in order to render properly. Usage notes Value false | true Default value false Animatable No true This value indicates that resources external to the current document are required. If an external resource is not available, pro...
preserveAlpha - SVG: Scalable Vector Graphics
erveAlpha attribute indicates how a <feConvolveMatrix> element handled alpha transparency. ...
...In this case, the filter will temporarily unpremultiply the color component values and apply the kernel. false This value indicates that the convolution will apply to all channels, including the alpha channel. Specifications Specification Status Co...
...In this case, the filter will temporarily unpremultiply the color component values and apply the kernel. false This value indicates that the convolution will apply to all channels, including the alpha channel. Specifications Specification Status Comment Filter Effects Module Level 1T...
Using templates and slots - Web Components
ses our template as the content of its shadow DOM. We'll call it <my-paragraph>: customElements.define('my-paragraph', class extends HTMLElement { constructor() { super(); let template = document.getElementById('my-paragraph'); let templateContent = template.content; const shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(templateContent.cloneNode(true)); } } ); The key point to note here is that we append a clone of the template content to the shadow root, created using the Node.cloneNode() method. And because we are appending its contents to a shadow DOM, we can include some styling information inside the template in a <style> element, which is then encapsulated inside the custom element. This wouldn't work if we just appended it to t...
...element above. This uses exactly the same pattern as we saw in our earlier trivial example. ...
... JavaScript.</span> </element-details> <script> customElements.define('element-details', class extends HTMLElement { constructor() { super(); const template = document .getElementById('element-details-template') .content; const shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(template.cloneNode(true)); } }) </script> </body> </html> ...
lang - XPath
Web › XPath › Functions › lang
Otherwise, false. Notes A node's language is determined by its xml:lang attribute. ...
...Otherwise, false. Notes A node's language is determined by its xml:lang attribute. ...
... then the value of the xml:lang attribute of the nearest ancestor that has an xml:lang attribute will determine the current node's language. If the language cannot be determined (no ancestor has an xml:lang attribute), this function will return false. If the given string does not specify a country code, this function will match nodes of that language with any country code. The converse is not true. Given this fragment of XML: <p xml:lang="en">I went up a floor.</p> <p xml:lang="en-GB">I took the lift.</p> <p xml:lang="en-US">I rode the elevator.</p> And this part of an XSL template: <xsl:value-of select="count(//p[lang('en')])" /> <xsl:value-of select="count(//p[lang('en-GB')])" /> <xsl:value-of select="count(//p[lang('en-US')])" /> <xsl:value-of select="count(//p[lang('de')])" /> T...
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
emory. Assuming that the DOM to be processed is contained by an element with the id example, that DOM can be "cloned" using the in-memory XML document's Document.importNode() method. Document.importNode() allows transferring a DOM fragment between documents, in this case from an HTML document to an XML document. The first parameter references the DOM node to clone. By making the second parameter "true", it will clone all descendants as well (a deep clone). The cloned DOM can then be easily inserted into the XML document using Node.appendChild(), as shown in figure 2. Figure 2 : Creating an XML document based on part of a document's DOM // create a new XML document in memory var xmlRef = document.implementation.createDocument("", "", null); // we want to move a part of the DOM from an ...
...e XML document using Node.appendChild(), as shown in figure 2. Figure 2 : Creating an XML document based on part of a document's DOM // create a new XML document in memory var xmlRef = document.implementation.createDocument("", "", null); // we want to move a part of the DOM from an HTML document to an XML document. ...
...t's DOM // create a new XML document in memory var xmlRef = document.implementation.createDocument("", "", null); // we want to move a part of the DOM from an HTML document to an XML document. // importNode is used to clone the nodes we want to process via XSLT - true makes it do a deep clone var myNode = document.getElementById("example"); var clonedNode = xmlRef.importNode(myNode, true); // add the cloned DOM into the XML document xmlRef.appendChild(clonedNode); Once the stylesheet has been imported, XSLTProcessor has to perform two methods for the actual transformation, namely XSLTProcessor.transformToDocument() and XSLTProcessor.transformToFragment(). XSLTProcessor.transformToDocument() returns a full XML document while XSLTProcessor.transformToFragment() returns a doc...
Understanding WebAssembly text format - WebAssembly
obal.get $g) (i32.const 1)))) ) This looks similar to what we've seen before, except that we specify a global value using the keyword global, and we also specify the keyword mut along with the value's datatype if we want it to be mutable. To create an equivalent value using JavaScript, you'd use the WebAssembly.Global() constructor: const global = new WebAssembly.Global({value: "i32", mutable: true}, 0); WebAssembly Memory The above example is a pretty terrible logging function: it only prints a single integer! What if we wanted to log a text string? To deal with strings and other more complex data types, WebAssembly provides memory (although we also have Reference types in newer implementation of WebAssembly). According to WebAssembly, memory is just a large array of bytes that can grow...
...s, shared memories and atomic memory accesses. Shared memories As described above, you can create shared WebAssembly Memory objects, which can be transferred between Window and Worker contexts using postMessage(), in the same fashion as a SharedArrayBuffer. ...
...ed WebAssembly Memory objects, which can be transferred between Window and Worker contexts using postMessage(), in the same fashion as a SharedArrayBuffer. ...
page-worker - Archive of obsolete content
initialized page worker instance. Parameters options : object Optional options: Name Type contentURL string The URL of the content to load in the panel. allow object An object with keys to configure the permissions on the page worker. The boolean key script controls if scripts from the page are allowed to run. script defaults to true. include string, RegExp, array of (String or RegExp) This is useful when your page worker loads a page which will redirect to other pages. A match pattern string or an array of match pattern strings. These define the documents to which the page-worker's content worker applies. At least one match pattern must be supplied. See the match-patt...
...g port for details. contentURL The URL of content to load. This can point to local content loaded from your add-on's "data" directory or remote content. Setting it loads the content immediately. allow A object describing permissions for the content. It contains a single key named script whose value is a boolean that indicates whether or not to execute script in the content. script defaults to true. include A set of match patterns to define the urls which the page-worker's content script will be applied. This is useful when using pages which redirect to other pages in your page-worker. contentScriptFile A local file URL or an array of local file URLs of content scripts to load. contentScript A string or an array of strings containing the texts of content scripts to load. contentScrip...
selection - Archive of obsolete content
ies text Gets or sets the current selection as plain text. Setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. Getting the selection when there is no current selection returns null. Setting the selection when there is no current selection throws an exception. Getting the selection when isContiguous is true returns the text of the first selection. html Gets or sets the current selection as HTML. Setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. Getting the selection when there is no current selection returns null. Setting the selection when there is no current selection throws an exception. Getting the...
...election. html Gets or sets the current selection as HTML. Setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text. Getting the selection when there is no current selection returns null. Setting the selection when there is no current selection throws an exception. Getting the selection when isContiguous is true returns the text of the first selection. isContiguous true if the current selection is a single, contiguous selection, and false if there are two or more discrete selections, each of which may or may not be spatially adjacent. (Discontiguous selections can be created by the user with Ctrl+click-and-drag.) Events select This event is emitted whenever the user makes a new selection in a page. ...
simple-prefs - Archive of obsolete content
tes These are attributes that all preferences may have: Attribute Description description This appears below the preference title in the Add-ons Manager UI. value A default value for the preference. Depending on the preference type, this may be an integer, string, or boolean value. hidden A Boolean value which, if present and set to true, means that the preference won't appear in the Add-ons Manager interface, so users of your add-on won't be able to see or alter it. { "name": "myHiddenInteger", "type": "integer", "title": "How Many?", "hidden": true } Your add-on's code will still be able to access and modify it, just like any other preference you define. Type-Specific Attributes These are s...
...erence types themselves. Preference Types The setting types map to the inline settings types used by the Add-on Manager. All the inline preferences are supported. Type Description Example Specification bool Displayed as a checkbox and stores a boolean. { "description": "Does it have tentacles?", "type": "bool", "name": "hasTentacles", "value": true, "title": "Tentacles" } boolint Displayed as a checkbox and stores an integer. A boolint is presented to the user as a checkbox, but instead of storing true or false, the "on" or "off" checkbox states are mapped to integers using "on" or "off" properties in the specification. To provide this mapping the boolint requires two mandatory attributes called "on" and "...
content/symbiont - Archive of obsolete content
contentScriptOptions object Read-only value exposed to content scripts under self.options property. Any kind of jsonable value (object, array, string, etc.) can be used here. Optional. allow object Permissions for the content, with the following keys: script boolean Whether or not to execute script in the content. Defaults to true. Optional. Optional. Symbiont Symbiont is composed from the Worker trait, therefore instances of Symbiont and their descendants expose all the public properties exposed by Worker along with additional public properties that are listed below: Properties contentScriptFile The local file URLs of content scripts to load. Content scripts specified by this property are loaded before thos...
... ...
frame/hidden-frame - Archive of obsolete content
Globals Constructors HiddenFrame(options) Creates a hidden frame. Parameters options : object Required options: Name Type onReady function,array Functions to call when the frame is ready to load content. You must specify an onReady callback and refrain from usi...
... Globals Constructors HiddenFrame(options) Creates a hidden frame. Parameters options : object Required options: Name Type onReady function,array Functions to call when the frame is ready to load content. You must specify an onReady callback and refrain from using the...
frame/utils - Archive of obsolete content
.document); Optionally create can be passed set of options to configure created frame even further. Execution of scripts may easily be enabled: let { open } = require('sdk/window/utils'); let { create } = require('sdk/frame/utils'); let window = open('data:text/html,top'); let frame = create(window.document, { uri: 'data:text/html,<script>console.log("running");</script>', allowJavascript: true }); } Globals Functions create(document, options) Creates a XUL browser element in a privileged document. Parameters document : nsIDOMDocument options : object Optional options: Name Type type String String that defines access type of the document loaded into it. Defaults to "content". For more details and other possible values see documentation ...
...object Optional options: Name Type type String String that defines access type of the document loaded into it. Defaults to "content". For more details and other possible values see documentation on MDN uri String URI of the document to be loaded into the new frame. Defaults to about:blank. remote Boolean If true separate process will be used for this frame, and all the following options are ignored. allowAuth Boolean Whether to allow auth dialogs. Defaults to false. allowJavascript Boolean Whether to allow Javascript execution. Defaults to false. allowPlugins Boolean Whether to allow plugin execution. Defaults to false. Re...
io/file - Archive of obsolete content
returned. Parameters path : string The path of a file. Returns string : The last component of the given path. dirname(path) Returns the path of the directory containing the given file. If the file is at the top of the volume, the empty string is returned. Parameters path : string The path of a file. Returns string : The path of the directory containing the file. exists(path) Returns true if a file exists at the given path and false otherwise. Parameters path : string The path of a file. Returns boolean : True if the file exists and false otherwise. join(...) Takes a variable number of strings, joins them on the file system's path separator, and returns the result. Parameters ... : strings A variable number of strings to join. The first string must be an absolute path. ...
...ring : A string containing the file's entire contents. remove(path) Removes a file from the file system. To remove directories, use rmdir. Parameters path : string The path of the file to remove. rmdir(path) Removes a directory from the file system. If the directory is not empty, an exception is thrown. Parameters path : string The path of the directory to remove. isFile(path) Returns true only if this path specifies a file. const fileIO = require("sdk/io/file"); let path = "/Users/Work/"; let list = fileIO.list(path); for (i = 0; i < list.length; i++) { let item = fileIO.join(path, list[i]); if (fileIO.isFile(item)) { console.log(item + " is a file"); } else { console.log(item + " is a directory"); } } Parameters path : string The path of the object. ...
io/text-streams - Archive of obsolete content
close() Closes both the stream and its backing stream. read(numChars) Reads and returns a string from the stream. If the stream is closed, an exception is thrown. Parameters numChars : number The number of characters to read. If not given, the remainder of the stream is read. Returns string : The string read. If the stream is at the end, the empty string is returned. Properties closed True if the stream is closed. TextWriter Methods close() Flushes the backing stream's buffer and closes both the stream and the backing stream. If the stream is already closed, an exception is thrown. flush() Flushes the backing stream's buffer. write(str) Writes a string to the stream. If the stream is closed, an exception is thrown. Parameters str : string The string to write. writeAsync...
...d, also on the background thread. If the stream is already closed, an exception is thrown immediately. Parameters str : string The string to write. callback : callback callback, if given, must be a function. It's called as callback(error) when the write completes. error is an Error object or undefined if there was no error. Inside callback, this is the TextWriter object. Properties closed True if the stream is closed. ...
preferences/event-target - Archive of obsolete content
this is "", the root. ...
...the same branch which reqire("sdk/simple-prefs") does var target = PrefsTarget({ branchName: "extensions." + require("sdk/self").preferencesBranch + "." }); target.once("test", function(prefName) { console.log(prefName) // logs "test" console.log(target.prefs[name]) // logs true }); target.once("", function() { console.log(prefName) // logs "test" console.log(target.prefs[name]) // logs true }) // changing a pref which our target listens to require("sdk/simple-prefs").prefs.test = true; ...
system/xul-app - Archive of obsolete content
ation about the application on which your add-on is running. With the exception of ids, each of these properties exposes the attribute of the same name on the nsIXULAppInfo interface. For more information, see the MDN documentation. Globals Functions is(name) Checks whether the host application is the given application. Parameters name : string A host application name. Returns boolean : True if the host application is name and false otherwise. isOneOf(names) Checks whether the host application is one of the given applications. Parameters names : array An array of host application names. Returns boolean : True if the host application is one of the names and false otherwise. versionInRange(version, lowInclusive, highExclusive) Compares a given version to a version range. See t...
... Compares a given version to a version range. See the MDN documentation for details on version comparisons. Parameters version : string The version to compare. lowInclusive : string The lower bound of the version range to compare. The range includes this bound. highExclusive : string The upper bound of the version range to compare. The range does not include this bound. Returns boolean : True if version falls in the given range and false otherwise. Properties ID The GUID of the host application. For example, for Firefox this value is "{ec8030f7-c20a-464f-9b0e-13a3a9e97384}". name The host application name. The possible values here are: "Firefox" "Fennec" "Mozilla" "SeaMonkey" "Sunbird" "Thunderbird" "Firefox"and"Fennec"` are the most commonly used values. version The ...
tabs/utils - Archive of obsolete content
ified tab. Parameters tab : tab A browser tab. Returns window : A browser window. openTab(window, url, options) Open a new tab in the specified browser window. Parameters window : window The browser window in which to open the tab. url : String URL for the document to load. ...
... closeTab(tab) Close the specified tab. Parameters tab : tab A XUL tab element. getURI(tab) Get the specified tab's URI. Parameters tab : tab A XUL tab element. Returns String : The current URI. getTabBrowserForTab(tab) Get the specified tab's tabbrowser. Parameters tab : tab A XUL tab element. ...
ui/button/action - Archive of obsolete content
", firstClick); button.on("click", subsequentClicks); } function subsequentClicks(state) { console.log("You clicked '" + state.label + "' again"); } The listener is passed a state object that contains all the button's properties. You can generate click events programmatically with the button's click() method. Disabling buttons You can disable a button by setting its disabled property to true. A disabled button will not generate click events and its icon will appear disabled: Updating state You can update all the button's properties except for its id. By default, the button has global state: that is, its properties are the same across all open windows and tabs, and updating them updates the button's state across all open windows and tabs. You can set state to be specific to a wi...
... Destroying buttons When you've finished with a button, destroy it by calling its destroy() method. After that, any attempts t...
ui/button/toggle - Archive of obsolete content
.png" }, onChange: handleChange }); var panel = panels.Panel({ contentURL: self.data.url("panel.html"), onHide: handleHide }); function handleChange(state) { if (state.checked) { panel.show({ position: button }); } } function handleHide() { button.state('window', {checked: false}); } Disabling buttons You can disable a button by setting its disabled property to true. A disabled button will not generate click or change events and its icon will appear disabled: Updating state You can update all the button's properties, except for its id. Depending on your application, you might want a button to have different state in different browser windows or different tabs. For example, you might want to give it a different appearance when the current page is being s...
... Updating checked You can update a toggle button's checked property in just the same way you update its other properties, but ...
ui/toolbar - Archive of obsolete content
new Frame({ url: "./frame-player.html" }); var toolbar = Toolbar({ title: "Player", items: [previous, next, play, frame] }); The toolbar appears just above the content window: To destroy a Toolbar call its destroy() method. Showing and hiding toolbars By default, a toolbar is shown when it is created, although you can specify that a toolbar should be hidden initially by passing hidden:true as an option in its constructor. After that, though, you can't show or hide the toolbar programmatically. Toolbars get a close button at the right-hand side, and users can show or hide the toolbar using the Firefox "View/Toolbars" menu, alongside built-in toolbars like the Bookmarks Toolbar. Hidden state persists even over create/destroy cycles: if a toolbar is created, then hidden, then destro...
...This appears as the name of the toolbar in the Firefox "Toolbars" menu. It must be uniq...
util/object - Archive of obsolete content
n the left are overwritten by a same named property of an object on the right. Properties are merged with descriptors onto the source object. Any argument given with "falsy" values (null, undefined) in case of objects are skipped. ...
... arguments : object n amount of additional objects that are merged into source object. Returns object : The source object. ...
package.json - Archive of obsolete content
add-on's em:name element in its install.rdf. harnessClassID Note: This is deprecated along with cfx; it's not available when using jpm. String in the GUID format. This is used as a classID of the "harness service" XPCOM component. Defaults to a random GUID generated by cfx. hasEmbeddedWebExtension New in jpm 1.2.0. Boolean value: true if the add-on contains an embedded WebExtension. homepage The URL of the add-on's website. This value will be used as the add-on's em:homepageURL element in its install.rdf. icon The path to an image file containing the icon for the add-on. Optional: you can have no icon field in package.json and put your icon named "icon.png" in the root directory o...
... Note: This is deprecated along with cfx and is not available when using jpm. A string pointing to a directory containing additional packages. Defaults to "packages". permissions An object describing the set of permissions that the add-on needs. private-browsing: a boolean indicating whether or not the add-on supports private browsing. If this value is not true or is omitted, then the add-on will not see any private windows or objects, such as tabs, that are associated with private windows. See the documentation for the private-browsing module. cross-domain-content: a list of domains for which content scripts are given cross-domain privileges to access content in iframes or to make XMLHTTPRequests. See the documentation for enabling cross-domain co...
Customizing the download progress bar - Archive of obsolete content
Now your new progress bar image will only be used for the downloads with your special attribute. ...
...Now your new progress bar image will only be used for the downloads with your special attribute. ...
Drag & Drop - Archive of obsolete content
Dropping files onto an XUL application It's possible to setup drag and drop events to handle dropping files from external applications or OS file managers onto your XUL-based application. First, you need to hook up the basic drag event handlers: elem.addEventListener("dragover", _dragOver, true); elem.addEventListener("dragdrop", _dragDrop, true); Here, elem could be a window or an XUL element. Next, setup the handlers so that files can be dropped on the application: function _dragOver(aEvent) { var dragService = Components.classes["@mozilla.org/widget/dragservice;1"].getService(Components.interfaces.nsIDragService); var dragSession = dragService.getCurrentSession(); var supported = dragSession.isDataFlavorSupported("text/x-moz-url"); if (!supported) supported = ...
...var dragService = Components.classes["@mozilla.org/widget/dragservice;1"].getService(Components.interfaces.nsIDragService); var dragSession = dragService.getCurrentSession(); var supported = dragSession.isDataFlavorSupported("text/x-moz-url"); if (!supported) supported = dragSession.isDataFlavorSupported("application/x-moz-file"); if (supported) dragSession.canDrop = true; } function _dragDrop(aEvent) { var dragService = Components.classes["@mozilla.org/widget/dragservice;1"].getService(Components.interfaces.nsIDragService); var dragSession = dragService.getCurrentSession(); var _ios = Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService); var uris = new Array(); // If sourceNode is not nu...
Forms related code snippets - Archive of obsolete content
ld(document.createTextNode(nDay)); } else { oTD.className = sPrefs + "-empty-cell"; } oTR.appendChild(oTD); } this.display.innerHTML = sMonthsNames[this.current.getMonth()] + " " + this.current.getFullYear(); this.container.appendChild(this.oTBody); }; function onDocClick (oPssEvt) { const oEvt = oPssEvt || /* IE */ window.event; var bOutside = true; for (var oNode = oEvt.target || /* IE */ oEvt.srcElement; oNode; oNode = oNode.parentNode) { if (oNode.className === sPrefs + "-calendar" || oNode.className === sDPClass) { bOutside = false; break; } } if (bOutside) { return; } aInstances[oNode.id.replace(rBgnNaN, "")].container.style.zIndex = nZIndex++; } function onHeadClick () { const bIsMo...
...addEventListener("load", buildCalendars, false) : window.attachEvent ? attachEvent("onload", bu...
Miscellaneous - Archive of obsolete content
xcludes textareas for simplicity, but onPageLoad() can easily be // modified to cycle through textareas as well. Further enhancements would include // handling for fields dynamically added to the page (e.g., by page javascript). 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). addEventListener("focus", function(e) {onFocusInput(e);}, false); inputList.item(i). addEventListener("blur", function(e) {onBlurInput(e);}, false); } } function onFocus...
...See How to Build an XPCOM Component in Javascript for details. Now are your certificates installed on every application startup. Unfortunately that seems to be the only working solution, apart from modifyin...
Listening to events in Firefox extensions - Archive of obsolete content
t This event works the same as the load event, except that it fires every time the page is loaded (whereas the load event doesn't fire in Firefox 1.5 when the page is loaded from cache). The first time the page loads, the pageshow event fires just after the firing of the load event. The pageshow event uses a boolean property called persisted that is set to false on the initial load. It is set to true if it is not the initial load (in other words, it is set to true when the page is cached). Set any JavaScript that you want to run every time a page loads to run when the pageshow event fires. If you call JavaScript functions as part of the pageshow event, you can ensure these functions are called when the page is loaded in browsers other than Firefox 1.5 by calling the pageshow event as part o...
...is article. pagehide event If you want to define behavior that occurs when the user navigates away from the page, but you don't want to use the unload event (which would cause the page to not be cached), you can use the new pagehide event. Like pageshow, the pagehide event uses a boolean property called persisted. 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. Firefox 1.5 tries to simulate load events in the same order they would occur when the page is initially loaded. Frames are treated the same way as the top-level document. If the page contains frames, then when the cached page is loaded: pageshow...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
e "./" on Linux require no special handling. Listing 6: Creating an XPCOM object representing a file var file = Components.classes['@mozilla.org/file/local;1'] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath('C:\\temp\\temp.txt'); Creating and deleting files Listing 7 shows how to delete a file if it exists, and create a new file with the same name. Passing true as a parameter for the nsILocalFile.remove() method will recursively delete folders and files. Let's see what happens when we pass true to delete all the contents of a folder. Listing 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 nsILocal...
...re, we're outputting a text file consisting of the ASCII characters "XUL." When we initialized nsIFileInputStream, we set the second and third parameters to initialize it in write-only mode. Here again, once the process is complete, you should close all streams. ...
Adding menus and submenus - Archive of obsolete content
<!-- Your menuitem goes here. --> </menupopup> </menu> </menupopup> Now let's look at some specialized types of menu items. Menu types Checkbox Menu Items You can make a menuitem "checkable" to allow the user to enable/disable options using the menu. We use two attributes for this: type and checked. The type attribute must be set to "checkbox". You can set the checked attribute to "true" to check it by default. The item's checked state changes when the user clicks on it. An example of one such item is the View > Status Bar item in the main Firefox menu. Radio Menu Items If you need to have a set of menuitem elements where only one of them has to be checked at any given moment, you should set the type to "radio". The name attribute is used to identify the items that belong to ...
...a set of menuitem elements where only one of them has to be checked at any given moment, you should set the type to "radio". The name attribute is used to identify the items that belong to the radio group. <menupopup oncommand="XULSchoolChrome.HW.GreetingDialog.greeting(event);"> <menuitem type="radio" name="xulschoolhello-greeting-radio" label="&xulschoolhello.greet.short.label;" checked="true" /> <menuitem type="radio" name="xulschoolhello-greeting-radio" label="&xulschoolhello.greet.medium.label;" /> <menuitem type="radio" name="xulschoolhello-greeting-radio" label="&xulschoolhello.greet.long.label;" /> </menupopup> This is a modified version of the 3 greeting menus. It is now implemented as a radio menu where you pick one of the 3 available choices. The first one is ch...
Connecting to Remote Content - Archive of obsolete content
You can see that an instance of the XMLHttpRequest class is created and it holds all functionality for making a request. We create this instance using XPCOM instead of the usual way (new XMLHttpRequest()) because this way works both in chrome and non-chrome code. Following initializatio...
.... request.overrideMimeType("text/xml"); // do this before sending the request! The open method takes two required parameters: the HTTP request method and the URL to send the request. The HTTP request method can be "GET", "POST" or "PUT". Sending a POST request requires you to set the content type of the request and to pass the post data to the send() method as below. request.open("POST", url, true); request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); request.send("data=hello&version=2"); The third parameter for the open method specifies whether the request should be handled asynchronously or not. In asynchronous mode code execution continues immediately after the send call. In synchronous mode the code and user interface are blocked while waiting for a response...
XPCOM Objects - Archive of obsolete content
And, finally, the factory object. var CounterFactory = { /* Single instance of the component. */ _singletonObj: null, createInstance: function(aOuter, aIID) { if (aOuter != null) { throw Cr.NS_ERROR_NO_AGGREGATION; } // in this case we need a unique instance of the service. if (!thi...
... And, finally, the factory object. var CounterFactory = { /* Single instance of the component. */ _singletonObj: null, createInstance: function(aOuter, aIID) { if (aOuter != null) { throw Cr.NS_ERROR_NO_AGGREGATION; } // in this case we need a unique instance of the service. if (!this._sin...
Promises - Archive of obsolete content
mimetype) { return new Promise(accept => this.AddonManager.getInstallForFile(url, accept, mimetype)); }, getAllInstalls: function getAllInstalls() { return new Promise(accept => this.AddonManager.getAllInstalls(accept)); }, _replaceMethod: function replaceMethod(method, callback) { Object.defineProperty(this, method, { enumerable: true, configurable: true, value: key => { return new Promise(accept => this.AddonManager[method](key, addon => accept(callback(addon)))); } }); }, }; for (let method of ["getAddonByID", "getAddonBySyncGUID"]) AOM._replaceMethod(method, addon => AOM.Addon(addon)...
...gre/modules/AddonManager.jsm", AOM); Example usage: Task.spawn(function* () { // Get an extension instance, and its data directory. let addon = yield AOM.getAddonByID(ADDON_ID); let path = yield addon.getDataDirectory(); writer.writeDataTo(path); // Disable all extensions. for (let extension of yield AOM.getAddonsByTypes(["extension"])) extension.userDisabled = true; }); JSON File Storage This helper simplifies the use of JSON data storage files with asynchronous IO. The JSONStore object must be instantiated with the base name of the storage file and, optionally, a JSON-compatible object to be used if the file does not yet exist. The constructor returns a Promise which resolves when the file's contents have been loaded. The contents of the file will be in...
Adding preferences to an extension - Archive of obsolete content
We do this because since refreshInformation() is usually called as a callback from setInterval. In such cases this doesn't refer to the right object. See Method binding for detailed explanation. Once we have...
...ckWatcher.refreshInformation()" /> </statusbar> Now when the user clicks on the status bar panel, the stock information refreshes, but when they right-click on it, a context menu pops up. Defining the menu is also easy. ...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
. Because of the iframe, we backed off of the idea that we'd be able to adhere to XHTML Strict rules, and settled for using the XHTML Transitional DTD. We were hoping to go all the way with the XHTML conversion, but our ad units and some other third-party content prevent us from doing so. Our engineers also faced a huge archive of content that wasn't entered into our CMS with XHTML in mind. It's true that our stories exist in a database, separated from page templates and peripheral formatting. But writers, editors, and producers have been inserting stories into Vignette for years sans closing paragraph (</p>) tags. Unquoted attributes and uppercase html tags? We've got them in spades, and they're embedded in all past stories of the database. Fortunately, our chief engineer was able to write s...
...e, without much concentrated effort at making it so. Sure, we now pay more attention to our image alt attributes, and try to use heading tags appropriately. But a huge decrease in the amount [sic] of presentation markup tags also plays a big role too. Since all of our content is also completely accessible sans style sheets, I think we get the best of both worlds: a well-designed, highly stylized, true-to-our-brand website which adapts in different browsing environments. What would you say to a site developer considering a similar conversion to standards-based layout, either with simple tables or no tables at all? I think the conversion is a matter of taking into account several considerations. Are you tired of the maintenance headaches caused by the glut of extra tables and presentation tags...
Creating a dynamic status bar extension - Archive of obsolete content
d whenever the user clicks on the status bar panel, when our extension is first added to a browser window, and by the interval handler to periodically update the display. refreshInformation: function() { var httpRequest = null; var fullUrl = 'http://quote.yahoo.com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s=GOOG'; // ... httpRequest = new XMLHttpRequest(); httpRequest.open('GET', fullUrl, true); httpRequest.onload = infoReceived; httpRequest.send(null); } The httpRequest variable will contain an XMLHttpRequest object. This object is used to configure and run an HTTP request on a web server, which we'll use to fetch the stock quote data. The fullUrl variable is the complete URL to use when requesting a stock quote. In this case, we're using Yahoo's comma-separated values return to ...
...a-separated values return to fetch easily-parsed stock quote data for Google (ticker symbol GOOG). refreshInformation() embeds another function, infoReceived(), which we'll look at separately shortly. The first thing we do is create a new XMLHttpRequest object to use for processing our request. We open the request, specifying that we wish to perform an HTTP "GET" command with the URL fullUrl. The true Boolean value in the third parameter indicates that we want to process the request asynchronously. Setting the httpRequest.onload property to our infoReceived() function configures the request to call infoReceived() when the response is received from the server. Finally, we send the request to the server and return. infoReceived() When the server responds to our request, our the infoReceived() fu...
Using Dehydra - Archive of obsolete content
e documentation for: process_type, input_end, print, .loc property Example: using attributes to mark a class as "final" Save the following code as final.cc: // This class should not be subclassed! ...
...__((user("final"))) MyClass { }; // This subclass should be an error class SubClass : public MyClass { }; Save the following analysis script final.js: /** * Helper function: returns true if a class is marked with the "final" attribute. ...
Drag and Drop - Archive of obsolete content
vice also provides the function getCurrentSession which can be called from within the drag event handlers to get and modify the state of the drag. The function returns an object that implements nsIDragSession. The interface nsIDragSession is used to get and set properties of the drag that is currently occuring. The following properties and methods are available: canDrop Set this property to true if the element the mouse is currently over can accept the object currently being dragged to be dropped on it. Set the value to false if it doesn't make sense to drop the object on it. This should be changed in the ondragover and ondragenter event handlers. dragAction Set to the current action to be performed, which should be one or more of the constants described earlier. This can be used to p...
...will be set to 5 if five bookmarks are being dragged. getData(transfer,index) Get the data being dragged. The first argument should be an nsITransferable object to hold the data. The second argument, index, should be the index of the item to return. sourceDocument The document where the drag started. sourceNode The DOM node where the drag started. isDataFlavorSupported(flavor) Returns true if the data being dragged contains data of the specified flavor. Next >> Original Document Information Author(s): Neil Deakin Original Document: Copyright Information: Copyright (C) Neil Deakin ...
Editor Embedding Guide - Archive of obsolete content
In the Beginning there is MakeEditable Given an nsIWebBrowser instance, get an nsIDOMWindow from the GetContentDOMWindow call. Then simply call nsIWebBrowser->do_GetInterface on the nsIWebBrowser to retrieve the nsIEditingSession from it. From there you call editingSession->MakeWindowEditable(domWindow, editortype, PR_TRUE). The first parameter is the nsIDOMWindow you just retrieved, the second is the editor type you want to create, and the third is whether you want the window editable immediately or when the document is done loading. In calling this method, the editor is created underneath and the event listeners are all prepa if (NS_FAILED(rv)) return NS_ERROR_FAILURE; // we are not setup??!! nsCOMPtr<nsIEditingSession> editingSession; nsIWebBrowser->do_GetInterface(getter_AddRefs(e...
...e immediately or when the document is done loading. ...
JavaScript crypto - Archive of obsolete content
equests, importing user certs, generating random numbers, logging out of your tokens, and signing text. Handling smart card events Web sites can make themselves more SmartCard friendly by listening for SmartCard insertion and removal events. To enable your document to receive these events, you must first tell the crypto system you are interested by setting window.crypto.enableSmartCardEvents to true. You can then register event handlers for these events with the document.addEventListener() method. Two smart card related events are generated: smartcard-insert when SmartCards are inserted, and smartcard-remove when SmartCards are removed. Web sites which use SSL clientAuth login could use the following code to refresh the page on token insertions and removals: <!DOCTYPE html> <p>... <script...
...events are generated: smartcard-insert when SmartCards are inserted, and smartcard-remove when SmartCards are removed. Web sites which use SSL clientAuth login could use the following code to refresh the page on token insertions and removals: <!DOCTYPE html> <p>... ...
Java in Firefox Extensions - Archive of obsolete content
, and // (2) addURL alone does not set the grant codeBase function policyAdd (loader, urls) { try { //If have trouble with the policy try changing it to //edu.mit.simile.javaFirefoxExtensionUtils.URLSetPolicy var str = 'edu.mit.simile.javaFirefoxExtensionUtils.URLSetPolicy'; var policyClass = java.lang.Class.forName( str, true, loader ); var policy = policyClass.newInstance(); policy.setOuterPolicy(java.security.Policy.getPolicy()); java.security.Policy.setPolicy(policy); policy.addPermission(new java.security.AllPermission()); for (var j=0; j < urls.length; j++) { policy.addURL(urls[j]); } }catch(e) { alert(e+'::'+e.lineNumbe...
...tance(urlArray); //Set security policies using the above policyAdd() function policyAdd(cl, urlArray); Now you can begin using LiveConnect, including referencing the classes in your JARs. Be aware that if you have added a namespace within your classes (via "package"), you will need to reference the namespace as well. ...
Space Manager Detailed Design - Archive of obsolete content
scoord aDx, nscoord aDy) { mX += aDx; mY += aDy; } /** * Returns the current translation from local coordinate space to * world coordinate space. This represents the accumulated calls to * Translate(). */ void GetTranslation(nscoord& aX, nscoord& aY) const { aX = mX; aY = mY; } /** * Returns the y-most of the bottommost band or 0 if there are no bands. * * @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. The band data * indicates which parts of the band are available, and which parts * are unavailable * * The band data that is returned is in the coordinate space of the * local coordinate system. * * The local coordin...
... */ void Translate(nscoord aDx, nscoord aDy) { mX += aDx; mY += aDy; } /** * Returns the current translation from local coordinate space to * world coordinate space. This represents the accumulated calls to * Translate(). */ void GetTranslation(nscoord& aX, nscoord& aY) const { aX = mX; aY = mY; } /** * Returns the y-most of the bottommost band or 0 if there are no bands. * * @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. The band data * indicates which parts of the band are available, and which parts * are unavailable * * The band data that is returned is in the coordinate space of the * local coordinate system. * * The local coordinat...
File object - Archive of obsolete content
ty may be set. File.separator The system name separator (slash on UNIX). Instance Properties File.length The length of the file in bytes, or the number of entries in the directory. Note: calculating the length of the directory is very expensive. File.parent The directory containing the file. File.path The canonical path to the file. File.name The name of the file. File.isDirectory True if the file is a directory. File.isFile True if the file is a file. File.exists True if the file exists. File.canRead True if the file can be read. File.canWrite True if the file can be written. File.canAppend True if the file is in append mode. File.canReplace True if the file is in replace mode. File.isOpen True if the file is open. File.type A string specifying the type of data...
...de" (UCS-2). (XXX Note -- ASCII might imply ASCIIZ) File.mode A string describing the mode used to open the file. File.creationTime A Date object representing the time when the file was created. File.lastModified A Date object representing the time when the file was last modified. File.size The length of the file in bytes; undefined(?) for directories and pipelines. File.hasRandomAccess True if random access is supported for this file. Binary (UTF-8) files and pipelines (including File.intput) do not support random access. File.hasAutoFlush Force a flush on each line break? (readonly) File.position The file position. Writing to the property moves the file pointer. File.isNative True if the file is backed by a native stdio FILE stream. (i.e. file.input, file.output, file.error o...
Abc Assembler Tests - Archive of obsolete content
of the MPL, the GPL or the LGPL. ...
...tlocal0 pushscope findproperty START pushstring "instructions that start with the letter L" callpropvoid START 1 newfunction .function_id(runTest) getlocal0 call 0 findproperty END callpropvoid END 0 returnvoid } function runTest() { // test null <= null == True findproperty COMPARE_STRICTEQ pushstring "null lessequals null" // testname pushtrue // expected pushnull pushnull lessequals // actual callpropvoid COMPARE_STRICTEQ 3 // Use .try / .catch to catch TypeError // convert_o null .try { pushnull convert_o pop findproperty FAIL pushstring "convert_o null" pushstring "exception should have been thrown: TypeError: Error #1009: Cannot access a property or metho...
Using Breakpoints in Venkman - Archive of obsolete content
tput of the associated script. The following options are available: Continue regardless of result causes Venkman to continue normal execution after running the breakpoint script. This can be useful to try out additional code, on the fly. Stop regardless of result causes Venkman to stop execution after executing the breakpoint script, allowing you to inspect program state. Stop if result is true effectively makes this a conditional breakpoint. If the breakpoint script returns a true value (it doesn't have to strictly be a boolean true, any non-null, non-empty string, non-zero, non-undefined, and non-false value will do), execution will continue normally. If, on the other hand, the script returns a false value, Venkman will stop execution at that point. Early return from caller with res...
... to treat the output of that script. The following meta comment types are available: The //@JSD_LOG comment will insert a breakpoint which is set to execute the script that follows without stopping. The result of the evaluation will be logged to the Interactive Session. The //@JSD_BREAK comment will insert a breakpoint which is set to execute the script that follows and stop if the result is true. The //@JSD_EVAL command will insert a breakpoint which is set to execute the script that follows without stopping and without logging the result. These meta comments can be used to insert debug-only code in your scripts with zero impact on production code. To enable meta comments in a script, select "Scan for Meta Comments" from the context menu of the file in the Loaded Scripts view. When ...
modDateChanged - Archive of obsolete content
...
...eSource1, 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. // Thus, no change in 'time stamp' values. err3 = File.modDateChanged(fileSource2, err1); logComment("File.modDateChanged should return 'true' = " + err2); // the reason it expects true is we're comparing // the return 'time stamp' value for // file1.txt with another file, file2.txt, with a different // 'time stamp' value. ...
isKeyWritable - Archive of obsolete content
isKeyWritable Returns whether the given registry key is writable or not. Method of WinReg object Syntax boolean isKeyWritable( string key); Parameters The method has the following parameter: key A string representing the path to the key Returns A boolean value: true if the key is writable; false if not. ...
...KeyWritable( 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. ...
valueExists - Archive of obsolete content
valueExists Returns whether a value for the given key exists. Method of WinReg object Syntax boolean valueExists ( string key, string value ); Parameters The method has the following parameters: key A string representing the path to the key. value A string representing the value being queried. ...
...enting the path to the key. value A string representing the value being queried. Returns Boolean value: true if the key exists and the user has read access to it, otherwise false. ...
Installer Script - Archive of obsolete content
the available disk space into kilobytes 8. spaceAvailable = parseInt(spaceAvailable / 1024); 9. // do the verification 10. if(spaceAvailable < spaceRequired) 11. { 12. logComment("Insufficient disk space: " + dirPath); 13. logComment(" required : " + spaceRequired + " K"); 14. logComment(" available: " + spaceAvailable + " K"); 15. return(false); 16. } 17. return(true); 18. } 19. var srDest = 17311; 20. var err = initInstall("Netscape Seamonkey", "Browser", "6.0.0.2000110807"); 21. logComment("initInstall: " + err); 22. var communicatorFolder = getFolder("Program"); 23. logComment("communicatorFolder: " + communicatorFolder); 24. if (verifyDiskSpace(communicatorFolder, srDest)) 25. { 26. err = addDirectory("Program", 27. "6.0.0.2...
...older: " + communicatorFolder); 24. if (verifyDiskSpace(communicatorFolder, srDest)) 25. { 26. err = addDirectory("Program", 27. "6.0.0.2000110807", 28. "bin", // jar source folder 29. communicatorFolder, // target folder 30. "", // target subdir 31. true ); // force flag 32. logComment("addDirectory() returned: " + err); 33. // create the plugins folder next to mozilla 34. var pluginsFolder = getFolder("Plugins"); 35. if (!fileExists(pluginsFolder)) 36. { 37. var ignoreErr = dirCreate(pluginsFolder); 38. logComment("dirCreate() returned: " + ignoreErr); 39. } 40. else 41. logCommen...
Learn XPI Installer Scripting by Example - Archive of obsolete content
This input is defined in line 22, where getFolder() is used to assign a value to the communicatorFolder variable representing the "Program" folder on the local system: var communicatorFolder = getFolder("Program"); spaceAvailable = fileGetDiskSpaceAvailable(dirPath); spaceRequired, the ...
...es to the installation in order to have them installed. ...
buttons - Archive of obsolete content
tonlabelextra2 attribute and its command with the ondialogextra2 attribute. Note: If you don't want to display any buttons in the dialog box, set the value of this attribute to "," (a single comma). Warning: If the accept and cancel buttons are actually shown is system dependent and is mainly controlled by the value of the boolean preference browser.preferences.instantApply. ...
...rowser.preferences.instantApply. If it is set to true any changes to settings are supposed to be applied immediately. The accept button is therefore unnecessary and is hidden. The cancel button might be shown as an additional possibility to close the dialog in this situation (Windows and Linux) or might be hidden, too (Mac OS). 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). ...
Deprecated and defunct markup - Archive of obsolete content
d a native scrollbar; had been for Mac only with native themes on) <outliner> (former name for <tree>; <listbox> had been "<tree>") <popup> (Use menupopup) <package> (no longer present but in older documentation) <scrollbarbutton> (button at end of scrollbar; had been only within larger <scrollbar>) So, not deprecated, but internal use only? ...
...y; part of XBL for <tree>) <treefoot> (old/experimental and unsupported XUL tags) <treeindentation> (old/experimental and unsupported XUL tags) Was a part of the old <tree> that predated <outliner> that was not converted to <listbox>--Neil 03 March 2011 <treeicon> (old/experimental and unsupported XUL tags) <treerows> (internal use only; part of XBL for <tree>) Attributes @debug="true" provided struts and springs around boxes to facilitate identification of flex issues but does not seem to work now You need a special DEBUG_LAYOUT build --Neil 03 March 2011 References XUL Element Reference by Neal Deakin Rapid Application Development With Mozilla, by Nigel McFarlane ...
findbar - Archive of obsolete content
ecified mode, which should be one of FIND_NORMAL, FIND_TYPEAHEAD, or FIND_LINKS. If you don't pass a mode, the last-used mode for the same findbar is used. If the findbar hasn't been used before, FIND_NORMAL is the default. onFindAgainCommand( findPrevious ) Return type: no return value Call this method to handle your application's "find next" and "find previous" commands. 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. This opens the findbar, focuses the edit field for the search term, and selects its contents. The first time this is called for a given findbar, the findbar will flash to draw attention to...
...tention to itself. The mode should be one of FIND_NORMAL, FIND_TYPEAHEAD, or FIND_LINKS. If you don't pass a mode, the last-used mode for the same findbar is used. If the findbar hasn't been used before, FIND_NORMAL is the default. 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. ...
onFindAgainCommand - Archive of obsolete content
<< XUL Reference home onFindAgainCommand( findPrevious ) Return type: no return value Call this method to handle your application's "find next" and "find previous" commands. ...
...ue Call this method to handle your application's "find next" and "find previous" commands. ...
Menus - Archive of obsolete content
iated with the menuitem, as well as icons beside the label. For details about adding shortcut keys to menus, see Adding Shortcut Keys to Menu Items. For details about adding icons to menus, see Adding Icons to Menu Items. For details about creating checkbox menu items or radio menu items see Checkbox Menu Items or Radio Menu Items. Menu items can be disabled by setting the disabled attribute to true. For an example, see Disabling a Menuitem. The menuseparator element The menuseparator element may be used to create a separator between menus. It is a good idea to group related commands together on a menu and use separators between different groups. This ensures that the items on the menu are easier to distinguish. There are no special attributes that would be used on a separator. <menusepar...
... The overlay should have a menu with the same id 'menu-tools' containing the complete definition of the menu. If you wish to have slight differences between each window, one possibility is to show or hide menu items in a load event listener. For example, to have an item initially hidden in a window: function initMenus() { var item = document.getElementById("menu-file-open"); item.hidden = true; } The hidden property is set to true to hide the menu with the id 'menu-fileOpen'. This function may be called from within an onload attribute on the window. Accessing and Setting the Active Item In a menu, there will usually be an item that is considered "active". This item will be highlighted, and will do certain functions depending on the kind of item it is, and the way in which it has ...
PopupEvents - Archive of obsolete content
t is to open another menu. This technique, as shown in the following example, is needed if you wish to open a submenu programmatically. This is because you cannot open a submenu directly without first opening the parent menu. ...
...Within this functi...
PopupKeys - Archive of obsolete content
e other keys do not apply. Focus in Popups A menu does not take the keyboard focus. The menu key listener described above captures key events on the document. Thus, a key listener added to a <menupopup> will not receive any key events. Instead, you must add a capturing key listener to the document or window if you want to listen for keys pressed within a menu. Note that the last argument here is true to listen for events during the capturing phase of event propagation: window.addEventListener("keypress", someAction, true); However, the default listener provides all the suitable responses to keys, so there shouldn't be a need to handle keys yourself. While a menu is open, the focus remains where it was before the menu was open. For example, focusing a textbox and opening the textbox's contex...
... focus is removed from any element that has it. This allows the focus to be shifted to elements within the panel. For more information about focus handling within panels, see Focus in Panels. Ignoring Keys The ignorekeys attribute may be used to disable the key listener described above. When the ignorekeys attribute is placed on a <menupopup> or <panel> element, and its value is set to the value true, the key listener is not used. <panel ignorekeys="true"> In this case, none of the key handling described above is performed. Instead, you will have to handle this yourself. You would not normally use this attribute for a menu, however you may wish to disable the escape key handling for a panel in this way. ...
Positioning - Archive of obsolete content
e. 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. When both are used, the value supplied to openPopup overrides the attribute. 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. This allows the script and XUL code to coordinate in different ways as to how the popup should be opened. Positioning using Coordinates A popup can be positioned further using the x and y arguments to openPopup. After the popup is positioned using the anchor, the x and y arguments may be used to offset the popup by a certain distanc...
...tion on the openPopupAtScreen method provides more details. For all popups, the left and top attributes may be used to specify pixel coordinates of where the popup should appear on the screen. If these attributes are used, the popup will appear at the location the attributes specify. As with the position attribute, the arguments to the openPopup method override unless the last argument is set to true. Here is an example: <panel left="100" top="200"> <button label="Test"/> </panel> The left and top attributes are most useful when using non-autohiding panels. With these, you can record the left and top positions as the popup is moved around, and use the persist attribute to maintain these attributes across sessions. This way, a panel will always open at the same location on the screen as ...
canAdvance - Archive of obsolete content
Set to false to disallow moving to the next page. ...
...Set to false to disallow moving to the next page. ...
Sorting and filtering a custom tree view - Archive of obsolete content
ple" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="init()"> <script type="application/javascript" src="sort.js"/> <hbox align="center" id="search-box"> <label accesskey="F" control="filter">Filter</label> <textbox id="filter" oninput="inputFilter(event)" flex="1"/> <button id="clearFilter" oncommand="clearFilter()" label="Clear" accesskey="C" disabled="true"/> </hbox> <tree id="tree" flex="1" persist="sortDirection sortResource" sortDirection="ascending" sortResource="description"> <treecols> <treecol id="name" label="Name" flex="1" persist="width ordinal hidden" onclick="sort(this)" class="sortDirectionIndicator" sortDirection="ascending"/> <splitter class="tree-splitter"/> <treecol id="description" label="description" flex="1" persis...
...tTopVisibleRow(topVisibleRow) { return tree.treeBoxObject.scrollToRow(topVisibleRow); } function inputFilter(event) { //do this now rather than doing it at every comparison var value = prepareForComparison(event.target.value); setFilter(value); document.getElementById("clearFilter").disabled = value.length == 0; } function clearFilter() { document.getElementById("clearFilter").disabled = true; var filterElement = document.getElementById("filter"); filterElement.focus(); filterElement.value = ""; setFilter(""); } function setFilter(text) { filterText = text; loadTable(); } ...
Building Hierarchical Trees - Archive of obsolete content
be re-examined for results using the photo as the starting point instead of the top level ref value. ...
...de in the XML document that has children. In this example, the two group elements are displayed at the first level. The individual people are displayed at the next level of the tree as the builder recurses. In this example, we only need to use one rule. ...
Introduction - Archive of obsolete content
ugh the RDF service directly. The datasource is loaded via its URL. Some RDF datasources are provided with Mozilla -- their URL's start with 'rdf:'. Otherwise, the datasource is loaded as any other URL is loaded. If the datasource is already loaded and cached, the template builder can begin work right away. Otherwise, there isn't anything to do until the data is loaded. Actually, this isn't quite true. The RDF service starts the loading of the datasource in the background, and the template builder goes through the process of building content anyway. Naturally, since there is no data yet, no results will be available, so the builder ends up building nothing. Once some data starts arriving, the template builder scans its information to see if some results can be created. If so, some content can ...
...rated again. An interesting thing to note is that due to the nature of the RDF parsing process, the builder generates results and builds content incrementally while the data arrives. Of course, since the data arrives so quickly from the network, you really don't notice this. If the datasource is already loaded, the builder can construct content all in one step, although even this isn't completely true as we'll see later. For XML datasources, use a querytype of xml. The datasources attribute should be the URL of an XML file, which can be either the location of a web site or a file on the local file system, using its file or chrome URL. This file will be loaded and the resulting XML document will be used as the datasource when the template builder generates results and creates content. For examp...
Using Recursive Templates - Archive of obsolete content
he XML source. The content of the action body is again generated for each result, but instead of being inserted inside the outermost groupbox, this new content is inserted inside the content generated from the previous iteration. The content is always inserted directly inside the element with the uri attribute. The result is output like the following: <groupbox> ... ...
...put like the following: <groupbox> ... <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" class="indent"><label value="Cleopatra"/></vbox> <vbox id="row8" class="indent"><label value="Laura Secord"/></vbox> </vbox> </groupbox> Note how similar content corresponding to the action body is created for both the groups as well as the people. The template builder has also added container and empty attribut...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
rn:mozilla:package:root"> <RDF:li RDF:resource="urn:mozilla:package:custombutton"/> </RDF:Seq> <RDF:Description RDF:about="urn:mozilla:package:custombutton" chrome:displayName="Custom Button" chrome:description="My custom toolbar button" chrome:author="My name" chrome:name="custombutton" chrome:localeVersion="1.8" chrome:skinVersion="1.5" chrome:extension="true"/> <RDF:Seq about="urn:mozilla:overlays"> <!-- browser --> <RDF:li> <RDF:Seq about="chrome://navigator/content/navigator.xul"> <RDF:li>chrome://custombutton/content/button.xul</RDF:li> </RDF:Seq> </RDF:li> <!-- address book --> <RDF:li> <RDF:Seq about="chrome://messenger/content/addressbook/addressbook.xul"> <RDF:li>chrome://custombutton/...
...Save the file as contents.rdf and navigate to SeaMonkey\chrome again, following steps 2 and 3 as listed above. Restart SeaMonkey and type the chrome url: chrome://myapp/content/myapp.xul, the browser should show you the content of the XUL file. Note: You ...
Accesskey display rules - Archive of obsolete content
d builds, the accesskey text is always appended even if the labels have their accesskey characters. E.g., when an accesskey of "OK" is 'O' and an accesskey of "?????" (means "cancel") is 'C', the labels will be "OK(O)" and "?????(C)" on Japanese localized build. XUL elements check "intl.menuitems.alwaysappendaccesskeys" pref value whether they should append accesskey text always. If the value is "true" (string), the accesskey text will be appended always. Don't change the pref value from your XUL applications. And also Note that there are no spaces between the original labels and accesskey text in the above Japanese example. Because typically, Japanese language doesn't use spaces as word separator. This is controled by "intl.menuitems.insertseparatorbeforeaccesskeys" pref value. If the value i...
...string), the accesskey text will be appended always. Don't change the pref value from your XUL applications. And also Note that there are no spaces between the original labels and accesskey text in the above Japanese example. Because typically, Japanese language doesn't use spaces as word separator. This is controled by "intl.menuitems.insertseparatorbeforeaccesskeys" pref value. If the value is "true" (string), a spece will be inserted before accesskey text. Don't change the pref value from your XUL applications too. Don't include accesskey text in labels XUL applications should use DTD for localizable UI resource. At that time, accesskeys are specified by independent entity from their label. Be aware, this is very important thing. When you cannot use DTD, e.g., when you need to generate som...
Creating a Skin - Archive of obsolete content
f the window. CSS: .findfilesbox { background-color: #0088CC; } XUL: <vbox class="findfilesbox" orient="vertical" flex="100%"> <toolbox> Rounding on the Tabs Next, let's modify the tabs. We will make the selected tab bold and change the rounding on the tabs. tab:first-child { -moz-border-radius: 4px 0px 0px 0px; } tab:last-child { -moz-border-radius: 0px 4px 0px 0px; } tab[selected="true"] { color: #000066; font-weight: bold; text-decoration: underline; } Two rules change the normal tab appearance, the first sets the rounding on the first tab and the second sets the rounding on the last tab. Used here is a special Mozilla style rule, -moz-border-radius, that creates rounded border corners. The upper left border of the first tab and the upper right border of the second t...
...es rounded border corners. The upper left border of the first tab and the upper right border of the second tab are rounded by four pixels and the other corners have a round corner of zero pixels, which is equivalent to no rounding. Increase the values here for more rounding and decrease them for a more rectangular look. The last rule only applies to tabs that have their selected attribute set to true. It makes the text in the selected tab appear bold, underlined and dark blue. Note in the image that this style has applied only to the first tab, because it's the selected one. Adding Toolbar Icons It is somewhat difficult to distinguish the buttons on the toolbar from the commands on the menu. We could add some icons to the buttons to make them clearer. Mozilla Composer provides some icons fo...
Creating a Wizard - Archive of obsolete content
wizardpage element to provide a sub-caption for that page. In the example above, it has been placed on the second page, but not the first page. Handling Page Changes You will generally want to do something once the Finish button is pressed. You can set an attribute onwizardfinish on the wizard element to accomplish this. Set it to a script which performs whatever task you want and then returns true. This script might be used to save the information that the user entered during the wizard. For example: <wizard id="example-window" title="Select a Dog Wizard" onwizardfinish="return saveDogInfo();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> When the user clicks the Finish button, the function saveDogInfo() will be called, which would be defined in a script fil...
...tered during the wizard. For example: <wizard id="example-window" title="Select a Dog Wizard" onwizardfinish="return saveDogInfo();" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> When the user clicks the Finish button, the function saveDogInfo() will be called, which would be defined in a script file to save the information that was entered. If the function returns true, the wizard closes. If it returns false, then the wizard does not close, which might occur if the function saveDogInfo() encountered invalid input, for example. There are also related onwizardback, onwizardnext and onwizardcancel attributes, which are called when the Back, Next and Cancel buttons are pressed respectively. These functions are called regardless of which page is currently displayed...
Focus and Selection - Archive of obsolete content
s commandDispatcher property. From there, you can get the focused element with the dispatcher's focusedElement property. The example below shows this. ...
...ods move the focus to the next element in sequence or the previous element respectively. This is what happens when the user presses TAB or Shift+Tab. For textboxes, a special attribute, focused is added whenever the element has the focus. You can check for the presence of this attribute to determine if the element has the focus, either from a script or within a style sheet. It will have the value true if the textbox has the focus and, if the textbox does not have the focus, the attribute will not be present. Suppose you wanted to move the focus from where it currently is, to the next place the browser thinks it should be. A user typically does this by hitting the "Tab" key. You can do this anywhere you have a XUL browser document by simply: document.commandDispatcher.advanceFocus(); In ...
Keyboard Shortcuts - Archive of obsolete content
Paste menu command to indicate that Ctrl and the V key can be pressed to invoke the menu command. This is added for you based on the modifiers on the key element. Keyboard shortcuts attached to menus will work even if the menu is not open. One additional feature of key definitions is that you can disable them easily. To do this add a disabled attribute to the key element and set it to the value true. This disables the keyboard shortcut so that it cannot be invoked. It is useful to change the disabled attribute using a script. Our find files example Let's add keyboard shortcuts to the find files dialog. We'll add four of them, one for each of the Cut, Copy, and Paste commands and also one for the Close command when the user presses Esc. <?xml version="1.0" encoding="utf-8"?> <window xml...
...Of course, the clipboard commands don't do anything anyway, as we haven't written those scripts. Key Events There are three keyboard events that may be used if the key related features described above aren't suitable. These events are: keypress Called whe...
List Controls - Archive of obsolete content
ates the textbox with the button beside it. The second, menupopup, creates the popup window which appears when the button is clicked. The third, menuitem, creates the individual choices. Its syntax is best described with the example below: Example 5 : Source View <menulist label="Bus"> <menupopup> <menuitem label="Car" /> <menuitem label="Taxi" /> <menuitem label="Bus" selected="true" /> <menuitem label="Train" /> </menupopup> </menulist> This menulist will contain four choices, one for each menuitem element. To show the choices, click the arrow button on the menulist. When one is selected, it appears as the choice in the menulist. The selected attribute is used to indicate the value that is selected by default. Editable menulist By default, you can only select choic...
...an only select choices from the list. You cannot enter your own text by typing it in. A variant of the menulist allows editing the text in the field. For example, the URL field in the browser has a drop-down for selecting previously typed URLs, but you can also type them in yourself. To create an editable menulist, add the editable attribute as follows: Example 6 : Source View <menulist editable="true"> <menupopup> <menuitem label="www.mozilla.org" /> <menuitem label="www.xulplanet.com" /> <menuitem label="www.dmoz.org" /> </menupopup> </menulist> The URL field created here has three pre-populated choices that the user can select or they can enter one of their own by typing it into the field. The text the user enters is not added as a new choice. Because the label attribute w...
Manifest Files - Archive of obsolete content
Many people put this as a subdirectory inside Mozilla's chrome directory, but this isn't necessary. The directory could be anywhere and on any disk. Put your XUL files in this directory. Create a file called contents.rdf and place it in this directory. Copy the text in the box below into the new c...
...ntify the application id, its name, author, version and so on. Change the highlighted parts of the file above to your own information. The red text 'myapplication' should be the ID of your application. You make this up, but typically, the ID is similar to your application's name. Replace the blue highlighted text above with your application's title and author. If the 'chrome:extension' field is true, the application is a Mozilla Firefox Extension and it will show up in the Extensions window of the browser. If false, it will not appear. Save the contents.rdf and make sure it is in the directory you created in step 1. Open the file <mozilla-directory>/chrome/installed-chrome.txt, where <mozilla-directory> is the directory where Mozilla is installed. Exit Mozilla before you do this. Next, yo...
Modifying the Default Skin - Archive of obsolete content
This documentation has not been fully updated for Firefox Quantum. Support for the userChrome.css file and any of its elements described below are not guaranteed in future versions of Firefox. Using it may lead to hard-to-diagnose bugs or crashes. Use at your own risk! This section describes how to modify the skin of a window. Skin Basics A skin is a set of style sheets, images and behaviors that are applied to a XUL file. ...
...e images and it may need some more complex design. By referring to the images with CSS, they are easy to remove. It also removes the reliance on specific image filenames. You can assign images to a button, checkbox and other elements by using the list-style-image property as in the following: checkbox { list-style-image: url("chrome://findfile/skin/images/check-off.jpg"); } checkbox[checked="true"] { list-style-image: url("chrome://findfile/skin/images/check-on.jpg"); } This code changes the image associated with a checkbox. The first style sets the image for a normal checkbox and the second style sets the image for a checked checkbox. The modifier 'checked=true' makes the style only apply to elements which have their checked attributes set to true. See also : creating a skin for Fir...
More Wizards - Archive of obsolete content
t have to load and save information between pages. However, you may want to do some validation of each field on each page. For this, use the handlers described in the previous section. If a field is invalid, you might display an alert. In some cases, it would be more convenient to disable the Next button until valid input has been entered. The wizard has a property canAdvance, which can be set to true to indicate that the Next button should be enabled. If set to false, the Next button is disabled. You can change the property when invalid or valid data has been entered. In the following example, the user must enter a secret code into a textbox on the first page of the wizard. The function checkCode() is called whenever the first page is shown as indicated by the onpageshow attribute. It is also...
...Both properties are adjusted automatically as you switch pages. Thus, t...
Simple Menu Bars - Archive of obsolete content
ks much like the button element. It accepts some of the same attributes plus some additional ones: id The unique identifier of the menu title button. label The text to appear on the menu, such as File or Edit. disabled This boolean attribute determines whether the menu is disabled. Although you can, there's rarely a need to disable an entire menu. This attribute can be set to either true or false. Of course, the latter is the default. accesskey This is the key that the user can press to activate the menu item. This letter is typically shown underlined on the menu title. Mozilla will look at the label attribute and add an underline character to the character specified here. For that reason, you should specify a character that exists in the text (although the key will still wo...
... menupopup, however they will be ignored on a Macintosh. menuitem element The menuitem element is much like the menu element and has some of the same attributes. id The unique identifier of the menu item. label The text to appear on the menu item, such as Open or Save. disabled This boolean attribute determines whether the menu item is disabled. This attribute can be set to either true or false where the latter is the default. accesskey This is the key that the user can press to activate the menu item. This letter is typically shown underlined on the menu title. Mozilla will look at the label attribute and add an underline character to the character specified here. For that reason, you should specify a character that exists in the text. acceltext This specifies the sh...
Tree Box Objects - Archive of obsolete content
example. ...
...; if (column.value && typeof column.value != "string") column.value = column.value.id; document.getElementById("row").value = row.value; document.getElementById("column").value = column.value; document.getElementById("part").value = part.value; } </script> <tree id="thetree" flex="1" onmousemove="updateFields(event);"> <treecols> <treecol id="utensil" label="Utensil" primary="true" flex="1"/> <treecol id="count" label="Count" flex="1"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="Fork"/> <treecell label="5"/> </treerow> </treeitem> <treeitem> <treerow> <treecell label="Knife"/> <treecell label="2"/> </treerow> </treeitem> <treeitem> <treerow> <treecell lab...
Tree Selection - Archive of obsolete content
assigning them to the 'value' property. So if the first range is from the third item to the seventh item, 'start.value' will be 2 (remember that indices start with 0, so we subtract one.) and 'end.value' will be 6. An alert is displayed for each index. If you just want to find out if a specific row is selected, use can use the isSelected() function. It takes a row index as an argument and returns true if that row is selected. alert(tree.view.selection.isSelected(3)); Modifying the Tree Selection The selection object has a number of functions which may be used to change the selection. The simplest function is the select() function, which deselects any rows that are currently selected and selects one specific row. For example, the following code will select the row at index 5: tree.view.selecti...
...n to clear the selection, and an invertSelection function to reverse the selection, that is, deselect all selected rows and select all unselected rows. To select specific rows, use the rangedSelect() function which selects all rows in between two indices. Here is an example which selects rows between index 2 and 7. Note that rows 2 and 7 will also be selected. tree.view.selection.rangedSelect(2,7,true); The last argument indicates whether to add to the current selection or not. If true, the range will be added to the existing selection. If false, all existing selected rows will be deselected first. Finally, the clearRange() function may be used to deselect a range of rows, leaving rows outside the range unaffected. tree.view.selection.clearRange(2,7); Next, we'll find out how to create a cus...
XPCOM Interfaces - Archive of obsolete content
on an object and the requested interface is not supported by an object, an exception is thrown. If you're not sure that an interface is supported by a component, you can use the instanceof operator to check: var aFile = Components.classes["@mozilla.org/file/local;1"].createInstance(); if (aFile instanceof Components.interfaces.nsILocalFile){ // do something } The instanceof operator returns true if aFile implements the nsILocalFile interface. This also has the side effect of calling QueryInterface(), so aFile will be a valid nsILocalFile afterwards. Calling the Functions of an Interface Now that we have an object that refers to a component with the nsILocalFile interface, we can call the functions of nsILocalFile through it. The table below shows some of the properties and methods of t...
... of nsILocalFile through it. The table below shows some of the properties and methods of the nsILocalFile interface. initWithPath This method is used to initialize the path and filename for the nsILocalFile. The first parameter should be the file path, such as '/usr/local/mozilla'. leafName The filename without the directory part. fileSize The size of the file. isDirectory() Returns true if the nsILocalFile represents a directory. remove(recursive) Deletes a file. If the recursive parameter is true, a directory and all of its files and subdirectories will also be deleted. copyTo(directory,newname) Copies a file to another directory, optionally renaming the file. The directory should be a nsILocalFile holding the directory to copy the file to. moveTo(directory,newname) Mo...
XUL accessibility guidelines - Archive of obsolete content
ve the focus to the next element before disabling, hiding, or destroying the focus element. The following example shows a JavaScript function that can be called before destroying an element to check for focus and move it if necessary. function moveFocus(element) { if(element == document.commandDispatcher.focusedElement) { document.commandDispatcher.advanceFocus(); return true; } return false; } Changing focus unexpectedly can confuse or disorient users. A common example of this occurrence in the US is with phone number form fields. US phone numbers are often displayed on the web in two main formats XXX-XXX-XXXX or (XXX) XXX-XXXX. To enforce this pattern some forms provide three form fields. The problem occurs when a developer decides to add functionality ...
...on't have access to screen reader software (and don't know anyone who does), your best option is to throughly check the source code to make sure that all of the above guidelines have been met, and then ensure that end users have a way to provide you with feedback on the accessibility (and other aspects) of your application. Display It is often said that "presentation is everything." While it is true that presentation is essential, documents should also be structured so that the user can invoke display preferences that may be necessary for accessibility. Presentation should also be flexible to window and font resizing. Cooperative applications adapt well to the user's environment. System defaults Maintain system defaults. Many users set their computers to use larger than normal fonts and/or...
checkbox - Archive of obsolete content
t with the mouse. A label, specified with the label attribute, may be added beside the check box. More information is available in the XUL tutorial. 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. This should be one of the characters that appears in the label attribute for the element. checked Type: boolean Indicates whether the element is checked or not. Use hasAttribute() to determine whether this attribut...
... disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
colorpicker - Archive of obsolete content
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...e type of accessibility object for the element. color Type: color string The currently selected color. This is modified when the user selects a color. You can assign a string of the form #RRGGBB to this property to change the selected color. disabled Type: boolean Gets and sets the value of the disabled attribute. open Type: boolean Returns true if the popup for a button-type colorpicker is open. Set this property to true to open the popup or false to close the popup. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value property gets and sets color attribute Methods Inherited Methods addEventListener(), appendChild(), blur, click, cloneNode(), compareDocumentPosition, dispatchEven...
command - Archive of obsolete content
s disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
... of this attribute is copied to the menulist.value property upon user selection of the menuitem. oncommand Type: script code This event handler is called when the command is activated. This occurs when a user selects a menu item or presses a keyboard shortcut attached to the command. reserved Type: string This attribute applies to a command element. Setting this attribute to "true" indicates that the command is reserved for Chrome code and is not available for use in the content. This means that, to execute these commands, key events won't be passed to content, and event listeners registered for them in content will not be executed. Currently, the content still receives these key events, even though it can't override them. In future releases, it won't receive them. See bu...
menupopup - Archive of obsolete content
up> </menulist> The following example shows how a menupopup can be used as a context menu for an element. When the label is right-clicked, the menu will be displayed. <menupopup id="clipmenu"> <menuitem label="Cut"/> <menuitem label="Copy"/> <menuitem label="Paste"/> </menupopup> <label value="Right click for popup" context="clipmenu"/> Attributes ignorekeys Type: boolean If true, keyboard navigation between items in the popup is disabled. left Type: integer Overrides the horizontal position of the popup specified by the showPopup method. onpopuphidden Type: script code This event is sent to a popup after it has been hidden. This event may also be received while the popup is still open, but when sub-menus contained within this popup are hidden. Examp...
...popup, the x and y arguments may be used to offset the popup from its anchored position by some number, measured in CSS pixels. An unanchored popup appears at the position specified by x and y, relative to the viewport of the document containing the popup node. In this case, the position and attributesOverride arguments are ignored. isContextMenu The isContextMenu argument should be true for context menus and false for all other types of popups. It affects menu item highlighting; that is, while a context menu is open, menus opened earlier do not highlight or execute their items. attributesOverride If the attributesOverride argument is true, the position attribute on the popup node overrides the position value argument. If attributesOverride is false, the attribute i...
notificationbox - Archive of obsolete content
ng properties: accessKey - the accesskey to appear on the button callback - function to be called when the button is activated. This function is passed three arguments: the <notification> the button is associated with the button description as passed to appendNotification. the element which was the target of the button press event. If the return value from this function is not True, then the notification is closed. The notification is also not closed if an error is thrown. label - the label to appear on the button popup - the id of a popup for the button. If null, the button is not a button popup (e.g. a menu). The type property must also be set to "menu", or "menu-button". isDefault - if True, this is the default button. There can be only one default button. If no ...
...o provide a popup via the popup property. getNotificationWithValue( value ) Return type: notification element Retrieve the notification with a particular value. The value is specified when adding the notification with appendNotification. If no matching value is found, returns null. removeAllNotifications( immediate ) Return type: no return value Remove all notifications. If immediate is true, the messages are removed immediately. If immediate is false, the notifications are removed using a slide transition. removeCurrentNotification() Return type: no return value Remove the current notification. removeNotification( item ) Return type: element Remove a notification, displaying the next one if the removed item is the current one. removeTransientNotifications( ) Return typ...
prefpane - Archive of obsolete content
s left out, no text appears. For an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. onpaneload Type: script code Code defined here is called when the pane has been loaded, much like the load event for a window. selected Type: boolean This attribute will be set to true for the currently selected prefpane. To change the selected pane, use the prefwindow's showPane method. src Type: URI The URI of the overlay contents of preference pane. If this is not specified, the contents of the prefpane element is used. Properties contentHeight (readonly) The height (in pixels) of current pane's content. image Type...
...bel attribute. loaded Indicates whether the pane is fully loaded. preferenceElements Type: DOM Nodelist Holds a list of the UI elements in the pane that are attached to preferences. preferences Type: DOM Nodelist Holds a list of the preference elements in the pane. selected Type: boolean This property's value is true if this element is selected, or false if it is not. This property is read only. This property is available for menuitem and menuseparator elements in Firefox 3. src Type: URL Gets and sets the value of the src attribute. Methods DOMElement getPreferenceElement(in DOMElement startElement) preferenceForElement( uielement ) Return type: preference element ...
richlistitem - Archive of obsolete content
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...an Gets and sets the value of the disabled attribute. label Type: string Gets the concatentation of text from any child label elements. Does not support setting label values. Use the child elements directly to set label text. searchLabel Type: string Gets and sets the value of the searchlabel attribute. selected Type: boolean This property's value is true if this element is selected, or false if it is not. This property is read only. This property is available for menuitem and menuseparator elements in Firefox 3. tabIndex Type: integer Gets and sets the value of the tabindex attribute. value Type: string Gets and sets the value of the value attribute. For textbox and user editable menulist elements, the conte...
rule - Archive of obsolete content
Archive › Mozilla › XUL › rule
and the simple query syntax may be used for RDF datasources. For more information about this, see the Simple Query Syntax. Attributes iscontainer, isempty, parent, parsetype Examples (example needed) Attributes iscontainer Type: boolean Indicates whether rules match based on containment. If not specified, the rule may match regardless of whether a node is a container or not. ...
... false: The rule will only match nodes that contain one or more child elements. parent Type: element tag name If set, the rule will only match the corresponding tag. This may be used to have separate rules for leaf and container nodes with different tags. ...
scale - Archive of obsolete content
Archive › Mozilla › XUL › scale
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
...ges when the arrows are clicked(or scales are dragged). The default value is 1. min Type: integer The minimum value the control's value may take. The default value is 0. Type: integer The maximum value that the scale or number box may be set to. The default value is 100 for scales and Infinity for number boxes. movetoclick Type: boolean If true, clicking the slide area of the scale moves the thumb directly to that position. If false, clicking the slide area moves the thumb only one increment in that direction. If not specified, the default value is used, which varies for each platform. pageincrement Type: integer The amount by which the value of the curpos or value attribute changes when the tray of the scroll bar (the area in ...
treeitem - Archive of obsolete content
s. In a template condition, you should use a treeitem instead of a content element when the dont-build-content flag is specified. Set the uri attribute to the variable name to bind to a content node during matching. More information is available in the XUL tutorial. Attributes container, empty, label, open, uri Examples (example needed) Attributes container Type: boolean Set to true if the element is to act as a container which can have child elements. This would be used for folders. This will be set by the template builder as needed. empty Type: boolean Set to true if the element is a container that contains no children. This will be set by the template builder as needed. label Tipo: string (concatenacion de caracteres) Para un arbol tree con columnas sim...
...ntains no children. This will be set by the template builder as needed. label Tipo: string (concatenacion de caracteres) Para un arbol tree con columnas simples, la etiqueta puede ser colocada directamnete sobre el elemeto "treeitem" sin la necesidad de una fila "row" y un elemento "treeitem" dentro. open Type: boolean For the menu type buttons, the open attribute is set to true when the menu is open. The open attribute is not present if the menu is closed. uri Type: string For template-generated content, the attribute should be placed on the element where content generation should begin. Thus, it should be placed on an element that is a descendant of a template. The value should be set to rdf:*. Elements that appear inside the element with the attribute wil...
where - Archive of obsolete content
Archive › Mozilla › XUL › where
<< XUL Reference home [ Examples | Attributes | Properties | Methods | Related ] Indicate a condition that must match for a template result to be used. If the condition is true, the corresponding action body is generated; otherwise the result is ignored and no content is generated. For more information, see Where Elements. Attributes ignorecase, multiple, negate, rel, subject, value Examples (example needed) Attributes ignorecase Type: boolean Set to true to indicate that the case does not matter when making comparisons. Otherwise, the default value is false, to indicate that the value should match with the same case. multiple Type: boolean Set to true to indicate that the value contains multiple values separated by commas. Any of the values may match. Ot...
...ue to indicate that the case does not matter when making comparisons. Otherwise, the default value is false, to indicate that the value should match with the same case. multiple Type: boolean Set to true to indicate that the value contains multiple values separated by commas. Any of the values may match. Otherwise, the entire value string is compared. negate Type: boolean Set to true to indicate that the comparison should be reversed. The where clause matches if the condition is false, and does not match if the condition is true. rel Type: one of the values below The type of comparison to perform. equals The subject and value must match exactly. less The numeric value of the subject must be less than the value greater The numeric value of the subject ...
Application Update - Archive of obsolete content
gs in your application: Branding The update process uses branding information, setup branding for your application as described here: XulRunner Tips Icons The updater process for Linux systems requires updater.png to be in your <application folder>/icons/, see https://bugzilla.mozilla.org/show_bug.cgi?id=706846 Preferences // Whether or not app updates are enabled pref("app.update.enabled", true); // This preference turns on app.update.mode and allows automatic download and // install to take place. We use a separate boolean toggle for this to make // the UI easier to construct. pref("app.update.auto", true); // Defines how the Application Update Service notifies the user about updates: // // AUM Set to: Minor Releases: Major Releases: // 0 download no promp...
...pref("app.update.silent", false); // Update service URL: // You do not need to use all the %VAR% parameters. Use what you need, %PRODUCT%,%VERSION%,%BUILD_ID%,%CHANNEL% for example pref("app.update.url", "https://yourserver.net/update/3/%PRODUCT%/%VERSION%/%BUILD_ID%/%BUILD_TARGET%/%LOCALE%/%CHANNEL%/%OS_VERSION%/%DISTRIBUTION%/%DISTRIBUTION_...
CommandLine - Archive of obsolete content
nsIComponentRegistrar); compReg.registerFactoryLocation(CLASS_ID, CLASS_NAME, CONTRACT_ID, aFileSpec, aLocation, aType); var catMan = Components.classes["@mozilla.org/categorymanager;1"] .getService(nsICategoryManager); catMan.addCategoryEntry("command-line-handler", CLD_CATEGORY, CONTRACT_ID, true, true); }, unregisterSelf : function mod_unreg(aCompMgr, aLocation, aType) { var compReg = aCompMgr.QueryInterface(nsIComponentRegistrar); compReg.unregisterFactoryLocation(CLASS_ID, aLocation); var catMan = Components.classes["@mozilla.org/categorymanager;1"] .getService(nsICategoryManager); catMan.deleteCategoryEntry("command-line-handler", CLD...
...ation, aType) { var compReg = aCompMgr.QueryInterface(nsIComponentRegistrar); compReg.unregisterFactoryLocation(CLASS_ID, aLocation); var catMan = Components.classes["@mozilla.org/categorymanager;1"] .getService(nsICategoryManager); catMan.deleteCategoryEntry("command-line-handler", CLD_CATEGORY); }, canUnload : function (aCompMgr) { return true; } }; function NSGetModule(aCompMgr, aFileSpec) { return appHandlerModule; } Create an observer that will get notified when arguments change: chrome/content/cmdline.js function CommandLineObserver() { this.register(); } CommandLineObserver.prototype = { observe: function(aSubject, aTopic, aData) { var cmdLine = aSubject.QueryInterface(Components.interfaces.nsICommandLine); v...
calICalendarView - Archive of obsolete content
view. Note that this date is typically not immediately useful for querying for the events and tasks shown in the calICalendarView. Typically, one more day must be added to it, in order to make it exclusive. supportsDisjointDates Consumers of calICalendarView should check this attribute to determine whether or not the implementation allows for calls to setDateList. If an implementation returns true for this attribute, it must allow for any arbitrary set of dates to be displayed. hasDisjointDates Returns false if the dates being displayed represent a continuous list, and true if certain dates in between startDate and endDate may not be displayed. selectedItem Returns a calIItemBase corresponding to the currently active item in the view. Other areas of the code may use this attribute fo...
...isible. The view is free to show other dates as well, although this should be kept to a minimum. (For instance, calendar-month-view will show all dates from the start of the week of aStartDate to the end of the week of aEndDate.) setDateList void setDateList(in unsigned long aCount, [array,size_is(aCount)] in calIDateTime aDates); This function can only be called if supportsDisjointDates is true and will throw an error if it is not. If supported, the dates in the aDates array will become the only dates shown in the view. getDateList void getDateList(out unsigned long aCount, [array,size_is(aCount),retval] out calIDateTime aDates); This function returns a list of all dates currently being shown in the view. History calICalendarView was introduced as part of the 'backend rewrite' t...
Monitoring plugins - Archive of obsolete content
{ 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: nsIObserverService n...
NPN_Invoke - Archive of obsolete content
arameters: npp The NPP indicating which plugin wants to call the method on the object. npobj The object on which to invoke a method. methodName A string identifier indicating the name of the method to invoke. args An array of arguments to pass to the method. argCount The number of arguments in the args array. result A pointer to an NPVariant to receive the result returned by the method. Returns true if the method was successfully invoked, otherwise false. If the method was invoked successfully, any return value is stored in the NPVariant specified by result. When the caller no longer needs the result, it must call NPN_ReleaseVariantValue() to release it. Description The method arguments are passed as an array of NPVariants, and the number of arguments is passed in. The result of the method i...
... stored in the NPVariant specified by result. When the caller no longer needs the result, it must call NPN_ReleaseVariantValue() to release it. Description The method arguments are passed as an array of NPVariants, and the number of arguments is passed in. The result of the method invocation is returned through an NPVariant result parameter. If the method invocation succeeds, NPN_Invoke() returns true, else false. Note: Early on in the development of the scriptability API this method used to be called NPN_Call() but was renamed for consistency. ...
NPN_InvokeDefault - Archive of obsolete content
parameters: npp The NPP indicating which plugin wants to call the default method on the object. npobj The object on which to invoke the default method. args An array of arguments to pass to the default method. argCount The number of arguments in the args array. result A pointer to an NPVariant to receive the result returned by the default method. Returns true if the default method was successfully invoked, otherwise false. If the default method was invoked successfully, any return value is stored in the NPVariant specified by result. When the caller no longer needs the result, it must call NPN_ReleaseVariantValue() to release it. Description The method arguments are passed as an array of NPVariants, and the number of arguments is passed in. The result...
... stored in the NPVariant specified by result. When the caller no longer needs the result, it must call NPN_ReleaseVariantValue() to release it. Description The method arguments are passed as an array of NPVariants, and the number of arguments is passed in. The result of the method invocation is returned through an NPVariant result parameter. If the method invocation succeeds, NPN_Invoke() returns true, else false. ...
NPN_PostURL - Archive of obsolete content
nstance regardless of MIME type. For values, see NPN_GetURL. len Length of the buffer buf. buf Path to local temporary file or data buffer that contains the data to post. Temporary file is deleted after use. Data in buffer cannot be posted for a protocol that requires a header. file A boolean value that specifies whether to post a file. Values: true: Post the file whose path is specified in buf, then delete the file. false: Post the raw data in buf. Returns If successful, the function returns NPERR_NO_ERROR. If unsuccessful, the plug-in is not loaded and the function returns an error code. For possible values, see Error Codes. Description NPN_PostURL works similarly to NPN_GetURL, but in reverse. NPN_GetURL reads data...
...ritten to a new browser window. You can also write the response data to a frame by specifying the frame name as the target parameter. For HTTP URLs only, the browser resolves this method as the HTTP server method POST, which transmits data to the server. The data to post can be contained either in a local temporary file or a new memory buffer. To post to a temporary file, set the flag file to true, the buffer buf to the path name string for a file, and len to the length of the path string. The file-type URL prefix "file://" is optional. MS Windows and OS X If a file is posted with any protocol other than FTP, the file must be text with Unix-style line breaks ('\n' separators only). To post data from a memory buffer, set the flag file to false, the buffer buf to the data to post, and le...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
es and does ] [ other standard checks ] /* * Make sure that the browser supports functionality we care * about. ...
...ization function the plugin will not be used which avoids crashes and other problems. Once you've verified that the browser has the compatibility you require, you can modify your NPP_GetValue call like so: NPError NPP_GetValue(void *future, NPPVariable variable, void *value) { NPError err = NPERR_NO_ERROR; switch (variable) { case NPPVpluginNeedsXEmbed: *((PRBool *)value) = PR_TRUE; break; default: err = NPERR_GENERIC_ERROR; } return err; } Once you have set those variables, it should be relatively easy to set up a plugin. Just create a GtkPlug that is the child of the XID passed in and it's just like using a standard Gtk widget. Other Toolkits and Out of Process Plugins It should be possible to use this interface to build a plugin that would r...
Theme changes in Firefox 3 - Archive of obsolete content
longer calculated during the drag (tabbrowser.xml). Instead a '-moz-margin-start' property must be added to .tab-drop-indicator-bar, with a value that is half of the width of the indicator image. Also, the visibility of the indicator is now controlled by setting collapsed in tabbrowser.xml. ...
...Instead .tabs-left now displayed and given the same width as the former margin-left. It was already done this way in Winstripe. ...
Developing cross-browser and cross-platform pages - Archive of obsolete content
(aka code branching) or points the user to different pages (aka site branching) or web content. Site branching can be particularly dangerous as people may enter a page through a link, bookmark, search engine or cache with a "wrong" browser. Let's see a basic example of this approach. ...
...branching can be particularly dangerous as people may enter a page through a link, bookmark, search engine or cache with a "wrong" browser. Let's see a basic example of this approach. // BAD SAMPLE if (navigator.appVersion.charAt(0) == "8") { if (navigator.appName == "Netscape") { isNS8 = true; alert("Netscape 8"); }; } else if (navigator.appVersion.indexOf("MSIE") != -1) { isIE = true; alert("Internet Explorer"); }; While this kind of checking in the above code can work in a crude sense, sharp readers may wonder what happens when Internet Explorer 8 is released or when an Opera 8.x user visits the page or even when an user with any non-Netscape browser starting with a "8" character in the appVersion string visits that page. As new browsers are released, it becomes necessary...
-ms-accelerator - Archive of obsolete content
The -ms-accelerator CSS property is a Microsoft extension that sets or retrieves a string indicating whether the object represents a keyboard shortcut. Initial valuefalseApplies toall elementsInheritednoComputed valueas specifiedAnimation typediscrete Syntax /* The object is not a keyboard shortcut (the default) */ -ms-accelerator: false /* The object is a keyboard shortcut */ -ms-accelerator: true Values false The object is not a keyboard shortcut. true The object is a keyboard shortcut. Formal syntax false | true Examples This example uses the -ms-accelerator attribute in a <u> element to specify that the "N" in the <label> element is a keyboard shortcut. When the option to "Hide keyboard navigation indicators until I use the Alt key" is enabled in the user's Display ...
...vigation indicators until I use the Alt key" is enabled in the user's Display Properties, the "N" is not underlined until the user presses the Alt key. When Alt + N is pressed, the <input> element that defines an accesskey attribute value of "N" receives the focus. <!DOCTYPE html> <html> <head> <title>Accelerator</title> </head> <body> <label for="oName"><u style="-ms-accelerator: true; accelerator: true">N</u>ame: </label> <input type="text" id="oName" size="25" accesskey="N" value="Your name here" /> </body> </html> Specifications Not part of any specification. Remarks This property is supported by Windows 2000 and later. It enables users to hide navigation indicators for menu items and controls until the Alt key is pressed. An access key i...
-ms-filter - Archive of obsolete content
EndColor The end color, supports only opaque colors in the #RRGGBB notation. EndColorStr The end color, supports both opaque colors (...
... EndColor The end color, supports only opaque colors in the #RRGGBB notation. EndColorStr The end color, supports both opaque colors (#RRGGBB) and colors with alpha opacity using the #AARRGGBB notation. ...
Debug.setNonUserCodeExceptions - Archive of obsolete content
The debug.setNonUserCodeExceptions property determines whether any try-catch blocks in this scope are to be treated by the debugger as user-unhandled. Exceptions can be classified as thrown, user-unhandled or unhandled. ...
...cified action on exceptions thrown inside that scope: for instance, if the developer wishes to break on user-unhandled exceptions. Setting this property to false is the same as never having set the property. For more information on debugging, see the Active Script Debugging Overview. Example The following code shows how to set this property. (function () { Debug.setNonUserCodeExceptions = true; try{ var x = null; x.y(); } catch (e) { // Catch the exception. } })(); Requirements Supported in the following document modes: Internet Explorer 10 standards and Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer ...
XForms Select Element - Archive of obsolete content
as to which type of widget(s) to use to represent this control. accesskey - used to specify the keyboard shortcut for focusing this control. Single-Node Binding Special selection - isn't currently supported. This attribute, when set to 'open', allows the user to provide free entry to the list. Possible values are open and closed, default is closed. incremental - supported, default value is true Properties selection - see corresponding attribute incremental - see corresponding attribute Type restrictions The select element can be bound to a node containing simple content capable of holding a sequence. The data binding restriction to simple content may be relaxed when an itemset element is used, which allows the available choices to be obtained from an XForms Model. The relaxatio...
...ontrol is bound to. Representations The XForms select element can be represented by the following widgets for the specified appearance attribute values: list - default representation (xhtml/xul) check group- used when appearance = 'full' (xhtml/xul) list Displaying a listbox is the default representation (xhtml/xul). 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. loses focus), otherwise it is updated upon item selection check group The select is represented as group of checkboxes (xhtml/xul). Characteristics appearance attribute contains the value fu...
XForms Switch Module - Archive of obsolete content
be conditionally rendered. The content elements (e.g. form controls, groups, switches, repeats and host language elements) within a non-selected case are not rendered. Correspondingly, content elements in a case that becomes selected are visible. Attributes Special selected - determines the initial selected state of the case. If multiple cases within a switch are marked as selected="true", the first selected case will appear and all others will not be visible. If no case is initially selected, the first case inside the switch becomes selected and visible. Representations The case element doesn't have a visual representation. Toggle Element The element (see the spec) selects one possible case from an exclusive list of alternatives in a switch. A toggle can be designated a...
...ternatives in a switch. A toggle can be designated as an event handler using XML Events or may also be contained in an action element. In either scenario, it would be triggered by an event. Attributes Events Special case - the IDREF of a case element to select Representations The case element doesn't have a visual representation. ...
Efficient animation for web games - Game development
sy way to do this is to declare your own refresh function that sets a flag when it calls requestAnimationFrame. 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. Remember that when you do drawing with requestAnimationFrame (and in general), you may be blocking the browser from updating other things. Try to keep unnecessary work outside your animat...
...ither too complicated for simple use-cases, or had performance issues on mobile. How this conclusion was reached, however, is more important than the conclusion itself. To begin with, the priority was to write the code quickly to iterate on gameplay (and we'd certainly recommend doing this). We assumed that our own, naive code was making the game slower than we would like. To an extent, this was true: we found plenty to optimise in our own code, but it got to the point where we knew what we were doing ought to perform quite well, and it still wasn't quite there. At this point, we turned to the Firefox JavaScript profiler, and this told us almost exactly what low-hanging-fruit was left to address to improve performance. As it turned out, the code from some of the things mentioned above; the an...
Build the brick field - Game development
need to add some code inside the nested loop stucture to draw each brick. Fill in the contents as shown below: for(c=0; c<brickInfo.count.col; c++) { for(r=0; r<brickInfo.count.row; r++) { var brickX = 0; var brickY = 0; newBrick = game.add.sprite(brickX, brickY, 'brick'); game.physics.enable(newBrick, Phaser.Physics.ARCADE); newBrick.body.immovable = true; newBrick.anchor.set(0.5); bricks.add(newBrick); } } Here we're looping through the rows and columns to create the new bricks and place them on the screen. The newly created brick is enabled for the Arcade physics engine, it's body is set to be immovable (so it won't move when hit by the ball), and we're also setting the anchor to be in the middle and adding the brick to the...
... Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: Next steps Something is missing tho...
Physics - Game development
ions Remember to remove our old method of adding values to x and y from the update() function: function update() { ball.x += 1; ball.y += 1; } we are now handling this properly, with a physics engine. ...
...adding values to x and y from the update() function: function update() { ball.x += 1; ball.y += 1; } we are now handling this properly, with a physics engine. ...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
ry is mostly built by JavaScript's compiler infrastructure, and the global symbol registry's content is not available to JavaScript's run-time infrastructure, except through these reflective methods. ...
...lobal symbol registry's content is not available to JavaScript's run-time infrastructure, except through these reflective methods. ...
Web fonts - Learn web development
's find some fonts! Go to Font Squirrel and choose two fonts -- a nice interesting font for the headings (maybe a nice display or slab serif font), and slightly less flashy and more readable font for the paragraphs. When you find each font, press on the download button, and save the file inside the same directory as the HTML and CSS files you saved earlier. It doesn't matter whether they are TTF (True Type Fonts) or OTF (Open Type Fonts). In each case, unzip the font package (Web fonts are usually distributed in ZIP files containing the font file(s) and licensing information). You may find multiple font files in the package -- some fonts are distributed as a family with different variants available, for example thin, medium, bold, italic, thin italic, etc. For this example, we just want you t...
...ontsquirrel. This is what one of the blocks looks like: @font-face { font-family: 'ciclefina'; src: url('fonts/cicle_fina-webfont.eot'); src: url('fonts/cicle_fina-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/cicle_fina-webfont.woff2') format('woff2'), url('fonts/cicle_fina-webfont.woff') format('woff'), url('fonts/cicle_fina-webfont.ttf') format('truetype'), url('fonts/cicle_fina-webfont.svg#ciclefina') format('svg'); font-weight: normal; font-style: normal; } This is referred to as "bulletproof @font-face syntax", after a post by Paul Irish from early on when @font-face started to get popular (Bulletproof @font-face Syntax). Let's go through it to see what it does: font-family: This line specifies the name you want to refer t...
Example 5 - Learn web development
ML Content <form class="no-widget"> <select name="myFruit"> <option>Cherry</option> <option>Lemon</option> <option>Banana</option> <option>Strawberry</option> <option>Apple</option> </select> <div class="select" role="listbox"> <span class="value">Cherry</span> <ul class="optList hidden" role="presentation"> <li class="option" role="option" aria-selected="true">Cherry</li> <li class="option" role="option">Lemon</li> <li class="option" role="option">Banana</li> <li class="option" role="option">Strawberry</li> <li class="option" role="option">Apple</li> </ul> </div> </form> CSS Content .widget select, .no-widget .select { position : absolute; left : -5000em; height : 0; overflow : hidden; } /* --------------...
...ighlight'); }); option.classList.add('highlight'); }; function updateValue(select, index) { var nativeWidget = select.previousElementSibling; var value = select.querySelector('.value'); var optionList = select.querySelectorAll('.option'); optionList.forEach(function (other) { other.setAttribute('aria-selected', 'false'); }); optionList[index].setAttribute('aria-selected', 'true'); nativeWidget.selectedIndex = index; value.innerHTML = optionList[index].innerHTML; highlightOption(select, optionList[index]); }; function getIndex(select) { var nativeWidget = select.previousElementSibling; return nativeWidget.selectedIndex; }; // ------------- // // Event binding // // ------------- // window.addEventListener("load", function () { var form = document.querySe...
How to build custom form controls - Learn web development
we'll stop with that; however, if you're a careful reader, you'll notice that some behaviors are missing. For example, what do you think will happen if the user hits the tab key while the control is in its open state? The answer is... nothing. OK, the right behavior seems obvious but the fact is, because it's not defined in our specs, it is very easy to overlook this behavior. This is especially true in a team environment when the people who design the control's behavior are different from the ones who implement it. Another fun example: what will happen if the user hits the up or down arrow keys while the control is in the open state? This one is a little bit trickier. If you consider that the active state and the open state are completely different, the answer is again "nothing will happen"...
...Screen readers are not limited to blind people; people with low vision and even perfect vision use them as...
Choosing the right approach - Learn web development
age = document.createElement('img'); image.src = objectURL; document.body.appendChild(image); }) .catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); }); Pitfalls Promise chains can be complex and hard to parse. If you nest a number of promises, you can end up with similar troubles to callback hell. ...
...Element('img'); image.src = objectURL; document.body.appendChild(image); }) .catch(e => { console.log('There has been a problem with your fetch operation: ' + e.message); }); Pitfalls Promise chains can be complex and hard to parse. If you nest a number of promises, you can end up with similar troubles to callback hell. ...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
r code next: function setEndgame() { cancelAnimationFrame(rAF); spinnerContainer.style.display = 'none'; result.style.display = 'block'; result.textContent = 'PLAYERS GO!!'; document.addEventListener('keydown', keyHandler); function keyHandler(e) { let isOver = false; console.log(e.key); if (e.key === "a") { result.textContent = 'Player 1 won!!'; isOver = true; } else if (e.key === "l") { result.textContent = 'Player 2 won!!'; isOver = true; } if (isOver) { document.removeEventListener('keydown', keyHandler); setTimeout(reset, 5000); } }; } Stepping through this: First, cancel the spinner animation with cancelAnimationFrame() (it is always good to clean up unneeded processes), and hide the spinner co...
...a useful way of finding out the key value of different keys you are pressing. When e.key is "a", display a message to say that Player 1 won, and when e.key is "l", display a message to say Player 2 won. (Note: This will only work with lowercase a and l -- if an uppercase A or L is submitted (the key plus Shift), it is counted as a different key!) If one of these keys was pressed, set isOver to true. Only if isOver is true, remove the keydown event listener using removeEventListener() so that once the winning press has happened, no more keyboard input is possible to mess up the final game result. You also use setTimeout() to call reset() after 5 seconds -- as explained earlier, this function resets the game back to its original state so that a new game can be started. That's it--yo...
What went wrong? Troubleshooting JavaScript - Learn web development
ar userGuess = Number(guessField.value); to var userGuess === Number(guessField.value); It throws this error because it thinks you are trying to do something different. 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. Note: See our SyntaxError: missing ; before statement reference page for more details about this error. The program always says you've won, regardless of the guess you enter This could be another symptom of mixing up the assignment and strict equality operators. For example, if we were to change this line inside checkGuess(): if (userGuess === randomNumber) { to if (userGues...
...g ; before statement reference page for more details about this error. The program always says you've won, regardless of the guess you enter This could be another symptom of mixing up the assignment and strict equality operators. For example, if we were to change this line inside checkGuess(): if (userGuess === randomNumber) { to if (userGuess = randomNumber) { the test would always return true, causing the program to report that the game has been won. Be careful! SyntaxError: missing ) after argument list This one is pretty simple -- it generally means that you've missed the closing parenthesis at the end of a function/method call. Note: See our SyntaxError: missing ) after argument list reference page for more details about this error. SyntaxError: missing : after property id T...
Multimedia: video - Learn web development
t could provide a better user experience than a 10 MB download, a grainy GIF-like video may reflect poorly on the brand or project. See CanIUse.com for current browser support of video and other media types. Video autoplay To ensure that a looping background video autoplays, you must add several attributes to the video tag: autoplay, muted, and playsinline. <video autoplay="" loop="" muted="true" playsinline="" src="backgroundvideo.mp4"> While the loop and autoplay make sense for a looping and autoplaying video, the muted attribute is required for autoplay in mobile browsers. Playsinline is required for mobile Safari, allowing videos to play without forcing fullscreen mode. Remove audio from muted hero videos For hero-video or other video without audio, removing audio is smart. <vid...
...ndvideo.mp4"> While the loop and autoplay make sense for a looping and autoplaying video, the muted attribute is required for autoplay in mobile browsers. Playsinline is required for mobile Safari, allowing videos to play without forcing fullscreen mode. Remove audio from muted hero videos For hero-video or other video without audio, removing audio is smart. <video autoplay="" loop="" muted="true" playsinline="" id="hero-video"> <source src="banner_video.webm" type='video/webm; codecs="vp8, vorbis"'> <source src="web_banner.mp4" type="video/mp4"> </video> This hero-video code (above) is common to conference websites and corporate home pages. It includes a video that is auto-playing, looping, and muted. There are no controls, so there is no way to hear audio. The audio is of...
Client-Server Overview - Learn web development
The target resource URL (/search). The URL parameters (q=client%2Bserver%2Boverview&topic=apps&topic=html&topic=css&topic=js&topic=api&topic=webdev). The target/host website (developer.mozilla.org). The end of the first line also includes a short string identifying the specific pr...
...plication/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Referer: https://developer.mozilla.org/profiles/hamishwillee/edit Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.8,es;q=0.6 Cookie: sessionid=6ynxs23n521lu21b1t136rhbv7ezngie; _gat=1; csrftoken=zIPUJsAZv6pcgCBJSCj1zU6pQZbfMUAT; dwf_section_edit=False; dwf_sg_task_completion=False; _ga=GA1.2.1688886003.1471911953; ffo=true csrfmiddlewaretoken=zIPUJsAZv6pcgCBJSCj1zU6pQZbfMUAT&user-username=hamishwillee&user-fullname=Hamish+Willee&user-title=&user-organization=&user-location=Australia&user-locale=en-US&user-timezone=Australia%2FMelbourne&user-irc_nickname=&user-interests=&user-expertise=&user-twitter_url=&user-stackoverflow_url=&user-linkedin_url=&user-mozillians_url=&user-facebook_url= The main difference is that ...
Accessibility in React - Learn web development
nd set their values to the appropriately named ref objects. The textbox <input> in your editing template should be updated like this: <input id={props.id} className="todo-text" type="text" value={newName} onChange={handleChange} ref={editFieldRef} /> The "Edit" button in your view template should read like this: <button type="button" className="btn" onClick={() => setEditing(true)} ref={editButtonRef} > Edit <span className="visually-hidden">{props.name}</span> </button> Focusing on our refs with useEffect To use our refs for their intended purpose, we need to import another React hook: useEffect(). useEffect() is so named because it runs after React renders a given component, and will run any side-effects that we'd like to add to the render process, which we can't ...
...ng on our editing field Now that we know our useEffect() hook works, we can manage focus with it. As a reminder, we want to focus on the editing field when we switch to the editing template. Update your existing useEffect() hook so that it reads like this: useEffect(() => { if (isEditing) { editFieldRef.current.focus(); } }, [isEditing]); These changes make it so that, if isEditing is true, React reads the current value of the editFieldRef and moves browser focus to it. We also pass an array into useEffect() as a second argument. This array is a list of values useEffect() should depend on. With these values included, useEffect() will only run when one of those values changes. We only want to change focus when the value of isEditing changes. Try it now, and you'll see that when you...
Adding a new todo form: Vue events, methods, and models - Learn web development
he root (outer-most wrapping) element on your component. .once: Listens for the event until it's been triggered once, and then no more. .left: Only triggers the handler via the left mouse button event. .right: Only triggers the handler via the right mouse button event. .middle: Only triggers the handler via the middle mouse button event. .passive: Equivalent to using the { passive: true } parameter when creating an event listener in vanilla JavaScript using addEventListener(). In this case, we need to use the .prevent handler to stop the browser's default submit action. Add .prevent to the @submit handler in your template like so: <form @submit.prevent="onSubmit"> If you try submitting the form now, you'll notice that the page doesn't reload. If you open the console...
...omponent object containing an addToDo() method, as shown below. For now, this method can just log To-do added to the console. export default { name: 'app', components: { ToDoItem, ToDoForm }, data() { return { ToDoItems: [ { id:uniqueId('todo-'), label: 'Learn Vue', done: false }, { id:uniqueId('todo-'), label: 'Create a Vue project with the CLI', done: true }, { id:uniqueId('todo-'), label: 'Have fun', done: true }, { id:uniqueId('todo-'), label: 'Create a to-do list', done: false } ] }; }, methods: { addToDo() { console.log('To-do added'); } } }; Next, add an event listener for the todo-added event to the <to-do-form></to-do-form>, which calls the addToDo() method when the event fires. Using the @...
Focus management with Vue refs - Learn web development
ItemEditForm"> Edit <span class="visually-hidden">{{label}}</span> </button> To access the value associated with our ref, we use the $refs property provided on our component instance. To see the value of the ref when we click our "Edit" button, add a console.log() to our toggleToItemEditForm() method, like so: toggleToItemEditForm() { console.log(this.$refs.editButton); this.isEditing = true; } If you activate the "Edit" Button at this point, you should see an HTML <button> element referenced in your console. Vue's $nextTick() method We want to set focus on the "Edit" Button when a user saves or cancels their edit. To do that, we need to handle focus in the ToDoItem component's itemEdited() and editCancelled() methods. For convenience, create a new method which takes no arguments...
...via your keyboard. You'll notice that focus isn't being set, so we still have a problem to solve. If you open your console, you'll see an error raised along the lines of "can't access property "focus", editButtonRef is undefined". This seems weird. Your button ref was defined when you activated the "Edit" Button, but now it's not. What is going on? Well, remember that when we change isEditing to true, we no longer render the section of the component featuring the "Edit" Button. This means there's no element to bind the ref to, so it becomes undefined. 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 ba...
Accessibility/LiveRegionDevGuide
e: The queue should be purged of 'polite' and 'assertive' messages and the new message should be added to the queue. Current utterances should be allowed to finish but the 'rude' messages should be output as soon as possible. container-atomic The atomic property determines if a live region change should be presented on it's own or if an AT should present the entire region. 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. The text offsets associated with a text changed event are used when supporting this property. The offsets can be acquired directly in a text changed event object in AT-SPI and through the use of IAccessibleText::get_oldText and IAccessibleText::get_newText in IAc...
...ed event are used when supporting this property. The offsets can be acquired directly in a text changed event object in AT-SPI and through the use of IAccessibleText::get_oldText and IAccessibleText::get_newText in IAccessible2. When atomic is set to "false", the start index and end index/run length are used as given. The result being that only the change will be presented. When atomic is set to "true", the entire region should be presented. In this case the start index is 0 and the end index/run length is the length of the text - 1. container-channel The channel property defines two channels - 'main' and 'alert'. It was originally intended to give web developers a means to force a live region message to go to a separate output device. For instance, a 'main' channel message might go to the ...
Adding a new event
wing methods manually. virtual InternalFooEvent* AsFooEvent() MOZ_OVERRIDE This method should just return this. This method is used for retrieving sub class pointer avoiding to use static_cast. virtual WidgetEvent* Duplicate() const MOZ_OVERRIDE This method should create a new instance with copying its members except widget. For copying the members, this should use AssignFooEventData() with true for aCopyTargets. And also, mFlags should be just copied since AssignFooEventData() doesn't copy mFlags. This method is basically used for duplicating an internal event class instance of a DOM event when the DOM event is stored by content. void AssignFooEventData(const InternalFooEvent* aEvent, bool aCopyTargets) This method should copy members from aEvent. First, this method should call its su...
...sTargetedAtFocusedContent(). How to implement a DOM event class If you're in the case 3 (non-DOM events), you can skip this section. Create WebIDL of the event Write a DOM event definition with WebIDL. It should be created under dom/webidl/. See WebIDL bindings for the detail. If your new event shouldn't be created with event constructor such as: var event = new FooEvent("bar", { bubbles: true, cancelable: true, detail: 5 }); you shouldn't define construnctor in it. Create XPCOM interface for the DOM event If your event class should be accessible via XPCOM interface, you should create a new nsIDOMFooEvent interface in dom/interfaces/events/. However, in these days, this is not necessary. If all information of the event is stored by its internal event, C++ event handlers can access t...
Application cache implementation overview
a client ID (= the manifest URL + a unique time stamp). Then, nsICacheService is asked to open nsICacheSession with STORE_OFFLINE policy and the given client ID. Entry is queried using that session. nsHttpChannel::OnOfflineCacheEntryAvailable is then invoked. When aEntryStatus is a success code, entry has been found and we are loading it from the cache. LoadedFromApplicationCache flag is now set true on the channel. When aEntryStatus is a failure code, entry has not been found, but the URL is falling under one of the NETWORK or FALLBACK namespaces. When matching FALLBACK namespace, the associated fallback entry for it is remembered. The load then continues from the network as a usual load, using HTTP cache. When load of the resource fails fallback steps are performed (see "falling back on a r...
...ompletely restarted. The load starts again from the top with a completely new channel. But this time the entry is not selected to load the top level document from. We search another, if available, potentially even in a different offline cache group. Loading subresources of a document using offline cache Each sub resource loading channel is set InheritApplicationCache flag. This flag is by default true, but it is dropped by nsDocShell::DoURILoad() to false only for top level document loading channels. The InheritApplicationCache flag instructs the channel to do GetInterface on its callbacks for nsIApplicationCacheContainer. This returns the top level document the whole load group is bound to. This is the same document object that is associated the nsIApplicationCache object during the "cache se...
A bird's-eye view of the Mozilla framework
k (RDF) example, where RDF is a framework for describing and interchangingmetadata, that is, information about information. In this example, we're interested in the RDF sub-graph underlying theContents Panel widget within theHelp Viewer window. Suppose the client already has an nsIRDFDataSource object representing a sub-graph of an RDF graph and calls nsIRDFDataSource.GetTarget(resource, NC_LINK, true) to obtain an nsIRDFNode representing a specific node in the graph, in this case a link to aHelp Viewer document page. The client is completely unaware of which C++ class (or other language) actually implements nsIRDFNode; it only interacts with the IDL interface. The client would like to ask the nsIRDFNode whether its supports nsIRDFLiteral. An nsIRDFNode must be an nsIRDFLiteral or an nsIRDFRe...
...PConnect; it serves as a bridge connecting JavaScript and XPCOM. getLink() uses the nsIRDFService to obtain an nsIRDFResource for the requested link. var resource = RDF.GetResource(rdfID); nsIRDFCompositeDataSource inherits from nsIRDFDataSource, which supports a GetTarget() method for obtaining the nsIRDFNode for a given resource and property. var link = tocDS.GetTarget(resource, NC_LINK, true); Now that getLink() has the nsIRDFNode for the link, it can call QueryInterface() to check whether the nsIRDFLiteral is supported. link = link.QueryInterface(Components.interfaces.nsIRDFLiteral); If nsIRDFLiteral is supported, getLink() uses it to return the value of the link. Otherwise it returns null. if (link) return link.Value; else return null; The document page for the link is...
Browser chrome tests
Call waitForExplicitFinish() from test() if you want to delay reporting a result until after test() has returned. Call finish() once the test is complete. Be aware that the test harness will mark tests that take too long to complete as FAILED (the current timeout is 30 seconds). function test() { waitForExplicitFinish(); setTimeout(completeTest, 1000); } function completeTest() { ok(true, "Timeout ran"); finish(); } If your test is randomly timing out and you think that's just due to it taking too long, you can extend the timeout. Be aware that this is not a solution; you should investigate why your test is taking so long, since it's most likely due to a bad test design or a performance problem. If you can rewrite the test to make is shorter, split it into smaller tests, or...
...sts, or find why it's taking so long, you should really do that instead! function test() { // requestLongerTimeout accepts an integer factor, that is a multiplier for the the default 30 seconds timeout. // So a factor of 2 means: "Wait for at last 60s (2*30s)". requestLongerTimeout(2); waitForExplicitFinish(); setTimeout(completeTest, 40000); } function completeTest() { ok(true, "Timeout did not run"); finish(); } Exceptions in tests Any exceptions thrown under test() will be caught and reported in the test output as a failure. Exceptions thrown outside of test() (e.g. in a timeout, event handler, etc) will not be caught, but will result in a timed out test if they prevent finish() from being called. Cleaning up after yourself If you need to do special clean up...
Creating reftest-based unit tests
n the README.txt referenced below, which was written by the creator of the reftest tool. There is one thing about automated tests that may not be obvious. There is really no way to construct a test that is too small. If you want to check something, and it seems trivial, that is ok. The cost of adding a new test to an automated suite is very, very low. For tests that are run manually, this is not true. ...
...I can create 50 or 100 test files that have spaces between the element name and the attribute of a element for a bunch of different elements, add those to the list of tests to be run, and it causes no problems for anyone. Maybe it will actually take 500 test files to actually check this behavior. It really does not matter. ...
HTMLIFrameElement.getCanGoBack()
mpatibilities between implementations and the behavior may change in the future. The getCanGoBack() method of the HTMLIFrameElement interface is used to indicate whether it's possible to go back in the navigation history of the browser <iframe>. Syntax instanceOfHTMLIframeElement.getCanGoBack() .then(function(result) { ... ...
...); Returns A Promise that resolves with a boolean that equals true if the history can be navigated backward or false if not. Parameters None. Example function canMoveBwd() { browser.getCanGoBack().then(function(result) { if (result) { back.disabled = false; console.log("It's possible to navigate the history backward."); } else { back.disabled = true; console.log("It's not possible to navigate the history backward."); } }); } Specification Not part of any specification. ...
HTMLIFrameElement.getCanGoForward()
ompatibilities between implementations and the behavior may change in the future. The getCanGoForward() method of the HTMLIFrameElement is used to indicate whether it's possible to go forward in the navigation history of the browser <iframe>. Syntax instanceOfHTMLIframeElement.getCanGoForward() .then(function(result) { ... ...
...}); Returns A Promise that resolves with a boolean that equals true if the history can be navigated forward or false if not. Parameters None. Example function canMoveFwd() { browser.getCanGoForward().then(function(result) { if (result) { fwd.disabled = false; console.log("It's possible to navigate the history forward."); } else { fwd.disabled = true; console.log("It's not possible to navigate the history forward."); } }); } Specification Not part of any specification. ...
mozbrowseractivitydone
roduction sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The mozbrowseractivitydone event is fired when something inside the browser <iframe> triggers a web activity, and that web activity's message is consumed by the receiving app. If the activity has a returnValue set to true, then the activity is consumed when postResult or postError is invoked on the activity by the receiving app. Note: For activities where the receiving app's activity definition in its manifest does not include returnValue or returnValue is false, no mozbrowseractivitydone event will be generated as of the landing of bug 1194525 in Firefox OS 2.5. postResult and postError calls made on such an ac...
...only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: success A Boolean that indicates whether the activity has completed successfully (true) or not (false). Examples var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowseractivitydone", function(event) { if(event.details.success) { console.log('Activity completed successfully'); } else { console.log('Activity not completed successfully'); } }); Related Events mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchang...
HTTP Cache
werk/cache2/nsICacheEntry.idl Obtained asynchronously or pseudo-asynchronously by a call to nsICacheStorage.asyncOpenURI. Provides access to a cached entry data and meta data for reading or writing or in some cases both, see below. Lifetime of a new entry Such entry is initially empty (no data or meta data is stored in it). The aNew argument in onCacheEntryAvailable is true for and only for new entries. Only one consumer (the so called "writer") may have such an entry available (obtained via onCacheEntryAvailable). Other parallel openers of the same cache entry are blocked (wait) for invocation of their onCacheEntryAvailable until one of the following occurs: The writer simply throws the entry away: other waiting opener in line gets the entry agai...
...tput stream of the entry has been opened or closed metaDataReady or setValid on the entry has been called the entry has been doomed state == EMPTY: on OPER_READONLY flag use: onCacheEntryAvailable with null for the cache entry otherwise: state = WRITING opener is removed from the FIFO and remembered as the current 'writer' onCacheEntryAvailable with aNew = true and this entry is invoked (on the caller thread) for the writer state == READY: onCacheEntryCheck with the entry is invoked on the first opener in FIFO - on the caller thread if demanded result == RECHECK_AFTER_WRITE_FINISHED: opener is left in the FIFO with a flag RecheckAfterWrite such openers are skipped until the output stream on the entry is closed, the...
Implementing QueryInterface
chnique works because nsBaseImplementation is already a complete class that could have been used on its own. This technique is less appropriate when you derive from several complete classes; but it can still be used if you are sensitive to the order, e.g., // ... nsresult status; if ( !foundInterface ) { // OK, ask |nsBase1Imp| first, because I want _it_ to be the one true |nsISupports|. status = nsBase1Imp::QueryInterface(aIID, &foundInterface); if ( !foundInterface ) status = nsBase2Imp::QueryInterface(aIID, &foundInterface); if ( !foundInterface ) status = nsBase3Imp::QueryInterface(aIID, &foundInterface); } else { NS_ADDREF(foundInterface); status = NS_OK; } // ... It will...
...ace ) status = nsBase2Imp::QueryInterface(aIID, &foundInterface); if ( !foundInterface ) status = nsBase3Imp::QueryInterface(aIID, &foundInterface); } else { NS_ADDREF(foundInterface); status = NS_OK; } // ... It will be difficult, if not impossible, to get the right thing to happen if any of your base classes participate in true aggregation. You won't be able to catch calls to QueryInterface on the aggregated objects, which may then return wrong interfaces. One more reason to avoid aggregation specifically, and complicated hierarchies in general. The NS_GET_IID macro You can use the NS_GET_IID macro instead of typing out the full GetIID expression. In general, I disapprove of macros except in cases where the macro must...
Assert.jsm
nc); The new Assert instance, assert, uses reporterFunc to report assertion results or throws an AssertionError when an assertion fails, as default behavior. ok, equal, notEqual, deepEqual, notDeepEqual, strictEqual, notStrictEqual, throws, setReporter, report Methods ok() Pure assertion tests whether a value is truthy, as determined by !!guard. This statement is equivalent to assert.equal(true, !!guard, message_opt);. To test strictly for the value true, use assert.strictEqual(true, guard, message_opt);. undefined ok( actual, message ); Parameters actual Test subject to be evaluated as truthy message Short explanation of the expected result equal() The equality assertion tests shallow, coercive equality with ==. undefined equal( actual, expected, message ); Par...
...xplanation of the expected result operator Operation qualifier used by the assertion method (ex: '==') Examples Custom reporter example Components.utils.import("resource://testing-common/Assert.jsm"); let assert = new Assert(); assert.setReporter(function customReporter(err, message, stack) { if (err) { do_report_result(false, err.message, err.stack); } else { do_report_result(true, message, stack); } }); ...
API-provided widgets
m for fine-grained control over the creation of the widget. viewId Only useful for views (and required there): the id of the that should be shown when clicking the widget. tooltiptext string to use for the tooltip of the widget label string to use for the label of the widget removable whether the widget is removable (optional, default: true). NB: if you specify false here, you must provide a defaultArea, too. overflows whether widget can overflow when in an overflowable toolbar (optional, default: true) defaultArea default area to add the widget to (optional, default: none; required if non-removable) shortcutId id of an element that has a shortcut for this widget (optional, default: null). Thi...
.... This is only used to display the shortcut as part of the tooltip for builtin widgets (which have strings inside customizableWidgets.properties). If you're in an add-on, you should not set this property, and should instead include the shortcut as part of the tooltiptext you pass in yourself. showInPrivateBrowsing whether to show the widget in private browsing mode (optional, default: true) Event handlers You can also define several event handlers which will be called at various stages in a widget's lifetime: Event handler name Description onBuild(aDoc) Only useful for custom widgets (and required there); a function that will be invoked with the document in which to build a widget. Should return the DOM node that has been constructed. NB: the DOM no...
Widget Wrappers
D type the type of widget (button, view, custom). For XUL-provided widgets, this is always 'custom' provider the provider type of the widget, id est one of PROVIDER_API or PROVIDER_XUL instances an array of all instances (single window wrappers) of the widget. This array is NOT live. 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. NB: this property is writable, and will toggle all the widgets' nodes' disabled states label for API-provided widgets, the label of the widget...
...nels opened from this node. 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. Note that you may prefer to use the g...
Dict.jsm
se top-level objects are not copied. Dict copy(); Parameters None. Return value A new dictionary object containing the same top-level items as the original dictionary on which the copy() method was called. del() Deletes a key/value pair from the dictionary, given a key. boolean del( String aKey ); Parameters aKey The key for the item to delete from the dictionary. Return value true if an entry was found and removed; false if no match was found. get() Returns the value corresponding to the specified key. Object get( String aKey, [optional] Object aDefault ); Parameters aKey The key whose value should be returned. aDefault Optional The value to return if the specified key isn't found. If you don't specify a default value, undefined is returned for keys that are...
... isn't found. If you don't specify a default value, undefined is returned for keys that aren't found. Return value The value of the specified key, or undefined if no matching key was found. has() Determines whether or not the specified key exists in the dictionary. boolean has( String aKey ); Parameters aKey The key for which to determine existence in the dictionary. Return value true if the specified key is in the dictionary, otherwise false. listitems() Returns an array of the key/value pairs in the dictionary. Note: The order in which items are returned is arbitrary. Array listitems(); Parameters None. Return value An array of the key/value pairs in the dictionary. listkeys() Returns an array of the keys in the dictionary. Note: The order in which items are retu...
Downloads.jsm
try { let download = yield Downloads.createDownload({ source: "http://www.mozilla.org/", target: OS.Path.join(OS.Constants.Path.tmpDir, "example-download.html"), }); list.add(download); try { download.start(); alert("Now monitoring all downloads. Close the message to stop."); } finally { yield list.remove(download); yield download.finalize(true); } } finally { yield list.removeView(view); } }).then(null, Components.utils.reportError); Conversion from nsIDownloadManager Starting in Firefox for Desktop version 26, the nsIDownloadManager and nsIDownload interfaces are not available anymore. The new module works differently from the old component. In general, you should be aware of the following highlights: There is no d...
...se the new download manager. By default it is not enabled. It will be enabled when the bug 851471 will be closed. If you don't activate it, you could use Downloads.jsm, but your view will not be called by the external helper app service (when a user click on a file to download, in a web page). To enable the new download manager : First you have to set the pref browser.download.useJSTransfer to true. Then you should declare the new nsITransfer object during the startup of your app. Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar) .registerFactory(Components.ID("{1b4c85df-cbdd-4bb6-b04e-613caece083c}"), "", "@mozilla.org/transfer;1", null); ...
FileUtils.jsm
fied hierarchy under a nsIDirectoryService key. nsIFile getFile( string key, array pathArray, bool followLinks ); Parameters key The nsIDirectoryService key to start from (see Getting special files for more info) pathArray An array of path components to locate beneath the directory specified by key. The last item in this array must be the leaf name of a file. followLinks Optional True if links should be followed, false otherwise. Return value Returns a nsIFile object for the file specified. The file is NOT created if it does not exist, however all required directories along the way are. getDir() Gets a directory at the specified hierarchy under a nsIDirectoryService key. nsIFile getDir( string key, array pathArray, bool shouldCreate, bool followLInks ); Paramet...
... getDir() Gets a directory at the specified hierarchy under a nsIDirectoryService key. nsIFile getDir( string key, array pathArray, bool shouldCreate, bool followLInks ); Parameters key The nsIDirectoryService key to start from (see Getting special files for more info) pathArray An array of path components to locate beneath the directory specified by key. shouldCreate Optional True if the directory hierarchy specified in pathArray should be created if it does not exist, false otherwise. followLinks Optional True if links should be followed, false otherwise location specified. Return value Returns a nsIFile object for the location specified. If the directory requested does not exist, it is created, along with any parent directories that need to be created. Note: If yo...
Sqlite.jsm
does not exist, a new SQLite database will be created. The value typically ends with .sqlite. sharedMemoryCache (optional) Boolean indicating whether multiple connections to the database share the same memory cache. Sharing the memory cache likely results in less memory utilization. However, sharing also requires connections to obtain a lock, possibly making database access slower. Defaults to true. shrinkMemoryOnConnectionIdleMS (optional) If defined, the connection will attempt to minimize its memory usage after this many milliseconds of connection idle. The connection is idle when no statements are executing. There is no default value which means no automatic memory minimization will occur. Please note that this is not a timer on the idle service and this could fire while the applicati...
...; try { Sqlite.shutdown.addBlocker("My connection closing", async () => await conn.close()); } catch (e) { // It's too late to block shutdown, just close the connection. await conn.close(); throw e; } clone(readOnly) This function returns a clone of the current connection-promise. These functions receive the following arguments: readOnly (optional) If true the clone will be read-only, default is false. If the original connection is already read-only, the clone will be, regardless of this option. If the original connection is using the shared cache, this parameter will be ignored and the clone will be as privileged as the original connection. transactionInProgress This boolean property indicates whether a transaction is in progress. This is rar...
WebChannel.jsm
nderContext The senderContext parameter passed to the .listen method. ...
...://mozilla.org", null, null)); // receive messages channel.listen(function (webChannelId, message, senderContext) { // send messages channel.send({ data: { greeting: true } }, senderContext); }); Webpage code Receive Messages from an existing WebChannel in content code window.addEventListener("WebChannelMessageToContent", function(e) { // receive messages console.log(e.detail); }, true); Send Messages to an existing WebChannel in chrome code window.dispatchEvent(new window.CustomEvent("WebChannelMessageToChrome", { detail: { id: webChannelId, message: { something: true } } })); ...
XPCOMUtils.jsm
implementing nsIFactory). If not // provided, the default factory is used, which returns // |(new MyComponent()).QueryInterface(iid)| in its createInstance(). _xpcom_factory: { ... }, // [optional] an array of categories to register this component in. _xpcom_categories: [{ // Each object in the array specifies the parameters to pass to // nsICategoryManager.addCategoryEntry(). ...
...meters to pass to // nsICategoryManager.addCategoryEntry(). 'true' is passed for // both aPersist and aReplace params. 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. When set to true, and only if 'value' // is not specified, the concatenation of the string "service," and the // object's contractID is passed as aValue parameter of addCategoryEntry. service: true, // optional array of applications' IDs in the form: // [ "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}", ... ] // If this is defined, the component is registered in this // category only on the s...
Creating localizable web applications
po: #. L10n: This will be wrongly indented. msgid "" "Long text\n" " Second part\n" " Third part\n" msgstr "" In order to indent your code, you must use string concatenation. See snippet 4 above for an example of how to do this. Use gettext contexts Depending on context in which it is used, one English string might require two or more different translations. This is particularly true for short strings, like "File" or "Log in". For instance, "Log in" as a button label might be translated by a localizer as the imperative, but for a dialog title, the localizer may choose to use a different form, like gerund (much like "Logging in"). Gettext's context feature allows the developer to distinguish between two identical English strings and disambiguate the translation. Use gettext p...
...ers">' . sprintf(ngettext("%d active daily user", "%d active daily users"), number_format($persona['popularity'])) . '</p>'; One might argue that adding plural support here is not necessary because, for instance, the number of daily users in the example above will always be greater than 1, i.e. will always require the use of the plural form. While this is true for English, it should be noted that some languages require different forms of strings for numbers greater than 1 as well. For example, all numbers ending in 2, 3 or 4 (be it 21 or 1021) might require a special plural form. Read more about plurals in gettext and about plural rules for different languages. Don't use text as decoration This needs more work. <?printf("<a href=\"%s\">" . _("Step...
MathML Demo: <mo> - operator, fence, separator, or accent
In general, the lspace and rspace around arrows should be similar to the spacing around relations. There is an issue with the markup of "long" LaTeX arrows in MathML. There are entities from these arrows, &xlarr; &xlArr; &xrarr; etc. but they have no standard unicodes. They can be viewed as stretched versions of short arrows. \longleftarrow can be scripted as <mo>&xlarr;</mo> or as <mo stretchy="true" minsize="1.8">&larr;</mo>. a ? b <- c a ? b <= c a ? b -> c a ? b => c a ? b <-> c a ? b <=> c a ? b ? c a ? b ? c a ? b ? c a ? b ? c a ? b ? c a ? b ? c a ? b ? c a ? b ? c a ? b ? c ...
.... This problem can be solved using aligned arrays, as follows a b c d a b c d However, all reasonable attempts to fence the column vector will fail because LaTeX fences are symmetric. In MathML, operators that are used for fencing are never symmetric and are always stretchy by default. (i.e., as documented in the suggested Operator Dictionary). Hence <mo symmetric="true"> must be scripted if the intent is to emulated LaTeX fence behavior. The commands \big, \Big, \bigg and \Bigg produce a discreet set of increasingly taller fences, | 1 + | 2 + | 3 + | 4 + | . | + 5 | + 6 | + 7 | + 8 | . Here's the same expression in a display | 1 + | 2 + | 3 + | 4 + | . | + 5 | + 6 | + 7 | + 8 | The size ratio is 3.0 : 2.4 : 1.8 : 1.2. Fixed s...
Using the viewport meta tag to control layout on mobile browsers
ould make sure that your pages work well in a large variation of screen sizes and orientations. The default pixel ratio depends on the display density. On a display with density less than 200dpi, the ratio is 1.0. On displays with density between 200 and 300dpi, the ratio is 1.5. For displays with density over 300dpi, the ratio is the integer floor(density/150dpi). Note that the default ratio is true only when the viewport scale equals 1. Otherwise, the relationship between CSS pixels and device pixels depends on the current zoom level. Viewport width and screen width Sites can set their viewport to a specific size. For example, the definition "width=320, initial-scale=1" can be used to fit precisely onto a small phone display in portrait mode. This can cause problems when the browser doesn...
...cations Specification Status Comment CSS Device AdaptationThe definition of '<meta name="viewport">' in that specification. Working Draft Non-normatively describes the Viewport META element There is clearly demand for the viewport meta tag, since it is supported by most popular mobile browsers and used by thousands of web sites. It would be good to have a true standard for web pages to control viewport properties. As the standardization process proceeds, we at Mozilla will work to keep up to date with any changes. ...
A brief guide to Mozilla preferences
atches the default. Sticky preferences are generally used for preferences that have a different default value in different channels with the intent being that once the user sets the preference in one channel, the preference will remain with that value when using a different channel with different defaults. For example, let's assume that Nightly has a preference "some.preference" which defaults to true while DeveloperEdition defaults the same preference to false and the user desires the preference to have the value true in both channels. If the preference is not a sticky preference and the user runs DeveloperEdition and flips the pref to true it will be saved as it is not the default. When the user then runs Nightly, the preference now has the same value as the default, so is not written by Nig...
...uns DeveloperEdition and flips the pref to true it will be saved as it is not the default. When the user then runs Nightly, the preference now has the same value as the default, so is not written by Nightly. When the user then runs DeveloperEdition again, the preference value will be false as no user preference was written by Nightly. If the preference is defined as a sticky preference, the value true will be written by Nightly even though it matches the current default, so when DeveloperEdition is run the preference keeps the desired value of true. ...
browser.urlbar.trimURLs
If the address starts with http:// and neither starts with a ftp. ...
...If the address starts with http:// and neither starts with a ftp. ...
Preference reference
ssibility.tabfocusThe preference accessibility.tabfocus controls what elements receive focus when the user presses the Tab key.browser.altClickSaveThe preference browser.altClickSave controls whether clicking a link while holding the alt key starts the download of that link.browser.dom.window.dump.enabledThis setting enables the dump function, which sends messages to the system console. 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. Changes require an application restart.browser.download.lastDir.savePerSitebrowser.download.lastDir.savePerSite controls whether the directory preselected ...
...he 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. Changes require an application restart.browser.download.lastDir.savePerSitebrowser.download.lastDir.savePerSite controls whether the directory preselected in the file picker for saving a file download is being remembered on a per-website (host) base. ...
PRLinger
interval (in PRIntervalTime units) to linger on closing a socket if any data remain in the socket send buffer. Syntax #include <prio.h> typedef struct PRLinger { PRBool polarity; PRIntervalTime linger; } PRLinger; Fields The structure has the following fields: polarity Polarity of the option's setting: PR_FALSE means the option is off, in which case the value of linger is ignored. PR_TRUE means the option is on, and the value of linger will be used to determine how long PR_Close waits before returning. linger Time (in PRIntervalTime units) to linger before closing if any data remain in the socket send buffer. Description By default, PR_Close returns immediately, but if there are any data remaining in the socket send buffer, the system attempts to deliver the data to the peer. T...
...em attempts to deliver the data to the peer. The PR_SockOpt_Linger socket option, with a value represented by a structure of type PRLinger, makes it possible to change this default as follows: If polarity is set to PR_FALSE, PR_Close returns immediately, but if there are any data remaining in the socket send buffer, the runtime attempts to deliver the data to the peer. If polarity is set to PR_TRUE and linger is set to 0 (PR_INTERVAL_NO_WAIT), the runtime aborts the connection when it is closed and discards any data remaining in the socket send buffer. If polarity is set to PR_TRUE and linger is nonzero, the runtime lingers when the socket is closed. That is, if any data remains in the socket send buffer, PR_Close blocks until either all the data is sent and acknowledged by the peer or the...
PR_Wait
s parameter elapses. The resumption from the wait is merely a hint that a change of state has occurred. It is the responsibility of the programmer to evaluate the data and act accordingly. This is usually done by evaluating a Boolean expression involving the monitored data. While the Boolean expression is false, the thread should wait. The thread should act on the data only when the expression is true. The boolean expression must be evaluated while in the monitor and within a loop. In pseudo-code, the sequence is as follows: PR_EnterMonitor(&ml); while (!expression) wait; ... act on the state change ... PR_ExitMonitor(&ml); A thread can be resumed from a wait for a variety of reasons. The most obvious is that it was notified by another thread. If the value of timeout is not PR_INTERVAL_...
... ...
NSS 3.15 release notes
ozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_15_RTM/src/ New in NSS 3.15 New Functionality Support for OCSP Stapling (RFC 6066, Certificate Status Request) has been added for both client and server sockets. TLS client applications may enable this via a call to SSL_OptionSetDefault(SSL_ENABLE_OCSP_STAPLING, PR_TRUE); Added function SECITEM_ReallocItemV2. It replaces function SECITEM_ReallocItem, which is now declared as obsolete. Support for single-operation (eg: not multi-part) symmetric key encryption and decryption, via PK11_Encrypt and PK11_Decrypt. certutil has been updated to support creating name constraints extensions. New Functions in ssl.h SSL_PeerStapledOCSPResponse - Returns...
...on as a single PKCS#11 operation (eg: not multi-part). This is necessary for AES-GCM. New Types in secitem.h SECItemArray - Represents a variable-length array of SECItems. New Macros in ssl.h SSL_ENABLE_OCSP_STAPLING - Used with SSL_OptionSet to configure TLS client sockets to request the certificate_status extension (eg: OCSP stapling) when set to PR_TRUE Notable Changes in NSS 3.15 SECITEM_ReallocItem is now deprecated. Please consider using SECITEM_ReallocItemV2 in all future code. NSS has migrated from CVS to the Mercurial source control management system. Updated build instructions are available at Migration to HG As part of this migration, the source code directory layout has been re-organized. The list of...
NSS 3.30 release notes
e (NSPR); 4.13.1 or newer. NSS 3.30 source distributions are available on ftp.mozilla.org for secure HTTPS download: Source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/NSS_3_30_RTM/src/ New in NSS 3.30 New Functionality In the PKCS#11 root CA module (nssckbi), CAs with positive trust are marked with a new boolean attribute, CKA_NSS_MOZILLA_CA_POLICY, set to true. Applications that need to distinguish them from other other root CAs, may use the exported function PK11_HasAttributeSet. Support for callback functions that can be used to monitor SSL/TLS alerts that are sent or received. New Functions in cert.h CERT_CompareAVA - performs a comparison of two CERTAVA structures, and returns a SECComparison result. in pk11pub.h PK11_HasAt...
...currently only accepts an RSA public/private key pair. New Macros in ciferfam.h PKCS12_AES_CBC_128, PKCS12_AES_CBC_192, PKCS12_AES_CBC_256 - cipher family identifiers corresponding to the PKCS#5 v2.1 AES based encryption schemes used in the PKCS#12 support in NSS in pkcs11n.h CKA_NSS_MOZILLA_CA_POLICY - identifier for a boolean PKCS#11 attribute, that should be set to true, if a CA is present because of it's acceptance according to the Mozilla CA Policy Notable Changes in NSS 3.30 The TLS server code has been enhanced to support session tickets when no RSA certificate (e.g. only an ECDSA certificate) is configured. RSA-PSS signatures produced by key pairs with a modulus bit length that is not a multiple of 8 are now supported. The pk12util tool now supp...
NSS Sample Code sample2
buf2 len must be atleast buf1 len */ tmp1_outlen = tmp2_outlen = 0; /* Create cipher context */ EncContext = PK11_CreateCo...
...ext */ EncContext = PK11_CreateContextBySymKey(cipherMech, CKA_DECRYPT, SymKey, SecParam); rv1 = PK11_CipherOp(EncContext, buf2, &tmp1_outlen, sizeof(buf2), buf1, result_len); rv2 = PK11_DigestFinal(EncContext, buf2+tmp1_outlen, &tmp2_outlen, result_len-tmp1_outlen); PK11_DestroyContext(EncContext, PR_TRUE); result_len = tmp1_outlen + tmp2_outlen; if (rv1 != SECSuccess || rv2 != SECSuccess) goto out; fprintf(stderr, "Decrypted Data: %s\n", buf2); /* =========================== END SECTION ============================= */ out: if (SymKey) PK11_FreeSymKey(SymKey); if (SecParam) SECITEM_FreeItem(SecParam, PR_TRUE); } ...
nss tech note2
, etc. To enable this mode, set: NSPR_LOG_MODULES=nss_mod_log:4 NSPR_LOG_FILE=<logfile> The output format is the same as above, but with more information. ...
...Collect performance data. This mode is most useful in optimized builds. The number of calls to each PKCS #11 function will be counted, and the time spent in each function as well. A summary of performance data is dumped during NSS shutdown. No additional environment variables are required for this mode. If ...
Rhino overview
SCRIPT tag with values such as "JavaScript1.2". Version 1.3 and greater are ECMA conformant. Operators == and != Version 1.2 only uses strict equality for the == and != operators. In version 1.3 and greater, == and != have the same meanings as ECMA. The operators === and !== use strict equality in all versions. ToBoolean Boolean(new Boolean(false)) is false for all versions before 1.3. It is true (and thus ECMA conformant) for version 1.3 and greater. Array.prototype.toString and Object.prototype.toString Version 1.2 only returns array or object literal notation ("[1]" or "{a:1, b:2}" for example). In version 1.3 and greater these functions are ECMA conformant. Array constructor Array(i) for a number argument i constructs an array with a single element equal to i for version 1.2 only.
...dings that run untrusted JavaScript code must do two things to enable the security features. First, every Context that is created must be supplied an instance of an object that implements the SecuritySupport interface. This will provide Rhino the support functionality it needs to perform security-related tasks. Second, the value of the property security.requireSecurityDomain should be changed to true in the resource bundle org.mozilla.javascript.resources.Security. The value of this property can be determined at runtime by calling the isSecurityDomainRequired method of Context. Setting this property to true requires that any calls that compile or evaluate JavaScript must supply a security domain object of any object type that will be used to identify JavaScript code. In a typical client embed...
Rhino scopes and contexts
and to remove a possibility for them to occur one can seal the shared scope and all its objects. A notion of a sealed object is a JavaScript extension supported by Rhino and it means that properties can not be added/deleted to the object and the existing object properties can not be changed. Any attempt to modify sealed object throws an exception. To seal all objects in the standard library passtrue for the sealed argument when calling Context.initStandardObjects(ScriptableObject, boolean): ScriptableObject sealedSharedScope = cx.initStandardObjects(null, true); This seals only all standard library objects, it does not seal the shared scope itself thus after callinginitStandardObjects, sealedSharedScope can be farther populated with application-specific objects and functions. Then after a...
...ld be able to alter the objects themselves. Note that currently in order to use Java classes (LiveConnect) from a sealed shared scope you need to pre-load a number of objects needed for LiveConnect into the scope before it gets sealed. These objects would normally be lazy loaded but the lazy loading fails if the scope is sealed. ScriptableObject sealedSharedScope = cx.initStandardObjects(null, true); // Force the LiveConnect stuff to be loaded. String loadMe = "RegExp; getClass; java; Packages; JavaAdapter;"; cx.evaluateString(sealedSharedScope , loadMe, "lazyLoad", 0, null); sealedSharedScope .sealObject(); Dynamic Scopes There's one problem with the setup outlined above. Calls to functions in JavaScript use static scope, which means that variables are first looked up in the function an...
Scripting Java
illa.javascript.Context@bb6ab6 Working with Java Now that we can access Java classes, the next logical step is to create an object. This works just as in Java, with the use of the new operator: js> new java.util.Date() Thu Jan 24 16:18:17 EST 2002 If we store the new object in a JavaScript variable, we can then call methods on it: js> f = new java.io.File("test.txt") test.txt js> f.exists() true js> f.getName() test.txt Static methods and fields can be accessed from the class object itself: js> java.lang.Math.PI 3.141592653589793 js> java.lang.Math.cos(0) 1 In JavaScript, unlike Java, the method by itself is an object and can be evaluated as well as being called. If we just view the method object by itself we can see the various overloaded forms of the method: js> f.listFiles funct...
... method's name as the additional argument. Function can use it to distinguish on behalf of which method it was called: js> var frame = new Packages.javax.swing.JFrame(); js> frame.addWindowListener(function(event, methodName) { if (methodName == "windowClosing") { print("Calling System.exit()..."); java.lang.System.exit(0); } }); js> frame.setSize(100, 100); js> frame.visible = true; true js> Calling System.exit()... Creating Java Arrays Rhino provides no special syntax for creating Java arrays. You must use the java.lang.reflect.Array class for this purpose. To create an array of five Java strings you would make the following call: js> a = java.lang.reflect.Array.newInstance(java.lang.String, 5); [Ljava.lang.String;@7ffe01 To create an array of primitive types, we mus...
Invariants
ompartments Suppose obj = JS_GetScopeChain(cx) is not null. Then cx->compartment == obj->compartment(). When a new object is created, it is automatically created in cx->compartment, but its parent and prototype are often determined by examining the scope chain. The object and its proto and parent must be in the same compartment. So it is utterly crucially important that this invariant always be true if objects are being created. The public API for compartment-hopping, JSAutoEnterCompartment, and the internal API, js::AutoCompartment, both make sure the invariant is maintained. However, there is another internal API, js::SwitchToCompartment, that lets you break this invariant, and of course in XPConnect we use that from time to time when we know we aren't going to be creating any new objects...
..., which have no parent or prototype) or doing anything that might call back into native code that could create objects. We do this in order to save some CPU cycles (in other words, for no good reason whatsoever). If !JS_IsRunning(cx) && cx->globalObject == NULL, then cx->compartment == cx->runtime->defaultCompartment. While executing a script, cx->compartment == script->compartment. But this is true only so long as we are actually in the interpreter or JIT code. A JSNative or other callback may move cx to another compartment, as long as it returns cx to the script's compartment before returning. A given trace-jit trace stays within a single compartment (indeed, a single global object) end-to-end. Lifetime invariants In some places, pointers to JSObjects and JSStrings must refer to live he...
JS::PersistentRooted
be a global variable. // JS::PersistentRootedValue persistentVal; static bool SetPersistent(JSContext* cx, unsigned argc, JS::Value* vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); // Set persistent value. ...
...s.rval().setUndefined(); return true; } static bool GetPersistent(JSContext* cx, unsigned argc, JS::Value* vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); // Get persistent value. JS::RootedValue val(cx, persistentVal.ref()); // or // JS::RootedValue val(cx, *persistentVal); // [SpiderMonkey 38] // JS::RootedValue val(cx, persistentVal); args.rval().set(val); return true; } static const JSFunctionSpec functions[] = { JS_FN("getPersistent", GetPersistent, 1, 0), JS_FN("setPersistent", SetPersistent, 0, 0), JS_FS_END }; int main(int argc, const char* argv[]) { // Initialize runtime // ... // Initialize here persistentVal.construct(rt, JS::NullValue()); // or // persistentVal = new JS::PersistentRootedValue(rt, JS::NullValue()); // [SpiderMo...
JSDeletePropertyOp
e property identifier) or an integer (element index). succeeded bool * Out parameter. Receives the result of deletion. Description JSDeletePropertyOp callback is a hook that applications may install to be called at some point during property access. A JSDeletePropertyOp may be installed on a JSClass to hook property deletes. If a JSDeletePropertyOp does nothing and returns true, then property delete is unaffected. It proceeds as normal. This callback may veto the ongoing property operation by optionally reporting an error or raising an exception and then returning false. The operation then fails, and the error is propagated to the caller. Otherwise the callback must return true, and the property operation proceeds. JSClass hooks JSClass offers the following hook: ...
...ion proceeds. JSClass hooks JSClass offers the following hook: JSClass.delProperty is called during most property deletions, even when obj has no property named id. If an error occurred, 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. This will cause delete obj[id] to evaluate to false in non-strict mode code, and to throw a TypeError in strict mode code. If no error occurred and the deletion wasn't disallowed (this is *not* the same as saying that a deletion actually occurred -- deleting a non-existent property, or an inherited property, is allowed -- it's just pointless), set *succeeded to true and return true. This h...
JS_AlreadyHasOwnProperty
sOwnPropertyById) The name of the property to search for. namelen size_t (in JS_AlreadyHasOwnUCProperty only) The length of name, in characters; or the special value (size_t) -1 to indicate that name is null-terminated. index uint32_t (in JS_AlreadyHasOwnElement only) The index of the element to search for. foundp bool * Out parameter. *foundp receives true if the property is found or false if it is not found. If an error occurs, the value left in *foundp is undefined. Description These functions attempt to determine whether a property already exists on a specific JSObject without modifying the object. By design, this search may not find a property that other property lookup functions, such as JS_LookupProperty, would find. For native objects-...
...azily resolved property has not yet been resolved.) Shared, permanent, delegated properties are not found. (Such properties are an implementation detail of SpiderMonkey. They are meant to be a transparent optimization; this is the only API that breaks the abstraction.) For non-native objects, this falls back on a complete search. This calls the JSObjectOps.lookupProperty hook. *foundp is set to true only if lookupProperty reports that the property was found on obj itself and not on some other object (even the corresponding outer object, if any). If the property is found on obj, this sets *foundp to true and returns true. If the property is not found on obj, this sets *foundp to false and returns true (to indicate that no error occurred). If the search fails with an error or exception, this r...
JS_GetPropertyAttributes
ich to retrieve attributes. namelen size_t (only in JS_GetUCPropertyAttributes) The length of name in characters; or (size_t) -1 to indicate that name is null-terminated. attrsp unsigned int * Out parameter. If the specified property is found on obj, *attrsp receives its attributes. foundp JSBool * Out parameter. 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 value left in *foundp is unspecified. Description JS_GetPropertyAttributes retrieves the property attributes of the property with the given name on a given object, obj. JS_GetUCPropertyAttributes is the Unicode version of the function. If an error occurs, the return value is JS_FALSE, and the valu...
...tUCPropertyAttributes is the Unicode version of the function. 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. The value left in *attrsp is unspecified. The return value is JS_TRUE (to indicate that no error occurred). If the property exists and belongs to obj, then *foundp is set to JS_TRUE, *attrsp is set to the logical OR of zero or more Property attributes flags, and the function returns JS_TRUE. See Also Property attributes bug 893186 ...
JS_HasOwnProperty
cx JSContext * A context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject Object to search on for the property. name or id const char * or JS::HandleId Name of the property to look up. foundp bool * Non-null pointer to a variable of type bool. On success, JS_HasOwnProperty stores true in this variable if obj has an own property with the given name, and false if not. Description JS_HasOwnProperty searches an object, obj, for an own property with the specified name. It behaves like the JavaScript expression Object.hasOwnProperty(obj, name). JS_HasOwnPropertyById is the same but takes a JS::HandleId for the property name. If the property exists, this function sets *found...
...his variable if obj has an own property with the given name, and false if not. Description JS_HasOwnProperty searches an object, obj, for an own property with the specified name. It behaves like the JavaScript expression Object.hasOwnProperty(obj, name). JS_HasOwnPropertyById is the same but takes a JS::HandleId for the property name. If the property exists, this function sets *foundp to true and returns true. If the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred). If an error occurs during the search, the function returns false, and the value of *foundp is undefined. See Also MXR ID Search for JS_HasOwnProperty MXR ID Search for JS_HasOwnPropertyById bug 1163423 ...
JS_HasProperty
bject Object to search on for the property. name or id const char * or const char16_t or JS::HandleId Name of the property to look up. namelen size_t (only in JS_HasUCProperty) The length of name in characters, or -1 to indicate that name is null-terminated. foundp bool * Non-null pointer to a variable of type bool. On success, JS_HasProperty stores true in this variable if obj has a property with the given name, and false if not. Description JS_HasProperty searches an object, obj, and its prototype chain, for a property with the specified name. It behaves like the JavaScript expression name in obj. JS_HasUCProperty is the corresponding Unicode API. JS_HasPropertyById is the same but takes a JS::HandleId for the property name. If the proper...
...ith the given name, and false if not. Description JS_HasProperty searches an object, obj, and its prototype chain, for a property with the specified name. It behaves like the JavaScript expression name in obj. JS_HasUCProperty is the corresponding Unicode API. JS_HasPropertyById is the same but takes a JS::HandleId for the property name. If the property exists, this function sets *foundp to true and returns true. If the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred). If an error occurs during the search, the function returns false, and the value of *foundp is undefined. See Also MXR ID Search for JS_HasProperty MXR ID Search for JS_HasUCProperty MXR ID Search for JS_HasPropertyById bug 461163 ...
JS_InstanceOf
al argument vector. If non-null, report an error if obj is not of type clasp. argv must be the argv argument passed from the engine to a JSNative callback, JS_ARGV(cx, rv) in a JSFastNative callback, or NULL. Obsolete since JSAPI 32 Description JS_InstanceOf can be used to check whether an object obj is of a particular JSClass. To use it this way, pass NULL for argv. JS_InstanceOf returns true if obj is of the given class and false otherwise. That is, it returns JS_GetClass(obj) == clasp. JS_InstanceOf can also be used in native functions to check the class of an argument when a particular class is required. To use it this way, pass the arguments provided by the engine for args with JS::CallArgsFromVp(argc, vp). When args is non-null, JS_InstanceOf behaves as follows. If obj is of the...
...lass and false otherwise. That is, it returns JS_GetClass(obj) == clasp. JS_InstanceOf can also be used in native functions to check the class of an argument when a particular class is required. To use it this way, pass the arguments provided by the engine for args with JS::CallArgsFromVp(argc, vp). When args is non-null, JS_InstanceOf behaves as follows. If obj is of the given class, it returns true. Otherwise, it returns false; it also reports a TypeError containing the function's name. Note that JS_InstanceOf is not the equivalent of the JavaScript instanceof keyword, which examines constructor properties along the prototype chain. JS_HasInstance is similar to instanceof. See Also MXR ID Search for JS_InstanceOf JS_HasInstance JS_GetClass bug 959787 ...
JS_ResolveStandardClass
to initialize JS function and object classes. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject An object to resolve id to a standard class. id JS::HandleId An id of a standard class name, which must contain either a string or an int. resolved bool * Out parameter. If the id is resolved, true is stored into *resolved if success. false otherwise. Description JS_ResolveStandardClass resolves id, which must contain either a string or an int, to a standard class name in obj if possible, defining the class's constructor and/or prototype and storing true in *resolved. If id does not name a standard class or a top-level property induced by initializing a standard class, store false i...
...Return false on error, as usual for bool result-typed API entry points. ...
JS_SameValue
me, as determined by the SameValue algorithm in ECMAScript 262, 5th edition. SameValue slightly differs from strict equality (===) in that +0 and -0 are not the same and in that NaN is the same as NaN. ...
...ext * Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v1 JS::Handle&lt;JS::Value&gt; / jsval The first value. v2 JS::Handle&lt;JS::Value&gt; / jsval The second value. Description JS_SameValue determines whether two values are the same, returning true or false accordingly. This method is infallible. See Also MXR ID Search for JS_SameValue JS_StrictlyEqual JS_LooselyEqual bug 1132045 -- use handle ...
JS_SetArrayLength
uest on this JSContext. obj JS::Handle&lt;JSObject*&gt; The array to modify. length uint32_t Number of array elements to set. Description JS_SetArrayLength sets the .length property of an object obj. length indicates the number of elements. JS_SetArrayLength(cx, obj, n) is exactly the same as setting the length property of obj to n using JS_SetProperty. This is true even if obj is not an Array object. You can call JS_SetArrayLength either to set the number of elements for an array object you created without specifying an initial number of elements, or to change the number of elements allocated for an array. If you set a shorter array length on an existing array, the elements that no longer fit in the array are destroyed. Setting the number of array elements ...
...er fit in the array are destroyed. Setting the number of array elements does not initialize those elements. To initialize an element call JS_DefineElement. If you call JS_SetArrayLength on an existing array, and length is less than the highest index number for previously defined elements, all elements greater than or equal to length are automatically deleted. On success, JS_SetArrayLength returns true. Otherwise it returns false. See Also MXR ID Search for JS_SetArrayLength JS_DefineElement JS_DeleteElement JS_GetArrayLength JS_GetElement JS_IsArrayObject JS_LookupElement JS_NewArrayObject JS_SetElement ...
JS_SetBranchCallback
JS_THREADSAFE builds, the JavaScript engine calls this callback only from within an active request on cx. The callback does not need to call JS_BeginRequest()). script JSScript The script that is running. This is guaranteed to be non-null, unless the JSOPTION_NATIVE_BRANCH_CALLBACK option has been enabled for the context cx using JS_SetOptions(). If the callback returns JS_TRUE, the JS engine continues to execute the script. If the callback raises an exception using JS_SetPendingException() and returns JS_FALSE, then the JavaScript engine propagates the exception to the script that was executing at the time. If the callback returns JS_FALSE without raising an exception, then the JavaScript engine immediately stops running the script with an uncatchable error. The engi...
...at runs for a long time. Another use is to call JS_MaybeGC periodically. The callback is called very frequently, so applications should ensure that the callback runs very quickly most of the time. Typically an application only wants to do something every 5,000 or so branches. A common technique is to use a counter. The callback simply increments the counter and does nothing further (returning JS_TRUE immediately) unless the counter has reached the threshold value. See Also MXR ID Search for JS_SetBranchCallback JS_SetOperationCallback JS_SetOptions bug 477187 ...
JS_SetContextCallback
ter to a JSContext which the callback may use to call into JSAPI functions. This is the context which was just created, or is about to be destroyed. For example, the callback my call JS_GetContextPrivate(cx) in order to free up resources previously allocated by JS_SetContextPrivate. contextOp unsigned See JSContextOp. For future compatibility the callback must do nothing and return true if any other value is passed. data void * data specified in JS_SetContextCallback. Added in SpiderMonkey 31 typedef enum JSContextOp { JSCONTEXT_NEW, JSCONTEXT_DESTROY } JSContextOp; Enumeration Meaning JSCONTEXT_NEW JS_NewContext successfully created a new JSContext instance. The callback can initialize the instance as required. If the callba...
...SContext instance. The callback can initialize the instance as required. If the callback returns JS_FALSE, the instance will be destroyed and JS_NewContext returns NULL. In this case the callback is not called again. JSCONTEXT_DESTROY One of JS_DestroyContext, JS_DestroyContextNoGC, or JS_DestroyContextMaybeGC was called. The callback may perform its own cleanup and must always return true. In a DEBUG build, if the callback returns false, the JS engine will halt with an assertion. Description JS_SetContextCallback specifies a callback function that is automatically called when JSContexts are created or destroyed. Only one callback function may be specified per JS runtime. This function returns the previous context callback, if any, else NULL. See Also MXR ID Search for JS_S...
JS_ValueToNumber
on this JSContext. v jsval The value to convert. dp jsdouble * Out parameter. On success, *dp receives the converted floating-point value. Description JS_ValueToNumber converts a JavaScript value to a number. It implements the ToNumber operator described in ECMA 262-3 ?9.3. If v is already a number, conversion succeeds. If v is undefined, null, false, or true, conversion succeeds, and the result is NaN, 0, 0, or 1 respectively. If v is a string, conversion proceeds as specified in ECMA 262-3 ?9.3.1. JS_ValueToNumber always succeeds in this case, returning JS_TRUE. If the string is not a numeric string, *dp is set to NaN. Otherwise v is an object. JS_ValueToNumber carries out the following steps to convert it to a number. If at any step an error or e...
...the value is converted to a number as described above and conversion succeeds. Otherwise, the resulting object's toString method, if any, is called. If that produces a primitive value, the value is converted to a number as described above and conversion succeeds. Otherwise conversion fails with a TypeError. On success, JS_ValueToNumber stores the converted value in *dp and returns JS_TRUE. On error or exception, it returns JS_FALSE, and the value left in *dp is undefined. See Also JS_ConvertArguments JS_ConvertValue JS_GetTypeName JS_TypeOfValue JS_ValueToInt32 JS_ValueToECMAInt32 bug 884410 ...
JSAPI reference
S_DropExceptionState These functions translate errors into exceptions and vice versa: JS_ReportPendingException JS_ErrorFromException JS_ThrowReportedError Obsolete since JSAPI 29 Values and types typedef jsval JS::Value JS::Value constructors: JS::NullValue Added in SpiderMonkey 24 JS::UndefinedValue Added in SpiderMonkey 24 JS::BooleanValue Added in SpiderMonkey 24 JS::TrueValue Added in SpiderMonkey 24 JS::FalseValue Added in SpiderMonkey 24 JS::NumberValue Added in SpiderMonkey 24 JS::Int32Value Added in SpiderMonkey 24 JS::DoubleValue Added in SpiderMonkey 24 JS::Float32Value Added in SpiderMonkey 24 JS::StringValue Added in SpiderMonkey 24 JS::ObjectValue Added in SpiderMonkey 24 JS::ObjectOrNullValue Added in SpiderMonkey 24 JS::SymbolValue Added in Sp...
...iderMonkey 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: JS::NullHandleValue Added in SpiderMonkey 24 JS::UndefinedHandleValue Added in SpiderMonkey 24 JS::TrueHandleValue Added in SpiderMonkey 38 JS::FalseHandleValue Added in SpiderMonkey 38 jsval constants: JSVAL_NULL Obsolete since JSAPI 42 JSVAL_VOID Obsolete since JSAPI 42 JSVAL_TRUE Obsolete since JSAPI 42 JSVAL_FALSE Obsolete since JSAPI 42 JSVAL_ZERO Obsolete since JSAPI 42 JSVAL_ONE Obsolete since JSAPI 42 Function and macros for checking the type of a jsval: enum JSType JS_Type...
SpiderMonkey 1.8.5
rs (and integers more than 31 bits long) as pointers to jsdouble; instead, the jsdouble value is directly stored in the jsval. This affects macros like DOUBLE_TO_JSVAL and JSVAL_TO_DOUBLE, which now operate directly on jsdouble rather than jsdouble pointers. Previous SpiderMonkey versions usually represented integer values smaller than 2^31 as jsvals encoding jsint; e.g. so that JSVAL_IS_INT was true. While this was never specified behaviour, it is no longer true; numeric values which are integers are frequently encoded as jsdouble inside the jsval. Embedders must be careful when converting numbers from jsvals into C. Note also that SpiderMonkey can now fit a full 32-bit integer (jsint) inside a jsval without promoting to a jsdouble. JSExtendedClass JSExtendedClass has been removed from the ...
... functions to retrieve the characters in the string failed. Additionally, JS_NewString, JS_GetStringBytes, and JS_GetStringChars were removed, replaced by fallible interfaces like JS_GetStringCharsZAndLength and JS_EncodeStringToBuffer (not an exhaustive list). Numbers SpiderMonkey 1.8.5 now stores integers up to 32-bits in the jsval. This means that the INT_FITS_IN_JSVAL macro is always returns true (be careful to only use this macro with jsints, not 64-bit integers). The jsval now also stores jsdoubles directly, rather than storing them on the heap. The JSVAL_TO_DOUBLE and DOUBLE_TO_JSVAL macros have been updated to work directly on jsdoubles rather than their pointers, and the JS_NewDoubleValue and JS_NewDouble interfaces have been removed. JavaScript shell changes There are many new built...
SpiderMonkey 1.8.7
rs (and integers more than 31 bits long) as pointers to jsdouble; instead, the jsdouble value is directly stored in the jsval. This affects macros like DOUBLE_TO_JSVAL and JSVAL_TO_DOUBLE, which now operate directly on jsdouble rather than jsdouble pointers. Previous SpiderMonkey versions usually represented integer values smaller than 2^31 as jsvals encoding jsint; e.g. so that JSVAL_IS_INT was true. While this was never specified behaviour, it is no longer true; numeric values which are integers are frequently encoded as jsdouble inside the jsval. Embedders must be careful when converting numbers from jsvals into C. Note also that SpiderMonkey can now fit a full 32-bit integer (jsint) inside a jsval without promoting to a jsdouble. JSExtendedClass JSExtendedClass has been removed from the ...
... functions to retrieve the characters in the string failed. Additionally, JS_NewString, JS_GetStringBytes, and JS_GetStringChars were removed, replaced by fallible interfaces like JS_GetStringCharsZAndLength and JS_EncodeStringToBuffer (not an exhaustive list). Numbers SpiderMonkey 1.8.5 now stores integers up to 32-bits in the jsval. This means that the INT_FITS_IN_JSVAL macro is always returns true (be careful to only use this macro with jsints, not 64-bit integers). The jsval now also stores jsdoubles directly, rather than storing them on the heap. The JSVAL_TO_DOUBLE and DOUBLE_TO_JSVAL macros have been updated to work directly on jsdoubles rather than their pointers, and the JS_NewDoubleValue and JS_NewDouble interfaces have been removed. JavaScript shell changes There are many new buil...
SpiderMonkey 38
g 645416) JS::IdentifyStandardConstructor (bug 976148) JS::IsCallable (bug 1065811) JS::IsConstructor (bug 1065811) JS::MutableHandleSymbol (bug 645416) JS::OrdinaryToPrimitive (bug 1103152) JS::PropertySpecNameEqualsId (bug 1082672) JS::PropertySpecNameIsSymbol (bug 1082672) JS::PropertySpecNameToPermanentId (bug 1082672) JS::ProtoKeyToId (bug 987669) JS::RootedSymbol (bug 645416) JS::TrueHandleValue (bug 959787) JSConstIntegerSpec (bug 1066020) JSID_IS_SYMBOL (bug 645416) JSID_TO_SYMBOL (bug 645416) JSPROP_DEFINE_LATE (bug 825199) JSPROP_IGNORE_ENUMERATE (bug 1037770) JSPROP_IGNORE_PERMANENT (bug 1037770) JSPROP_IGNORE_READONLY (bug 1037770) JSPROP_IGNORE_VALUE (bug 1037770) JSPROP_PROPOP_ACCESSORS (bug 1088002) JSPROP_REDEFINE_NONCONFIGURABLE (bug 1101123) JS_AddFinali...
...w use char16_t directly. Embedder code should use char16_t, too. (See bug 1063962.) JS_PreventExtensions now indicates its success or failure in two ways: via return value (as with most JSAPI methods), and via outparam (indicating whether the attempt took effect or not, independent of JSAPI failure). This change better aligns with ECMAScript's [[PreventExtensions]] hook, which generally returns true or false to indicate whether subsequent attempts to add a new property will fail, yet also itself may throw in some cases. JavaScript shell changes Detail added/removed methods here... Known Issues Detail any known issues here... Future Direction ...insert details on future plans... SpiderMonkey embedders should be aware that Mozilla has no plans to keep the JSAPI, nor the JSDBGAPI, sta...
Retrieving part of the bookmarks tree
it, and then you can iterate the children. As long as the container is open, it will listen for notifications from the bookmarks system to keep itself up-to-date. When you're done, be sure to close the container to free up the resources. Otherwise, it will continue to get observer notifications and update itself, slowing down the whole browser. ...
...rootNode.containerOpen = false; ...
extIPreferenceBranch
name of the branch root. all readonly attribute nsIVariant Array of extIPreference listing all preferences in this branch. events readonly attribute extIEvents The events object for the preferences supports: "change" Methods has() Check to see if a preference exists. boolean has(in AString aName) Parameters aName The name of preference Return value true if the preference exists, false if not get() Gets an object representing a preference extIPreference get(in AString aName) Parameters aName The name of preference Return value a preference object, or null if the preference does not exist getValue() Gets the value of a preference. Returns a default value if the preference does not exist. nsIVariant getValue(in AString aName, in nsIV...
...ect. Return value The value of the preference or the given default value if preference does not exists. The use of a variant as the return value means that to JavaScript code the value will appear as a value of the same type as is used in the preferences file and no coercion will occur. A quoted string in the preference file will always appear as a string, even if the value of the string is "true" or "false". An integer preference appears as a JavaScript Number, and a boolean appears as a JavaScript Boolean. There are no other types supported by the preference subsystem. setValue() Sets the value of a preference with the given name. void setValue(in AString aName, in nsIVariant aValue) Parameters aName The name of a preference aValue The value of a preference Return value ...
How to build an XPCOM component in JavaScript
mplementing nsIFactory). If not // provided, the default factory is used, which returns // |(new MyComponent()).QueryInterface(iid)| in its createInstance(). _xpcom_factory: { ... }, // [optional] an array of categories to register this component in. _xpcom_categories: [{ // Each object in the array specifies the parameters to pass to // nsICategoryManager.addCategoryEntry(). ...
...parameters to pass to // nsICategoryManager.addCategoryEntry(). 'true' is passed for both // aPersist and aReplace params. 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. When set to true, and only if 'value' is not // specified, the concatenation of the string "service," and the object's contractID // is passed as aValue parameter of addCategoryEntry. service: true }], // QueryInterface implementation, e.g. using the generateQI helper (remove argument if skipped steps above) QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIHelloWorld]), // Op...
Receiving startup notifications
artup Sent just before the first application window is displayed. Registering with the Category Manager To register with the Category Manager, simply call its nsICategoryManager.AddCategoryEntry() method: categoryManager->AddCategoryEntry(APPSTARTUP_CATEGORY, "mycomponentname", "contract-id", PR_TRUE, PR_TRUE, getter_Copies(previous)); This causes your component to be instantiated using nsIComponentManager.createInstance(). If you want your component to be started as a service, prepend "service," to the contract ID: categoryManager->AddCategoryEntry(APPSTARTUP_CATEGORY, "mycomponentname", "s...
...(previous)); This causes your component to be instantiated using nsIComponentManager.createInstance(). If you want your component to be started as a service, prepend "service," to the contract ID: categoryManager->AddCategoryEntry(APPSTARTUP_CATEGORY, "mycomponentname", "service,contract-id", PR_TRUE, PR_TRUE, getter_Copies(previous)); With "service," specified, the component is instantiated using nsIComponentManager.getService(). In either case, there's no need to additionally register for the startup notifications. Simply registering with the Category Manager is enough. What happens next Once you've registered with the Category Manager, at Mozilla startup t...
XPCOM Stream Guide
Mozilla › Tech › XPCOM › Guide › Streams
ny channel, and from there an input stream. The IO service is available through the Services.jsm module as the .io property. Stream Listeners A stream listener is an object you build to let you know when there is data in a stream ready for you to consume. Most streams are asynchronous: they make no assumptions that all the data a resource provides is available immediately. (This is particularly true of streams that reach out over a network connection, like HTTP and FTP channels.) Stream listeners implement three methods. From the nsIStreamListener interface, the .onDataAvailable(request, context, inputStream, offset, count) method gives you the input stream and the number of bytes available. The stream listener must read exactly count bytes before exiting. From the nsIRequestObserver interf...
...r. Mozilla provides an "input stream pump" component to feed data from the stream into the reader. There are two parts: initializing the pump, and telling it to asynchronously read data into the stream listener: var pump = Components.classes["@mozilla.org/network/input-stream-pump;1"] .createInstance(Components.interfaces.nsIInputStreamPump); pump.init(stream, -1, -1, 0, 0, true); pump.asyncRead(listener, context); nsIPipe Code Examples File input and output For file input, see Code Snippets: Reading from a file. For file output, see Code Snippets: Writing to a file. ZIP input and output For getting an input stream from a ZIP archive, see the nsIZipReader interface: // file is an nsIFile object mapping to a ZIP archive var zipReader = Components.classes["@moz...
Introduction to XPCOM for the DOM
as follows: nsCOMPtr<nsIFoo> fooptr; The rest of the use of nsCOMPtr's is described in the next Section. For more information about nsCOMPtr's, please read the User's Guide. QueryInterface() Consider again the class nsFoo that implements two interfaces, nsIFoo and nsIFoo2: class nsFoo : public nsIFoo, public nsIFoo2 Let's assume an instance of nsFoo was somehow created (this assertion is true most of the time). You would like to manipulate that object with a method defined on the nsIFoo interface. The goal is to retrieve a pointer to the nsIFoo interface. To do so, there are two main techniques, and the context should tell you what to use. The first technique is to use a "Getter", the second is to use a static cast on the "this" pointer. A getter is a function defined in global scope...
...e nsHTMLDocument::Fabian() and nsHTMLDocument::GetNeat(). So let's just code them. NS_IMETHODIMP nsHTMLDocument::Fabian(void) { printf("Hello from the nsIDOMFabian interface\n"); // Whatever you want... 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. The functions are very simple, but it is only a proof-of-concept. A second possibility is to use the "Interface forwarding macro". This macro is also auto-generated by the XPIDL compiler. Below is the theory behind interface forwarding, followed by an example of nsIDOMFabian. Theory ...
Components.utils.isXrayWrapper
ple, privileged code using an Xray to a DOM object sees only the original, native version of the DOM object. Any expando properties are not visible, and if any native properties have been redefined, this has no effect. ...
...re not visible, and if any native properties have been redefined, this has no effect. Use this function to determine whether a given object is an Xray or not. Syntax boolean Components.utils.isXrayWrapper(obj); Parameters obj The object to check. ...
Components.utils.unwaiveXrays
an expando to its global window: // page script foo = "I'm an expando"; By default, chrome code won't see foo, because it sees the content window with Xray vision, but the chrome code can waive Xray protection. ...
...aived); // false foo = waived.foo; // "I'm an expando" // waiving is transitive isXray = Components.utils.isXrayWrapper(waived.document); // false // use unwaiveXrays to undo the waiver var unwaived = Components.utils.unwaiveXrays(waived); isXray = Components.utils.isXrayWrapper(unwaived); // true foo = unwaived.foo; // undefined // unwaiving is transitive isXray = Components.utils.isXrayWrapper(unwaived.document); // true ...
Observer Notifications
ification. Note: This notification is specific to Firefox and SeaMonkey 2.0 applications Application shutdown These are the topics that you can observe on shutdown, in order of appearance. Topic Description quit-application-requested Something has requested that the application be shutdown. You can cancel the shutdown from here by setting aSubject.data to true (aSubject is the first parameter to your observer, the data value is an nsISupportsPRBool). quit-application-granted All observers have agreed to the shutdown. quit-application The application is about to quit. This can be in response to a normal shutdown, or a restart. Note: The data value for this notification is either 'shutdown' or 'restart'. profile-c...
...cific history and other information have been purged. The data value is a string form of the domain. browser-lastwindow-close-requested Sent when the browser wishes to close the last open browser window. When this is sent, it is possible that other windows may still be open, such as the download manager or preferences. The data value is an nsISupportsPRBool. Recipients may set this to true to abort the close. browser-lastwindow-close-granted Sent when all interested parties have responded to the browser-lastwindow-close-requested notification and none of them requested that the close be aborted. After this is sent and handled, the browser window will close. browser-delayed-startup-finished Sent when the browser window and all its components have been loaded ...
IAccessibleTable2
ssed, [out] value is null. S_FALSE if there is nothing to return, [out] value is null. S_OK. isColumnSelected() Returns a boolean value indicating whether the specified column is completely selected. [propget] HRESULT isColumnSelected( [in] long column, [out] boolean isSelected ); Parameters column 0 based index of the column for which to determine whether it is selected. isSelected Returns true if the specified column is selected completely and false otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value indicating whether the specified row is completely selected. [propget] HRESULT isRowSelected( [in] long row, [out] boolean isSelected ); Parameters row 0 based index of the row for which to determine whether it...
...ted completely and false otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. isRowSelected() Returns a boolean value indicating whether the specified row is completely selected. [propget] HRESULT isRowSelected( [in] long row, [out] boolean isSelected ); Parameters row 0 based index of the row for which to determine whether it is selected. isSelected Returns true if the specified row is selected completely and false otherwise. Return value E_INVALIDARG if bad [in] passed, [out] value is false. S_OK. modelChange() Returns the type and extents describing how a table changed. Provided for use by the IA2_EVENT_TABLE_MODEL_CHANGED event handler. This data is only guaranteed to be valid while the thread notifying the event continues. Once the handler has retur...
amIInstallTrigger
ons to install. This should be a JS object, each property is the name of an add-on to be installed. The value of the property should either be a string URL, or an object with the following properties: URL for the add-on's URL IconURL for an icon for the add-on Hash for a hash of the add-on. aCallback Optional A callback to call as each installation succeeds or fails. Return value true if the installations were successfully started. installChrome Starts installing a new add-on. This method is deprecated, please use install() in the future. boolean installChrome( in PRUint32 aType, in AString aUrl, in AString aSkin ); Parameters aType Unused, retained for backwards compatibility. aUrl The URL of the add-on. aSkin Unused, retained for backwards compatibility. ...
...ations were successfully started. installChrome Starts installing a new add-on. This method is deprecated, please use install() in the future. boolean installChrome( in PRUint32 aType, in AString aUrl, in AString aSkin ); Parameters aType Unused, retained for backwards compatibility. aUrl The URL of the add-on. aSkin Unused, retained for backwards compatibility. Return value true if the installation was successfully started. startSoftwareUpdate Starts installing a new add-on. boolean startSoftwareUpdate( in AString aUrl, in PRInt32 aFlags Optional ); Parameters aUrl The URL of the add-on. aFlags Optional Unused, retained for backwards compatibility. Return value true if the installation was successfully started. updateEnabled Tests if installation is e...
amIWebInstallListener
bInstallBlocked( in nsIDOMWindow aWindow, in nsIURI aUri, [array, size_is(aCount)] in nsIVariant aInstalls, in PRUint32 aCount Optional ); Parameters aWindow The window that triggered the installs. aUri The URI of the site that triggered the installs. aInstalls The AddonInstalls that were blocked. aCount Optional The number of AddonInstalls. Return value true if the caller should start the installs. onWebInstallDisabled() Called when installation by websites is currently disabled. void onWebInstallDisabled( in nsIDOMWindow aWindow, in nsIURI aUri, [array, size_is(aCount)] in nsIVariant aInstalls, in PRUint32 aCount Optional ); Parameters aWindow The window that triggered the installs. aUri The URI of the site that triggered t...
... ...
jsdIStackFrame
ogether. Last version set on this context. Scripts typically select this with the "language" attribute. See the VERSION_* consts on jsdIDebuggerService. Unique tag among all valid jsdIContext objects, useful as a hash key. Private data for this context, if it is an nsISupports, |null| otherwise. Retrieve the underlying context wrapped by this jsdIContext. Top of the scope chain for this context. |true| if this context should be allowed to run scripts, |false| otherwise. This attribute is only valid for contexts which implement nsIScriptContext. Setting or getting this attribute on any other context will throw a NS_ERROR_NO_INTERFACE exception. Stack frame objects. These are only valid inside the jsdIExecutionHook which gave it to you. After you return from that handler the bottom frame, and an...
...ned long line, out jsdIValue result); Attributes Attribute Type Description callee jsdIValue Function object running in this stack frame. Read only. callingFrame jsdIStackFrame Link to the caller's stack frame. Read only. executionContext jsdIContext Executon context. Read only. functionName AUTF8String Function name executing in this stack frame. Read only. isConstructing boolean True if stack frame is constructing a new object. Read only. isDebugger boolean True if stack frame represents a frame created as a result of a debugger evaluation. Read only. isNative boolean True if stack frame represents a native frame. Read only. Obsolete since Gecko 2.0 JSDContext JSDContext Internal use only. Read only. Native code only! JSDStackFrameInfo JSDStackFrameInfo Internal use o...
mozIAsyncFavicons
the favicon URI, aDataLen will be 0, aData will be an empty array, and aMimeType will be an empty string. setAndFetchFaviconForPage() Declares that a given page uses a favicon with the given URI and attempts to fetch and save the icon data by loading the favicon URI through a asynchronous network request. If the icon data already exists, we will not try to reload the icon unless aForceReload is true. Similarly, if the icon is in the failed favicon cache we will not do anything unless aForceReload is true, in which case we'll try to reload the favicon. This function will only save favicons for "good" URIs, as defined by what gets added to history or is a bookmark. For "bad" URIs, this function will succeed but do nothing. This function will also ignore the error page favicon URI (see FAVICON_...
... boolean aForceReload, in unsigned long afaviconLoadType, in nsIFaviconDataCallback aCallback Optional ); Parameters aPageURI URI of the page whose favicon is being set. aFaviconURI URI of the favicon to associate with the page. aForceReload If false, we try to reload the favicon only if we do not have it or it has expired from the cache. Setting to true causes us to reload the favicon even if we have a usable copy. aFaviconLoadType Set to nsIFaviconService.FAVICON_LOAD_PRIVATE if the favicon is loaded from a private browsing window. Set to nsIFaviconService.FAVICON_LOAD_NON_PRIVATE otherwise aCallback Optional Once we're done setting and/or fetching the favicon, we invoke this callback. replaceFaviconData() Sets the ...
mozIStorageFunction
nt our function. ...
...r<nsIWritableVariant> result = do_CreateInstance("@mozilla.org/variant;1"); NS_ENSURE_TRUE(result, NS_ERROR_OUT_OF_MEMORY); rv = result->SetAsInt64(value * value); NS_ENSURE_SUCCESS(rv, rv); NS_ADDREF(*_result = result); return NS_OK; } }; // Now, register our function with the database connection. nsCOMPtr<mozIStorageFunction> func = new squareFunction(); NS_ENSURE_TRUE(func, NS_ERROR_OUT_OF_MEMORY); nsresult rv = dbConn->CreateFunction( NS_LITERAL_CSTRING("square"), 1, func ); NS_ENSURE_SUCCESS(rv, rv); // Run some query that uses the function. nsCOMPtr<mozIStorageStatement> stmt; rv = dbConn->CreateStatement(NS_LITERAL_CSTRING( "SELECT square(value) FROM some_table"), getter_AddRefs(stmt) ); NS_ENSURE_SUCCESS(rv, rv); PRBool hasMore; while (NS_SUCCE...
mozIStorageVacuumParticipant
e WAL mode, but this will only work reliably if the participant properly resets statements. If the attempt to restore the journal node fails, it will remain TRUNCATE. Methods onBeginVacuum() Called when a vacuum operation begins. Once you receive this notification, you should avoid using the database until onEndVacuum() is called. boolean onBeginVacuum(); Parameters None. ...
...nVacuum(); Parameters None. 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. onEndVacuum() Called when a vacuum operation ends. void onEndVacuum( in boolean aSucceeded ); Parameters aSucceeded true if the vacuum operation was successful, or false if it wasn't successful. ...
nsIAccessibleDocument
ibute Type Description caretAccessible nsIAccessible Read only. Obsolete since Gecko 1.9 docType AString The doc type of the document, as specified in the document. Read only. DOMDocument nsIDOMDocument The nsIDOMDocument interface associated with this document. Read only. Note: Renamed from document in Gecko 2.0 isEditable boolean True if the document is live in an editor. False if the document is being displayed but not edited. If a <div> is contentEditable, then it has its own document, with isEditable == true. Read only. Obsolete since Gecko 1.9 mimeType AString The mime type of the document. Read only. title AString The title of the document, as specified in the document. Read only. UR...
...leInParentChain() Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Returns the first accessible parent of a DOM node. Guaranteed not to return null if the DOM node is in a document. nsIAccessible getAccessibleInParentChain( in nsIDOMNode aDOMNode, in boolean aCanCreate ); Parameters aDOMNode The DOM node we need an accessible for. aCanCreate If true, this method can create a new accessible. Otherwise, it will return the first cached accessible in the parent chain. Return value The first nsIAccessible found by crawling up the DOM node to the document root. Native code only!getCachedAccessNode Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1)This feature is obsolete. Although it may still work in some browsers, its ...
nsIAccessibleEvent
his can be used to get the DOM window, the DOM document and the window handler, among other things. Read only. DOMNode nsIDOMNode The nsIDOMNode associated with the event. May return null if accessible for event has been shut down. Read only. eventType unsigned long The type of event, based on the enumerated event values defined in this interface. Read only. isFromUserInput boolean Returns true if the event was caused by explicit user input, as opposed to purely originating from a timer or mouse movement. Constants Constant Gecko version Description 1.7 - 1.8.1 1.9 - 1.9.2 2.0 EVENT_SHOW 0x8002 0x0001 An object has been created. EVENT_HIDE 0x8003 0x0002 An object has been destroyed. EVENT_REORDER 0x8004 0x005C 0x0003 An object's children have changed. EVENT_ACTIVE_D...
...INTERNAL_LOAD 0x005B Used internally in Gecko. Example To listen to in-process accessibility invents, make your object an nsIObserver, and listen for accessible-event by using code something like this: nsCOMPtr<nsIObserverService> observerService = do_GetService("@mozilla.org/observer-service;1", &rv); if (NS_SUCCEEDED(rv)) { rv = observerService->AddObserver(this, "accessible-event", PR_TRUE); } ...
nsIAccessibleHyperLink
link. Read only. Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. valid boolean Determines whether the hyperlink is valid, for example points to a valid URL. Read only. Note: Currently only used with ARIA links, and the author has to specify that the link is invalid via the aria-invalid='true' attribute. In all other cases, true is returned. Exceptions thrown NS_ERROR_FAILURE Indicates that the accessible is unattached from the accessible tree. Methods Returns a reference to the object at the given index. Note: ARIA hyperlinks do not have an anchor accessible to point to, since clicks are processed via JavaScript. Note: In the case of an image ma...
...rty does not work on ARIA links. nsIURI getURI( in long index ); Parameters index The 0-based index of the URI to be returned. Return value The nsIURI object containing the specifications for the URI. isSelected() Obsolete since Gecko 1.9 (Firefox 3) Note: Has been replaced by the selected attribute. boolean isSelected(); Parameters None. Return value true if the element currently has the focus. isValid() Obsolete since Gecko 1.9 (Firefox 3) Note: Has been replaced by the valid attribute. boolean isValid(); Parameters None. Return value true if the hyperlink is valid. Remarks Anchors, image maps, xul:labels with class="text-link" implement this interface. See also nsIAccessible nsIURI ...
nsIAccessibleSelectable
ected. void clearSelection(); Parameters None. GetSelectedChildren() Returns an nsIArray of the selected nsIAccessible children. nsIArray GetSelectedChildren(); Parameters None. Return value An nsIArray. isChildSelected() Determines if the current child of this object is selected. boolean isChildSelected( in long index ); Parameters index The zero-based accessible child index. Return value True if the child is selected, false if not. refSelection() Returns a reference to the accessible object representing the specified selected child of the object. nsIAccessible refSelection( in long index ); Parameters index Zero-based selected accessible child index. Return value The selected accessible child. removeChildFromSelection() Removes the specified child of the object from the object's ...
...ected, then it does nothing. void removeChildFromSelection( in long index ); Parameters index Zero-based accessible child index. Exceptions thrown NS_ERROR_FAILURE If the specified object is not selectable. selectAllSelection() Select all children. boolean selectAllSelection(); Parameters None. Return value If the object does not accept multiple selection, return false. Otherwise, returns true. ...
nsIAccessibleStateChangeEvent
...
... ...
nsIAccessibleTable
ize)] out long rowsArray ); Parameters rowsArraySize Length of array. rowsArray Array of indices of selected rows. isCellSelected() Return a boolean value indicating whether the specified cell is selected. boolean isCellSelected( in long rowIndex, in long columnIndex ); Parameters rowIndex The row index of the cell. columnIndex The column index of the cell. Return value true if the cell is selected, false if the cell is not selected. isColumnSelected() Return a boolean value indicating whether the specified column is selected, that is all cells within the column are selected. boolean isColumnSelected( in long columnIndex ); Parameters columnIndex The column index. Return value true if the column is selected, false if the column is not selected. isProba...
...cted, that is all cells within the column are selected. boolean isColumnSelected( in long columnIndex ); Parameters columnIndex The column index. Return value true if the column is selected, false if the column is not selected. isProbablyForLayout() Use heuristics to determine if table is most likely used for layout. boolean isProbablyForLayout(); Parameters None. Return value true if the table is probably for layout, false if the table is probably not for layout. isRowSelected() Return a boolean value indicating whether the specified row is selected, that is all cells within the row are selected. boolean isRowSelected( in long rowIndex ); Parameters rowIndex The row index. Return value true if the row is selected, false if the row is not selected. selectColu...
nsIAppShell
t the handle event loop. void exit(); Parameters None. favorPerformanceHint() Give hint to native event queue notification mechanism. If the native platform needs to tradeoff performance vs. native event starvation this hint tells the native dispatch code which to favor. The default is to prevent native event starvation. Calls to this function may be nested. 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. starv...
...is real or a null placeholder (Macintosh). aEvent Void pointer to native event structure. ListenToEventQueue() Obsolete since Gecko 1.9 (Firefox 3) An event queue has been created or destroyed. Hook or unhook it from your system, as necessary. void ListenToEventQueue( in nsIEventQueue aQueue, in PRBool aListen ); Parameters aQueue The queue in question. aListen PR_TRUE for a new queue wanting hooking up. PR_FALSE for a queue wanting to be unhooked. resumeNative() Resumes the use of additional platform-specific methods to run() Gecko events on the main application thread. Calls to suspendNative() and resumeNative may be nested. On some platforms this will be a no-op. void resumeNative(); Parameters None. run() Enter an event loop. Do not leave until exit() is ...
nsIAppStartup
This can be used, for example, when doing performance testing of the startup process to discount numbers for tests that were interrupted by a user prompt. nativeAppSupport nsINativeAppSupport Getter for "native application support." Read only. Obsolete since Gecko 1.9.1 Constants The following flags may be pa...
... Creates the initial state of the application by launching tasks specfied by "general.startup.*" prefs. Note: SIZE_TO_CONTENT may be used for width or height. boolean createStartupState( in long aWindowWidth, in long aWindowHeight ); Parameters aWindowWidth The width to make the initial window(s) opened. aWindowHeight The height to make the initial window(s) opened. Return value TRUE if a window was opened. destroyHiddenWindow() Destroys the hidden window. This will have no effect if the hidden window has not yet been created. void destroyHiddenWindow(); Parameters None. doProfileStartup() Obsolete since Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Starts up the profile manager with the given arguments. void doProfileStartup( ...
nsIApplicationCacheChannel
nterface is implemented by communication channels that support application caches. ...
...ion chooseApplicationCache boolean When true, the channel will choose an application cache if one was not explicitly provided and none is available from the notification callbacks. The default value is false. This attribute will not be transferred through a redirect. Exceptions thrown NS_ERROR_ALREADY_OPENED If set after calling AsyncOpen() on the channel. inheritApplicationCache boolean true if the channel will ask its notification callbacks for an application cache if one is not explicitly provided. The default value is true. Exceptions thrown NS_ERROR_ALREADY_OPENED If set after calling AsyncOpen() on the channel. loadedFromApplicationCache PRBool true if the resource was loaded from the application cache, otherwise false. This value may be false even if the resource is assign...
nsIAsyncStreamCopier
ean aSourceBuffered, in boolean aSinkBuffered, in unsigned long aChunkSize, in boolean aCloseSource, in boolean aCloseSink ); Parameters aSource Contains the data to be copied. aSink Specifies the destination for the data. aTarget Specifies the thread on which the copy will occur. A null value is permitted and causes the copy to occur on an unspecified background thread. aSourceBuffered true if aSource implements nsIInputStream.readSegments(). aSinkBuffered true if aSink implements nsIInputStream.writeSegments() . aChunkSize Specifies how many bytes to read and write at a time. This controls the granularity of the copy operation. This value should match the segment size of any buffered streams involved in the operation. aCloseSource true if aSource should be closed after copying. aC...
...e implements nsIInputStream.readSegments(). aSinkBuffered true if aSink implements nsIInputStream.writeSegments() . aChunkSize Specifies how many bytes to read and write at a time. This controls the granularity of the copy operation. This value should match the segment size of any buffered streams involved in the operation. aCloseSource true if aSource should be closed after copying. aCloseSink true if aSink should be closed after copying. See also nsIInputStream nsIOutputStream ...
nsICacheSession
oolean noWait); void evictEntries(); PRBool isStorageEnabled(); nsICacheEntryDescriptor openCacheEntry(in ACString key, in nsCacheAccessMode accessRequested, in boolean blockingMode); void doomEntry(in ACString key, in nsICacheListener listener); Attributes Attribute Type Description doomEntriesIfExpired PRBool Expired entries will be doomed or evicted if this attribute is set to true. 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). This attribute defaults to true. Methods asyncOpenCacheEntry() This method gives an asynchronous cache access. Does not block the calling thread. Instead, the listener will be notified when the descriptor is available. void asyncOpenCacheEntry( ...
...out one descriptor with WRITE access to a given cache entry at a time. Until the client calls MarkValid on its descriptor, other attempts to open the same cache entry will block. nsICacheEntryDescriptor openCacheEntry( in ACString key, in nsCacheAccessMode accessRequested, in boolean blockingMode ); Parameters key The key for cache entry. accessRequested The requested access. blockingMode True or False value to turn blocking mode for calling the thread to ON/OFF respectively. Return value Returns a unique descriptor each time it is called. See also nsICache nsICacheEntryDescriptor nsICacheListener nsICacheService ...
nsICacheVisitor
iceInfo deviceInfo); boolean visitEntry(in string deviceID, in nsICacheEntryInfo entryInfo); Methods visitDevice() This method is called to provide information about a cache device. boolean visitDevice( in string deviceID, in nsICacheDeviceInfo deviceInfo ); Parameters deviceID Specifies the device being visited. deviceInfo Specifies information about this device. ...
...turns true to start visiting all entries for this device, otherwise returns false to advance to the next device. visitEntry() This method is called to provide information about a cache entry. boolean visitEntry( in string deviceID, in nsICacheEntryInfo entryInfo ); Parameters deviceID Specifies the device being visited. entryInfo Specifies information about this entry. 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. See also nsICache nsICacheDeviceInfo nsICacheEntryInfo ...
nsICachingChannel
ng from the net if the data in the cache has been evicted. An error of NS_ERROR_DOCUMENT_NOT_CACHED will be sent to the listener's onStopRequest in this case. This flag is set automatically when the application is offline. LOAD_ONLY_IF_MODIFIED 1 << 31 This load flag controls what happens when a document would be loaded from the cache to satisfy a call to AsyncOpen. If this attribute is set to true, then the document will not be loaded from the cache. A stream listener can check isFromCache() to determine if the AsyncOpen will actually result in data being streamed. If this flag has been set, and the request can be satisfied via the cache, then the OnDataAvailable events will be skipped. The listener will only see OnStartRequest followed by OnStopRequest. Methods isFromCache() ...
...e cache, then the OnDataAvailable events will be skipped. The listener will only see OnStartRequest followed by OnStopRequest. Methods isFromCache() Obsolete since Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) This method finds out whether or not this channel's data is being loaded from the cache. boolean isFromCache(); Parameters None. Return value Returns true if this channel's data is being loaded from the cache, otherwise returns false. This value is undefined before the channel fires its OnStartRequest notification and after the channel fires its OnStopRequest notification. See also nsICache ...
nsICharsetResolver
e ); Parameters charset The detected charset. closure The closure returned by requestCharset(). requestCharset() Called to resolve the charset that should be used for parsing the document being loaded from aChannel. If the charset cannot be resolved, but the implementation of nsICharsetResolver wants to be notified of the final resolved charset when one is available, it can set aWantCharset to true. If this is done, the caller of requestCharset is responsible for calling notifyResolvedCharset() and passing it the final resolved charset and the closure that requestCharset set. ACString requestCharset( in nsIWebNavigation aWebNavigation, in nsIChannel aChannel, out boolean aWantCharset, out nsISupports aClosure ); Parameters aWebNavigation The nsIWebNavigation the document is being ...
... passing it the final resolved charset and the closure that requestCharset set. ACString requestCharset( in nsIWebNavigation aWebNavigation, in nsIChannel aChannel, out boolean aWantCharset, out nsISupports aClosure ); Parameters aWebNavigation The nsIWebNavigation the document is being loaded in. May be null. aChannel The channel the document is coming in from. aWantCharset Gets set to true if notifyResolvedCharset() should be called with the given aClosure object. aClosure A resulting object which should be passed to notifyResolvedCharset() if aWantCharset is set to true. Return value The resolved charset, or an empty string if no charset could be determined. ...
nsIClipboard
n the clipboard matching any of the flavors in the given list. boolean hasDataMatchingFlavors( [array, size_is(aLength)] in string aFlavorList, in unsigned long aLength, in long aWhichClipboard ); Parameters aFlavorList An array of ASCII strings. aLength The length of the aFlavorList. aWhichClipboard Specifies the clipboard to which this operation applies. Return value Returns true, if data is present and it matches the specified flavor. Otherwise it returns false. setData() This method sets the data from a transferable on the native clipboard. void setData( in nsITransferable aTransferable, in nsIClipboardOwner anOwner, in long aWhichClipboard ); Parameters aTransferable The transferable containing the data to put on the clipboard. anOwner The owner of the...
...le containing the data to put on the clipboard. anOwner The owner of the transferable. aWhichClipboard Specifies the clipboard to which this operation applies. supportsSelectionClipboard() This method allows clients to determine if the implementation supports the concept of a separate clipboard for selection. boolean supportsSelectionClipboard(); Parameters None. Return value Returns true if kSelectionClipboard is available. Otherwise it returns false. supportsFindClipboard() This method allows clients to determine if the implementation supports the concept of a separate clipboard for find search strings. boolean supportsFindClipboard(); Parameters None. Return value Returns true if the separate clipboard for find search strings is supported. Otherwise it returns false. S...
nsIController
uld execute the command with the specified name. void doCommand( in string command ); Parameters command The name of the command to execute. isCommandEnabled() Implement this method to indicate whether or not the specified command is enabled. boolean isCommandEnabled( in string command ); Parameters command The name of the command whose availability is to be checked. Return value Return true if the specified command is currently available to be used; otherwise, it should return false. onEvent() Implement this method to process the event with the specified name. void onEvent( in string eventName ); Parameters eventName The name of the event to process. supportsCommand() Implement this method to report whether or not the command with the specified name is supported. boolean suppor...
... the event with the specified name. void onEvent( in string eventName ); Parameters eventName The name of the event to process. supportsCommand() Implement this method to report whether or not the command with the specified name is supported. boolean supportsCommand( in string command ); Parameters command The name of the command to determine whether or not it is supported. Return value true if the specified command is supported; otherwise false. See also nsICommandController nsIControllers XUL Tutorial/Commands ...
nsICryptoHash
4 Secure Hash Algorithm 256 SHA384 5 Secure Hash Algorithm 384 SHA512 6 Secure Hash Algorithm 512 Methods finish() Completes the hash object and produces the actual hash data. Note: This method may be called any time after " .. manch("init") .. " is called. This call resets the object. ACString finish( in PRBool aASCII ); Parameters aASCII If true then the returned value is a base-64 encoded string. If false, then the returned value is binary data. Return value This method returns a hash of the data that was read by this object. This can be either binary data or a base-64 encoded string. Exceptions thrown NS_ERROR_NOT_INITIALIZED Indicates that init() or initWithString() has not been called. init() Initialize the hashing object.
...ms are specified as constants on the interface. Also note that when you call the updateFromStream() method, the second parameter is the number of bytes to read. Passing PR_UINT32_MAX here indicates that you want the entire file read. Finally, note that calling the finish() method produces the hash value. The single parameter to this method is false in this example to return binary data. Passing true returns the hash as a base 64 encoded string. In this example we take the binary data and produce a hexadecimal string of the result, as is commonly output by hashing programs. Computing the Hash of a String Another common operation is computing the hash value of a string. Since hash functions are computed over bytes, you will first need to convert the string to a series of bytes using nsIScrip...
nsIDBChangeListener
ged. void onJunkScoreChanged(in nsIDBChangeListener aInstigator); Parameters aInstigator The caller who changed the junk score. This can be used to filter out events that you yourself started. aInstigator may also be null. onHdrPropertyChanged() Called in the general case where any field may have changed. OnHdrPropertyChanged is called twice per change. On the first call, aPreChange is true, and aStatus is undefined. OnHdrPropertyChanged saves any required status in aStatus (such as a filter match). The calling function stores the value of aStatus, changes the header aHdrToChange, then calls OnHdrPropertyChanged again with aPreChange false. On this second call, the stored value of aStatus is provided, so that any changes may be noted. void onHdrPropertyChanged(in nsIMsgDBHdr aHdrT...
...econd call, the stored value of aStatus is provided, so that any changes may be noted. void onHdrPropertyChanged(in nsIMsgDBHdr aHdrToChange, in PRBool aPreChange, inout PRUint32 aStatus, in nsIDBChangeListener aInstigator); Parameters aHdrToChange The nsIMsgDBHdr of the message that is changing. aPreChange True on first call before change, false on second call after change. aStatus The storage location provided by calling routine for status. aInstigator The caller who added the header. This can be used to filter out events that you yourself started. aInstigator may also be null. onEvent() Generic notification for extensibility. Common events should be documented here so we have a hope of keeping ...
nsIEditor
ndOfLine 6 Attributes Attribute Type Description contentsMIMEType string The MIME type of the document. document Document Read only. The DOM Document this editor is associated with. documentCharacterSet ACString Sets the current 'Save' document character set. documentIsEmpty boolean Read only. Returns true if the document has no *meaningful* content. documentModified boolean Read only. Returns true if the document is modifed and needs saving. flags unsigned long Edit flags for this editor. May be set at any time. isDocumentEditable PRBool Read only. Returns true if we have a document that is not marked read-only. isSelectionEditable boolea...
...This helps to support cases where only parts of the document are editable, by letting you see if the current selection is in an editable section. rootElement nsIDOMElement Read only. ...
nsIExternalHelperAppService
mines whether or not data whose filename has the specified extension should be decoded from the specified encoding type before being saved or delivered to helper applications. boolean applyDecodingForExtension( in AUTF8String aExtension, in ACString aEncodingType ); Parameters aExtension The filename extension to check. aEncodingType The encoding type to check. 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. doContent() Binds an external helper application to a stream listener. The caller should pump data into the returned stream listener. When the OnStopRequest is issued, the stream listener implementation will launch the helper app with th...
...terfaceRequestor aWindowContext, in boolean aForceSave ); Parameters aMimeContentType The content type of the incoming data. aRequest The request corresponding to the incoming data. aWindowContext Use nsIServiceManager.getInterface() to retrieve properties like the DOM window or parent window; the service might need this in order to bring up dialogs. aForceSave true to always save this content to disk, regardless of nsIMIMEInfo and other such influences. Return value A nsIStreamListener which the caller should pump the data into. ...
nsIFormHistory2
oid removeAllEntries(); void removeEntriesByTimeframe(in long long aBeginTime, in long long aEndTime); void removeEntriesForName(in AString name); void removeEntry(in AString name, in AString value); Attributes Attribute Type Description DBConnection mozIStorageConnection Returns the underlying DB connection the form history module is using. Read only. hasEntries boolean Returns true if the form history has any entries. Read only. Methods addEntry() Adds a name and value pair to the form history. void addEntry( in AString name, in AString value ); Parameters name value entryExists() Gets whether a name and value pair exists in the form history. boolean entryExists( in AString name, in AString value ); Parameters name value Return value nameExists() Retur...
... the form history has any entries. Read only. Methods addEntry() Adds a name and value pair to the form history. void addEntry( in AString name, in AString value ); Parameters name value entryExists() Gets whether a name and value pair exists in the form history. boolean entryExists( in AString name, in AString value ); Parameters name value Return value nameExists() Returns true if there is no entry that is paired with a name. boolean nameExists( in AString name ); Parameters name Return value removeAllEntries() Removes all entries in the entire form history. void removeAllEntries(); Parameters None. removeEntriesByTimeframe() Removes entries that were created between the specified times. void removeEntriesByTimeframe( in long long aBeginTime, in long long aE...
nsIHttpChannelInternal
documentURI nsIURI An HTTP channel can own a reference to the document URI. forceAllowThirdPartyCookie boolean Force relevant cookies to be sent with this load even if normally they would not be. loca...
...igned long minor); void HTTPUpgrade(in ACString aProtocolName, in nsIHttpUpgradeListener aListener); void setCookie(in string aCookieHeader); void setupFallbackChannel(in string aFallbackKey); Attributes Attribute Type Description canceled boolean Returns true if and only if the channel has been canceled. Read only. channelIsForDownload boolean External handlers may set this to true to notify the channel that it is open on behalf of a download. documentURI nsIURI An HTTP channel can own a reference to the document URI. forceAllowThirdPartyCookie boolean Force relevant cookies to be sent with this load even if normally they would not be. localAddress AUTF8String The local IP address to which the channel is bound, in the same format produced by PR_NetAddrToString(). T...
nsIIDNService
stname is in the IDN whitelist. If the hostname isn't in the whitelist, it's converted into ACE format. The resulting string is useful for display purposes, and ensures that the encoding is consistent with nsIURI.GetHost(). AUTF8String convertToDisplayIDN( in AUTF8String input, out boolean isASCII ); Parameters input The string to convert to display format. isASCII On return, this is set to true if the result is ASCII or ACE encoded; otherwise it's false. Return value The display formatted hostname. convertUTF8toACE() Converts the specified hostname from UTF-8 to ACE format, using the IDNA "ToASCII" algorithm. ACString convertUTF8toACE( in AUTF8String input ); Parameters input The hostname to convert to ACE format. Return value The ACE encoded version of the hostname. isACE() Deter...
...rom UTF-8 to ACE format, using the IDNA "ToASCII" algorithm. ACString convertUTF8toACE( in AUTF8String input ); Parameters input The hostname to convert to ACE format. Return value The ACE encoded version of the hostname. isACE() Determines whether or not the specified hostname is ACE encoded. boolean isACE( in ACString input ); Parameters input The string to check. Return value Returns true if the specified string is ACE encoded; otherwise, returns false. normalize() Performs the Unicode normalization needed for hostnames in IDN. This is useful if you need to normalize a hostname separately from converting it to display format. AUTF8String normalize( in AUTF8String input ); Parameters input The hostname to normalize. Return value The normalized hostname. See also IDN Charter I...
nsIIOService
When in offline mode, attempts to access the network will fail (although this does not necessarily correlate with whether there is actually a network available -- that's hard to detect without causing the dialer to come up). Observers will be notified of changes to this attribute. Methods allowPort() Checks if a port number is banned. This involves con...
...to block the port. This gives the protocol handler ultimate control over its own security policy while ensuring reasonable, default protection. Is similar to nsIProtocolHandler.allowPort(). boolean allowPort( in long aPort, in string aScheme ); Parameters aPort The port to check aScheme The scheme for the protocol handler that could override the IOService's decision. Return value true if the port is allowed, false otherwise. extractScheme() Utility to extract the scheme from a URL string, consistently and according to spec (see RFC 3986). Note: Most URL parsing is done via nsIURI, and in fact the scheme can also be extracted from a URL string via nsIURI. This method is provided purely as an optimization. ACString extractScheme( in AUTF8String urlString ); Parameters ...
nsILoginInfo
s a clone of this login. nsILoginInfo clone(); Parameters None. Return value An nsILoginInfo containing a clone of the login on which this method was invoked. equals() Tests to determine whether this login is exactly equal to another nsILoginInfo object. boolean equals( in nsILoginInfo aLoginInfo ); Parameters aLoginInfo The login to which to compare for equality. Return value true if the two logins are exactly equal or false if they're not. init() Initializes a newly created nsILoginInfo object. void init( in AString aHostname, in AString aFormSubmitURL, in AString aHttpRealm, in AString aUsername, in AString aPassword, in AString aUsernameField, in AString aPasswordField ); Parameters aHostname The value to assign to the hostname field. aFormSubmit...
...red, and the password values may be optionally ignored. If one login's formSubmitURL is an empty string (but not null), it will be treated as a wildcard. A blank value indicates the login was stored before bug 360493 was fixed. boolean matches( in nsILoginInfo aLoginInfo, in boolean ignorePassword ); Parameters aLoginInfo The login to which to compare for equality. ignorePassword If true, do not examine the password value when matching. Return value true if the two logins are equivilant or false if they're not. See also nsILoginManager Using nsILoginManager ...
nsIMIMEInputStream
The value of the content-length is automatically calculated using the available() method on the data stream. The value is recalculated every time the stream is rewound to the start. Not allowed to be changed once the stream has been started to be read. Methods addHeader() Adds an additional header to the stream on the form "nam...
... an nsISeekableStream. ...
nsIMemory
e Frees a previously allocated block of memory. void free( in voidPtr ptr ); Parameters ptr The address of the memory block to free. This may be null, in which case nothing happens. heapMinimize() Attempts to shrink the size of the heap. A particular nsIMemory instance may choose not to implement this method. void heapMinimize( in boolean immediate ); Parameters immediate If true, heap minimization will occur immediately if the call was made on the main thread. If false, the flush will be scheduled to happen when the app is idle. isLowMemory Determine if we are in a low-memory situation (what constitutes low-memory is platform dependent). This can be used to trigger the memory pressure observers. Note: This method was deprecated in Gecko 2.0. If you need to monitor l...
...rmine if we are in a low-memory situation (what constitutes low-memory is platform dependent). This can be used to trigger the memory pressure observers. Note: This method was deprecated in Gecko 2.0. If you need to monitor low memory conditions, you should watch for the Low memory notifications "memory-pressure" notifications instead. boolean isLowMemory(); Parameters None. Return value true if we are in a low-memory situation. Otherwise false. Note: From Gecko 2.0 always returns false. See bug 592308. realloc() Reallocates a block of memory to a new size. voidPtr realloc( in voidPtr ptr, in size_t newSize ); Parameters ptr The address of the memory block to reallocate. This may be null, in which case realloc behaves like alloc(). newSize Specifies the new size in by...
nsIMenuBoxObject
= xulMenu.boxObject.QueryInterface(Components.interfaces.nsIMenuBoxObject); Method overview boolean handleKeyPress(in nsIDOMKeyEvent keyEvent); void openMenu(in boolean openFlag); Attributes Attribute Type Description activeChild nsIDOMElement The currently active menu or menuitem child of the menu box. openedWithKey boolean true if the menubar was opened using the keyboard; otherwise false. Note: For Gecko 2.0, the openedWithKey attribute exists on the nsIMenuBoxObject_MOZILLA_2_0_BRANCH interface. Subsequent Gecko versions will have the attribute on the nsIMenuBoxObject interface. Methods handleKeyPress() boolean handleKeyPress( in nsIDOMKeyEvent keyEvent ); Parameters keyEvent The key event to handl...
...ng the keyboard; otherwise false. Note: For Gecko 2.0, the openedWithKey attribute exists on the nsIMenuBoxObject_MOZILLA_2_0_BRANCH interface. Subsequent Gecko versions will have the attribute on the nsIMenuBoxObject interface. Methods handleKeyPress() boolean handleKeyPress( in nsIDOMKeyEvent keyEvent ); Parameters keyEvent The key event to handle for the menu. 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. See also nsIBoxObject menu ...
nsIMsgCustomColumnHandler
must implement all of nsITreeView and nsIMsgCustomColumnHandler. ...
...rn value The string value that sorting will be done with. getSortLongForRow() If the column displays a number, this will return the number that the column should be sorted by. unsigned long getSortLongForRow(in nsIMsgDBHdr aHdr); Parameters aHdr The message's nsIMsgDBHdr. Return value The long value that sorting will be done with. isString() boolean isString(); Parameters None. Return value true if the column displays a string value. false otherwise. This affects whether getSortStringForRow or getSortLongForRow is used to determine the sort key for the column. It does not affect whether getCellText vs. getImageSrc is used to determine what to display. See Also Extensions:Thunderbird:Creating_a_Custom_Column ...
nsIMsgDatabase
rderValue Readonly: msgHdrCacheSize unsigned long folderStream nsIOutputStream summaryValid boolean Methods Open() Opens a database folder. void Open(in nsILocalFile aFolderName, in boolean aCreate, in boolean aLeaveInvalidDB); Parameters aFolderName The name of the folder to create. aCreate Whether or not the file should be created. aLeaveInvalidDB Set to true if you do not want the database to bedeleted if it is invalid. Exceptions Thrown NS_ERROR_FILE_TARGET_DOES_NOT_EXIST aFolderName doesn't exist and aCreate was false. NS_MSG_ERROR_FOLDER_SUMMARY_OUT_OF_DATE The database is present (and was opened), but the summary file is out of date. NS_MSG_ERROR_FOLDER_SUMMARY_MISSING The database is present (and was opened), but the summary file is missing. ...
...tStringProperty() void setStringProperty(in nsMsgKey aKey, in string aProperty, in string aValue); MarkImapDeleted() void MarkImapDeleted(in nsMsgKey key, in boolean deleted, in nsIDBChangeListener instigator); applyRetentionSettings() Purge unwanted message headers and/or bodies. If deleteViaFolder is true, we'll call nsIMsgFolder.DeleteMessages() to delete the messages. Otherwise, we'll just delete them from the db. void applyRetentionSettings(in nsIMsgRetentionSettings aMsgRetentionSettings, in boolean aDeleteViaFolder); HasNew() boolean HasNew(); ClearNewList() void ClearNewList(in boolean notify); AddToNewList() void AddToNewList(in nsMsgKey key); StartBatch...
nsIMsgHeaderParser
r duplicates against. Addresses in this list will not be added to the result. Return value A string based on the original without the duplicate addresses. Exceptions thrown Missing Exception Missing Description Native code only!unquotePhraseOrAddr This function removes the quoting if you want to show the names to users. e.g. summary file, address book. ...
...unquotePhraseOrAddr This function removes the quoting if you want to show the names to users. e.g. summary file, address book. If preserveIntegrity is set to true, quote will not be removed in case the name part of the email contains a comma. string unquotePhraseOrAddr( in string line, in boolean preserveIntegrity ); Parameters line The header line to parse. preserveIntegrity Set to true, quote will not be removed Return value User friendly names Exceptions thrown Missing Exception Missing Description unquotePhraseOrAddrWString() This function removes the quoting if you want to show the names to users. e.g. summary file, address book. If preserveIntegrity is set to true, quote will not be removed in case the name part of the email contains a comma. wstring unquotePhra...
nsIMsgIncomingServer
structedPrettyName AString helper function to construct the pretty name in a server type specific way - for example, mail for foo@test.com, news on news.mozilla.org. Read only. defaultCopiesAndFoldersPrefsToServer boolean If the server supports Fcc/Sent/etc, default prefs can point to the server. Otherwise, copies and folders prefs should point to Local Folders. By default this value is set to true via global pref 'allows_specialfolders_usage' (mailnews.js). For Nntp, the value is overridden to be false. If ISPs want to modify this value, they should do that in their rdf file by using this attribute. Please look at mozilla/mailnews/base/ispdata/aol.rdf for usage example. displayStartupPage boolean doBiff boolean downloadMessagesAtStartup boolean Read only. downloadOnBiff boolean...
..., such as "mailbox", "imap", or "news" used to construct URIs. Read only. loginAtStartUp boolean logonFallback boolean maxMessageSize long offlineSupportLevel long password ACString passwordPromptRequired boolean If the password for the server is available either via authentication in the current session or from password manager stored entries, return false. Otherwise, return true. If password is obtained from password manager, set the password member variable. Read only. performingBiff boolean port long prettyName AString pretty name - should be "userid on hostname" if the pref is not set. realHostName ACString real hostname of the server (if server name is changed it is stored here) realUsername ACString real username of the server (if username is changed i...
nsINavHistoryObserver
2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Note: This method was removed in Gecko 2.0. Use onDeleteVisits() instead. Called when a history entry expires. This notification is sent to indicate that a specific visit has expired, and includes the time of that visit. When the last visit for a history entry expires, the history entry itself is deleted and the aWholeEntry parameter is true. If your code only cares about whole entries being deleted instead of individual visits, you can simply act only when aWholeEntry is true. It's possible for a history entry to be deleted even though it has no visits if something is out of sync after a bookmark with no visits is deleted; this results in the entire history entry being freed). In such cases, aVisitTime is 0. void onPageExpired( in...
...with no visits is deleted; this results in the entire history entry being freed). In such cases, aVisitTime is 0. void onPageExpired( in nsIURI aURI, in PRTime aVisitTime, in boolean aWholeEntry ); Parameters aURI The URI of the page that expired. aVisitTime The visit time that expired; this may (or may not) be 0 if a bookmark with no visits is deleted. 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. onTitleChanged() Called whenever either the real title or the custom title of the page changes. Both titles are always included in this notification, even though only one is changed each time it is called, since often consumers will want to display...
nsINavHistoryQueryOptions
al options for executing a query. 1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 13.0 (Firefox 13.0 / Thunderbird 13.0 / SeaMonkey 2.10) Method overview nsINavHistoryQueryOptions clone(); Attributes Attribute Type Description applyOptionsToContainers boolean If true, the query options are only applied to the containers. asyncEnabled boolean When true, the root container node generated by these options and all of its descendant containers are opened asynchronously if they support doing so. By default, this is false. Note: Currently, only bookmark folder containers support being opened asynchronously. ...
...I" annotation). Ignored for queries over history. excludeItems boolean This option excludes all URIs and separators from a bookmarks query. This would be used if you just wanted a list of bookmark folders and queries (such as the left pane of the places page). Ignored for queries over history. Defaults to false. excludeQueries boolean Set to true to exclude queries ("place:" URIs) from the query results. Simple folder queries (bookmark folder symlinks) will still be included. Defaults to false. excludeReadOnlyFolders boolean Set to true to exclude read-only folders from the query results. This is designed for cases where you want to give the user the option of filing something into a list of folders. It only af...
nsINavHistoryResult
bute. sortingMode unsigned short Specifies the sorting mode for the result. This value must be one of nsINavHistoryQueryOptions.SORT_BY_*. Changing this value updates the corresponding options for the result so that reusing the current options and queries will always return results based on the current view. suppressNotifications boolean If true, notifications are suppressed. This is used to prevent rapid flickering of changes when performing batch or temporary operations on the result structure. viewer nsINavHistoryResultViewer The viewer for this result. The viewer is responsible for actually updating the view object itself, as well as for handling events on the view. Obsolete since Gecko 2.0 Metho...
... void addObserver( in nsINavHistoryResultObserver aObserver, in boolean aOwnsWeak ); Parameters aObserver An object that implements the nsINavHistoryResultObserver interface, which will receive notifications of changes on the result. aOwnsWeak If false, the result will keep an owning reference to the observer, which must be removed by calling removeObserver(). If true, the result will keep a weak reference to the observer, which must implement the nsISupportsWeakReference interface. removeObserver() Removes an observer that was added by a previous call to addObserver(). void removeObserver( in nsINavHistoryResultObserver aObserver ); Parameters aObserver The observer to remove. See also nsINavHistoryResultObserver nsINavHistoryContaine...
nsINetworkLinkService
The link is only up when network connections can be established. For example, the link is down during DHCP configuration (unless there is another usable interface already configured). If the link status is not currently known, we generally assume that it is up. Read only. linkStatusKnown boolean This is set to...
...when the system is believed to have a usable network connection. The link is only up when network connections can be established. For example, the link is down during DHCP configuration (unless there is another usable interface already configured). If the link status is not currently known, we generally assume that it is up. Read only. linkStatusKnown boolean This is set to true when we believe that isLinkUp is accurate. Read only. linkType unsigned long The type of network connection, one of the LINK_TYPE_* constants. Read only. Note: As of Gecko 8.0, all Operating Systems currently return LINK_TYPE_UNKNOWN. Android support was backed out due to perceived security concerns, see bug 691054. As of Gecko 28.0 Android support is available again...
nsIPrintingPrompt
ent just one of the dialogs and pass back NS_ERROR_NOT_IMPLEMENTED for any of the others. For the Print Dialog: You may stub out this service by having all the methods return NS_ERROR_NOT_IMPLEMENTED. You can then fly you own dialog and then properly fill in the PrintSettings object before calling nsIWebBrowserPrint's Print method. If you stub out this service you MUST set "printSilent" to true, if you do not, Printing will terminate and an error dialog will be displayed. Mac: The GFX layer still supports default toolkit behavior for displaying the Print Dialog. If an embedder implemented service returns NS_ERROR_NOT_IMPLEMENTED for "showPrintDialog" The toolkit will display the native print dialog. Defaults for platform service: Mac OS X: showPrintDialog - displays a nativ...
...server openDialogObserver, in boolean isForPrinting, out nsIWebProgressListener webProgressListener, out nsIPrintProgressParams printProgressParams, out boolean notifyOnOpen ); Parameters webBrowserPrint Represents the document to be printed. printSettings PrintSettings for print "job" openDialogObserver An observer that will be notifed when the dialog is opened. isForPrinting true - for printing, false for print preview. webProgressListener Additional listener can be registered for progress notifications. printProgressParams Parameter object for passing progress state. notifyOnOpen This indicates that the observer will be notified when the progress dialog has been opened. If false is returned it means the observer (usually the caller) shouldn't wait For Print Preview...
nsIProfile
nativeProfileDir, in wstring langcode, in boolean useExistingDir ); Parameters profileName The name to assign to the new profile. nativeProfileDir The pathname of the directory to use as the profile directory; if you specify null, a new folder will be created in the default profiles directory. langcode The locale to use for the new profile. useExistingDir If true, an existing directory may be used; otherwise, the profile directory will be unique. deleteProfile() Deletes the specified profile. void deleteProfile( in wstring name, in boolean canDeleteFiles ); Parameters name The name of the profile to delete. canDeleteFiles If true, the Profile Manager will try to delete all of the profile's files and its directory. getProfileList() ...
...ers length On return, contains the number of profiles in the profileNames array. profileNames On return, contains an array of all of the available profiles' names. profileExists() Determine whether or not a profile with the specified name exists. boolean profileExists( in wstring profileName ); Parameters profileName The name of the profile to look for. Return value true if there is a profile with the specified name. renameProfile() Renames an existing profile. void renameProfile( in wstring oldName, in wstring newName ); Parameters oldName The name of the profile to rename. newName The new name to assign to the profile. Exceptions thrown NS_ERROR_FAILURE A profile already exists with the name newName. shutDownCurrentProfile() Shu...
nsIRequest
cel has been called. Note: Most nsIRequest implementations expect aStatus to be a failure code; however, some implementations may allow aStatus to be a success code such as NS_OK. In general, aStatus should be a failure code. void cancel( in nsresult aStatus ); Parameters aStatus The reason for canceling this request. isPending() Indicates whether the request is pending. isPending is true when there is an outstanding asynchronous event that will make the request no longer be pending. Requests do not necessarily start out pending; in some cases, requests have to be explicitly initiated (for example nsIChannel implementations are only pending once asyncOpen returns successfully). Requests can become pending multiple times during their lifetime. Note: Suspended requests are still c...
...no longer be pending. Requests do not necessarily start out pending; in some cases, requests have to be explicitly initiated (for example nsIChannel implementations are only pending once asyncOpen returns successfully). Requests can become pending multiple times during their lifetime. Note: Suspended requests are still considered pending. boolean isPending(); Parameters None. Return value true if the request has yet to reach completion. resume() Resumes the current request. This may have the effect of re-opening any underlying transport and will resume the delivery of data to any open streams. void resume(); Parameters None. suspend() Suspends the current request. This may have the effect of closing any underlying transport (in order to free up resources), although any open str...
nsIScrollable
ntal scroll range. minVerticalPos An integer representing the minimal position of the vertical scroll range. ...
...ing the minimal position of the vertical scroll range. ...
nsIServiceManager
Y_NOT_REGISTERED Indicates that the specified class is not registered. isServiceInstantiated() This method tests whether or not a XPCOM service, identified by ClassID, has been instantiated. boolean isServiceInstantiated( in nsCIDRef aClass, in nsIIDRef aIID ); Parameters aClass The ClassID of the service that is being tested. aIID The interface type to be tested. Return value true if the service has already been created. Exceptions thrown NS_ERROR_SERVICE_NOT_AVAILABLE Indicates that the service hasn't been instantiated. NS_NOINTERFACE Indicates that the IID given isn't supported. isServiceInstantiatedByContractID() This method tests whether or not a XPCOM service, identified by ContractID, has been instantiated. boolean isServiceInstantiatedByContractID( in s...
...at the IID given isn't supported. isServiceInstantiatedByContractID() This method tests whether or not a XPCOM service, identified by ContractID, has been instantiated. boolean isServiceInstantiatedByContractID( in string aContractID, in nsIIDRef aIID ); Parameters aContractID The ContractID of the service that is being tested. aIID The interface type to be tested. Return value true if the service has already been created. Exceptions thrown NS_ERROR_SERVICE_NOT_AVAILABLE Indicates that the service hasn't been instantiated. NS_NOINTERFACE Indicates that the IID given isn't supported. Remarks The service manager depends on the repository to find and instantiate factories to obtain services. Because services are instantiated lazily, methods are provided to test wheth...
nsISessionStore
tion with browser sessions, tabs, and windows. The API operates on top-level browser.xul and navigator.xul windows; see Note on windows for details. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) In versions of Firefox prior to 3.5, the user preference browser.sessionstore.enabled must be true for these calls to be successful. Starting in Firefox 3.5, this preference is no longer used. Method overview void deleteTabValue(in nsIDOMNode aTab, in AString aKey); void deleteWindowValue(in nsIDOMWindow aWindow, in AString aKey); nsIDOMNode duplicateTab(in nsIDOMWindow aWindow, in nsIDOMNode aTab); nsIDOMNode forgetClosedTab(in nsIDOMWindow aWindow, in u...
...ze them using JSON.stringify. setWindowState() Sets the state of a single window to a given stored state. void setWindowState( in nsIDOMWindow aWindow, in AString aState, in boolean aOverwrite ); Parameters aWindow The nsIDOMWindow whose state is to be set to the state indicated by aState. aState The saved state to apply to the specified window. aOverwrite If this parameter is true, all existing tabs are removed and replaced with the tabs in the state aState. If it's false, the tabs in aState are added to the tabs already in the window. setWindowValue() Sets the value corresponding to a given key for a specified window. void setWindowValue( in nsIDOMWindow aWindow, in AString aKey, in AString aStringValue ); Parameters aWindow The browser window for which th...
nsISimpleEnumerator
PCOM objects and provides methods to access elements sequentially. Inherits from: nsISupports Last changed in Gecko 0.9.6 Method overview nsISupports getNext(); boolean hasMoreElements(); Methods getNext() Called to retrieve the next element in the enumerator. The "next" element is the first element upon the first call. Must be preceded by a call to hasMoreElements() which returns PR_TRUE. This method is generally called within a loop to iterate over the elements in the enumerator. nsISupports getNext(); Parameters None. Return value NS_OK if the call succeeded in returning a non-null value through the out parameter. NS_ERROR_FAILURE if there are no more elements to enumerate. hasMoreElements() Called to determine whether or not the enumerator has any elements that can be returne...
...asMoreElements() Called to determine whether or not the enumerator has any elements that can be returned via getNext(). This method is generally used to determine whether or not to initiate or continue iteration over the enumerator, though it can be called without subsequent getNext() calls. Does not affect internal state of enumerator. boolean hasMoreElements(); Parameters None. Return value PR_TRUE if there are remaining elements in the enumerator. PR_FALSE if there are no more elements in the enumerator. Remarks This interface was frozen for Gecko 0.9.6. See bug 154047 for details. From Gecko 2.0 interfaces are no longer frozen. See also Code example of nsISimpleEnumerator ...
nsIStringEnumerator
xpcom/ds/nsIStringEnumerator.idlScriptable Please add a summary to this article. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview AString getNext(); boolean hasMore(); Methods getNext() Called to retrieve the next string in the enumerator. The "next" element is the first string upon the first call. Must be preceded by a call to hasMoreElements() which returns PR_TRUE. This method is generally called within a loop to iterate over the strings in the enumerator. AString getNext(); Parameters None. Return value The next string in the enumerator. Throws an exception if there are no more strings. hasMore() Called to determine whether or not the enumerator has any strings that can be returned via getNext(). This method is generally used to determine whether or not ...
...e no more strings. hasMore() Called to determine whether or not the enumerator has any strings that can be returned via getNext(). This method is generally used to determine whether or not to initiate or continue iteration over the enumerator, though it can be called without subsequent getNext() calls. Does not affect internal state of enumerator. boolean hasMore(); Parameters None. Return value True if there are remaining strings in the enumerator. False if there are no more strings in the enumerator. ...
nsITaskbarPreviewButton
isplayed below the window preview. 1.0 66 Introduced Gecko 1.9.2 Inherits from: nsISupports Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) You can't directly instantiate this interface. Instead, you use the nsITaskbarWindowPreview.getButton() to get the objects representing the buttons. Attributes Attribute Type Description disabled boolean If true, the button is disabled. This is not the same as visible, which indicates whether or not the button should be displayed at all. dismissOnClick boolean If true, the array of previews should be dismissed when the button is clicked. This is false by default. hasBorder boolean If true, the taskbar should draw a border around this button's image. This is true by default. image imgIContainer The ...
...If false, the button doesn't participate in the layout of buttons underneath the preview. This is false by default. ...
nsITaskbarPreviewController
th the controller's width and height, the values of which are obtained immediately prior to calling this method. boolean drawPreview( in nsIDOMCanvasRenderingContext2D ctx ); Parameters ctx An nsIDOMCanvasRenderingContext2D object representing the drawing context into which the preview is to be rendered. Note that this context is not actually attached to a canvas element. Return value true if you want a frame drawn around the preview, otherwise false. drawThumbnail() Invoked by the taskbar preview when it needs to draw the thumbnail in the taskbar's application preview window. boolean drawThumbnail( in nsIDOMCanvasRenderingContext2D ctx, in unsigned long width, in unsigned long height ); Parameters ctx An nsIDOMCanvasRenderingContext2D object representing the drawing...
...enting the drawing context into which the thumbnail is to be rendered. Note that this context is not actually attached to a canvas element. width The width of the surface backing the drawing context. height The height of the surface backing the drawing context. Note: It's guaranteed that width / height will equal the thumbnailAspectRatio, within the margin of rounding errors. Return value true if you want a frame drawn around the thumbnail, otherwise false. onActivate() Invoked when the user clicks on the tab preview. boolean onActivate(); Parameters None. Return value true if the top level window corresponding to the preview should be activated, false if activation is not accepted. onClick() Invoked when one of the buttons on the window preview's toolbar is clicked by the us...
nsITaskbarWindowPreview
implements much of the behavior for applications in a standard way. This interface's primary purpose is to let Gecko applications take control over parts of the preview; however, certain parts of the preview are not controlled using this interface. For example, the title and icon for each preview always match the title and icon of the corresponding window. If the enableCustomDrawing attribute is true, the controller you implement will start receiving calls to its nsITaskbarPreviewController.drawPreview() and nsITaskbarPreviewController.drawThumbnail() methods, as well as reads of its width, height, and thumbnailAccessRatio attributes. By default, however, Windows handles this drawing by itself. In addition, these previews are visible by default. When made invisible, the window disappears from...
...attributes on that interface. User clicks on the toolbar buttons are reported to your nsITaskbarPreviewController implementation's nsITaskbarPreviewController.onClick() method. Method overview nsITaskbarPreviewButton getButton(in unsigned long index); Attributes Attribute Type Description enableCustomDrawing boolean If true, the nsITaskbarPreviewController object's nsITaskbarPreviewController.drawPreview() and nsITaskbarPreviewController.drawThumbnail() methods will be called to draw the preview. If false, the operating system draws these for you. Constants Constant Value Description NUM_TOOLBAR_BUTTONS 7 The maximum number of toolbar buttons supported ...
nsITelemetry
set, [optional] in boolean aClear); void registerEvents(in ACString aCategory, in jsval aEventData); void registerScalars(in ACString aCategoryName, in jsval aScalarData); void clearEvents(); test only Attributes Attribute Type Description canRecordBase boolean A flag indicating if Telemetry can record base data (FHR data). This is true if the FHR data reporting service or the self-support service is enabled. canRecordExtended boolean A flag indicating if Telemetry is allowed to record extended data. 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. ...
... { name1: {data1}, name2:{data2}...} where data consists of the following properties: min - Minimal bucket size max - Maximum bucket size histogram_type - HISTOGRAM_EXPONENTIAL or HISTOGRAM_LINEAR counts - An array representing the values of buckets in the histogram. ranges - An array with corresponding bucket sizes. sum - Sum of the counts array. static - true for histograms defined in Histograms.json, false for ones defined with newHistogram(). Read only. Constants Histogram Types Constant Value Description HISTOGRAM_EXPONENTIAL 0 Buckets increase exponentially. HISTOGRAM_LINEAR 1 Buckets increase linearly. HISTOGRAM_BOOLEAN 2 For storing 0/1 values. HISTOGRAM_FLAG...
nsITextInputProcessorCallback
Focus: false, _hasRightsToCompose: false, _TIP: null, _callback: function simpleIME_callback(aTIP, aNotification) { try { switch (aNotification.type) { case "request-to-commit": aTIP.commitComposition(); break; case "request-to-cancel": aTIP.cancelComposition(); break; case "notify-focus": this._hasFocus = true; break; case "notify-blur": this._hasFocus = false; break; case "notify-detached": this._hasFocus = false; this._hasRightsToCompose = false; break; } return true; } catch (e) { return false; } }, setComposition: function simpleIME_setComposition(aText, aClauses, aCaret) { if (!this._TIP...
...Otherwise, false. ...
nsIThread
d was not created with the Thread Manager's nsIThreadManager.newThread() method, or the thread is already in the process of being shut down. hasPendingEvents() Determines whether or not the thread has events that are ready to be processed. Note: This method must be called from within the thread itself, and not from another thread. boolean hasPendingEvents() Parameters None. Return value true if there are pending events at the time the function was called. Since other threads may add events to the current thread, it's possible that by the time this method returns, the event queue may no longer be empty, even if a false result is reported. Exceptions thrown NS_ERROR_UNEXPECTED The method was called when this thread wasn't the current thread. processNextEvent() Processes the nex...
... Warning: Calling nsIThread.processNextEvent allows network and UI events to run which can modify data structures that your code isn't expecting to be modified during a synchronous method call. This can cause random crashes and other bugs that may be hard to find and fix. Consider use asynchronous callbacks instead. boolean processNextEvent( in boolean mayWait ); Parameters mayWait If true, this method blocks until an event is available to process if the event queue is empty. If false, this method returns immediately if the queue is empty. Return value Returns true if an event was processed, or false if there were no pending events. Exceptions thrown NS_ERROR_UNEXPECTED This method was called when this thread wasn't the current thread. See also The Thread Manager nsIT...
nsITransaction
ribute Type Description isTransient boolean The transaction's transient state. This attribute is checked by the transaction manager after the transaction's Execute() method is called. If the transient state is false, a reference to the transaction is held by the transaction manager so that the transactions' undoTransaction() and redoTransaction() methods can be called. If the transient state is true, the transaction manager returns immediately after the transaction's doTransaction() method is called, no references to the transaction are maintained. Transient transactions cannot be undone or redone by the transaction manager. Read only. Methods doTransaction() Executes the transaction. void doTransaction(); Parameters None. merge() Attempts to merge a transaction into "this" transaction. ...
... transaction. void doTransaction(); Parameters None. merge() Attempts to merge a transaction into "this" transaction. Both transactions must be in their undo state, doTransaction() methods already called. The transaction manager calls this method to coalesce a new transaction with the transaction on the top of the undo stack. This method returns a boolean value that indicates the merge result. A true value indicates that the transactions were merged successfully, a false value if the merge was not possible or failed. If true, the transaction manager will Release() the new transaction instead of pushing it on the undo stack. boolean merge( in nsITransaction aTransaction ); Parameters aTransaction The previously executed transaction to merge. Return value Missing Description redoTransactio...
nsITransactionList
ers aIndex The index of the item in the list. Return value Missing Description getNumChildrenForItem() Returns the number of child (auto-aggreated) transactions the item at aIndex has. long getNumChildrenForItem( in long aIndex ); Parameters aIndex The index of the item in the list. Return value The number of child (auto-aggreated) transactions the item at aIndex has. itemIsBatch() Returns true if the item at aIndex is a batch. Note that currently there is no requirement for a TransactionManager implementation to associate a toplevel nsITransaction with a batch so it is possible for itemIsBatch to return true and getItem() to return null. However, you can still access the transactions contained in the batch with a call to getChildListForItem(). boolean itemIsBatch( in long aIndex ); ...
...equirement for a TransactionManager implementation to associate a toplevel nsITransaction with a batch so it is possible for itemIsBatch to return true and getItem() to return null. However, you can still access the transactions contained in the batch with a call to getChildListForItem(). boolean itemIsBatch( in long aIndex ); Parameters aIndex The index of the item in the list. Return value true if the item at aIndex is a batch. See also nsITransaction nsITransactionListener nsITransactionManager ...
nsIUTF8StringEnumerator
lement this interface to allow a client to iterate over a set of strings provided by the object. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview AUTF8String getNext(); boolean hasMore(); Methods getNext() Returns the next string in the enumerator. The "next" element is the first string upon the first call. Must be preceded by a call to hasMore(), which returns PR_TRUE. This method is generally called within a loop to iterate over the strings in the enumerator. AUTF8String getNext(); Parameters None. Return value The next string in the enumerator. Throws an exception if there are no more strings. hasMore() Reports whether or not the enumerator has any strings that can be returned via getNext(). This method is generally used to determine whether or not to initi...
...s. hasMore() Reports whether or not the enumerator has any strings that can be returned via getNext(). This method is generally used to determine whether or not to initiate or continue iteration over the enumerator, athough it can be called without subsequent getNext() calls. Calling this method doesn't affect the internal state of the enumerator. boolean hasMore(); Parameters None. Return value true if there are remaining strings in the enumerator, otherwise false. ...
nsIXULRuntime
3.3 / SeaMonkey 2.1) Implemented by: @mozilla.org/xre/app-info;1. To get an instance, use: var xulRuntime = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULRuntime); Method overview void invalidateCachesOnRestart(); Attributes Attribute Type Description accessibilityEnabled boolean If true, the accessibility service is running. Read only. browserTabsRemoteAutostart boolean If true, browser tabs may be opened by default in a different process from the main browser UI. Read only. inSafeMode boolean Whether the application was launched in safe mode. Read only. is64Bit boolean Indicates whether the current Firefox build is 64-bit. R...
... inSafeMode boolean Whether the application was launched in safe mode. Read only. is64Bit boolean Indicates whether the current Firefox build is 64-bit. Read only. logConsoleErrors boolean Whether to write console errors to a log file. If a component encounters startup errors that might prevent the app from showing proper UI, it should set this flag to true. OS AUTF8String A string tag identifying the current operating system. This is taken from the OS_TARGET configure variable. It will always be available. Read only. processID unsigned long The system process ID of the caller's process. Read only. processType unsigned long The type of the caller's process. Returns one of process type constants. Read onl...
nsIXULSortService
content/xul/templates/public/nsIXULSortService.idlScriptable A service used to sort the contents of a XUL widget. Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview void insertContainerNode(in nsIRDFCompositeDataSource db, in nsRDFSortState sortStatePtr, in nsIContent root, in nsIContent trueParent, in nsIContent container, in nsIContent node, in boolean aNotify); Native code only! Obsolete since Gecko 1.9 void sort(in nsIDOMNode aNode, in AString aSortKey, in AString aSortHints); Constants Constant Value Description SORT_COMPARECASE 0x0001 SORT_INTEGER 0x0100 Methods Native code only!insertContainerNode Obsolete since Gecko 1.9 (Firefox 3)This feature is obsolete. Although it may still work in...
...ive code only!insertContainerNode Obsolete since Gecko 1.9 (Firefox 3)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Used internally for insertion sorting. void insertContainerNode( in nsIRDFCompositeDataSource db, in nsRDFSortState sortStatePtr, in nsIContent root, in nsIContent trueParent, in nsIContent container, in nsIContent node, in boolean aNotify ); Parameters db sortStatePtr root trueParent container node aNotify sort() Sort the contents of the widget containing aNode using aSortKey as the comparison key, and aSortHints as how to sort. void sort( in nsIDOMNode aNode, in AString aSortKey, in AString aSortHints ); Parameters aNode A node in the X...
nsIXULTemplateBuilder
de has content generated for it. This method is intended to be called only by the RDF query processor. If aTag is set, the content must have a tag name that matches aTag. aTag may be ignored for builders that don't generate real DOM content. boolean hasGeneratedContent( in nsIRDFResource aNode, in nsIAtom aTag ); Parameters aNode Node to check. aTag Tag that must match. Return value Returns true if the node has content generated for it; otherwise returns false. addRuleFilter() Adds a rule filter for a given rule, which may be used for specialized rule filtering. Any existing filter on the rule is removed. The default conditions specified inside the <rule> tag are applied before the rule filter is applied, meaning that the filter may be used to further filter out results but not reaccept ...
...rces. [noscript] void init( in nsIContent aElement ); Parameters aElement The root element from which to derive the data. Native code only!createContents Invoked lazily by a XUL element that needs its child content built. [noscript] void createContents( in nsIContent aElement, in boolean aForceCreation ); Parameters aElement The element whose contents need to be built. aForceCreation If true, the contents of the element are generated even if the element is closed; this behavior is used with menus. If false, the element's contents are only generated if it's open. addListener() Adds a listener to this template builder. The template builder holds a strong reference to the listener. void addListener( in nsIXULBuilderListener aListener ); Parameters aListener An nsIXULBuilderListener ...
nsIXULTemplateQueryProcessor
cked by the builder so it is safe to use them, however note that a URI that redirects may still needs to be checked to ensure that the document containing aRootNode may access it. This is the responsibility of the query processor if it needs to load the content of the URI. If the query processor needs to load the datasource asynchronously, it may set the aShouldDelayBuilding returned parameter to true to delay building the template content, and call the builder's Rebuild method when the data is available. nsISupports getDatasource( in nsIArray aDataSources, in nsIDOMNode aRootNode, in boolean aIsTrusted, in nsIXULTemplateBuilder aBuilder, out boolean aShouldDelayBuilding ); Parameters aDataSources The list of nsIURI objects and/or nsIDOMNode objects. aRootNode The root node the bui...
...content, and call the builder's Rebuild method when the data is available. nsISupports getDatasource( in nsIArray aDataSources, in nsIDOMNode aRootNode, in boolean aIsTrusted, in nsIXULTemplateBuilder aBuilder, out boolean aShouldDelayBuilding ); Parameters aDataSources The list of nsIURI objects and/or nsIDOMNode objects. aRootNode The root node the builder is attached to. aIsTrusted true if the template is in a trusted document. aBuilder The template builder. aShouldDelayBuilding Whether the builder should wait to build the content or not. Return value A datasource object. initializeForBuilding() Initialize for query generation. This will be called before the rules are processed and whenever the template is rebuilt. This method must be called once before any of the other query p...
nsIXULWindow
assert if they do change. The state change is one-way and idempotent. void assumeChromeFlagsAreFrozen(); Parameters None. center() Move the window to a centered position. void center( in nsIXULWindow aRelative, in boolean aScreen, in boolean aAlert ); Parameters aRelative If not null, the window relative to which the window is moved. See aScreen parameter for details. ...
... createNewWindow() Create a new window. nsIXULWindow createNewWindow( in PRInt32 aChromeFlags, in nsIAppShell aAppShell ); Parameters aChromeFlags See nsIWebBrowserChrome. aAppShell The app shell passed to nsIAppShellService's CreateTopLevelWindow method. ...
nsIZipReader
URI for the JAR (only used for directory streams). zipEntry The name of the entry to open() the stream from. Return value The nsIInputStream containing the contents of the specified zip entry. hasEntry() Checks whether the zipfile contains an entry specified by zipEntry. boolean hasEntry( in AUTF8String zipEntry ); Parameters zipEntry The zip entry. Return value Boolean value, true if the zip entry exists, false is it does not exist. init() Obsolete since Gecko 1.9 (Firefox 3) Initializes a zip reader after construction. void init( in nsIFile zipFile ); Parameters zipFile Zip file to initialize. open() Opens a zip file for reading. It is allowed to open with another file, but it needs to be closed first with close(). Note: Prior to G...
... { zr.open(nsiFileXpi); //if file dne it throws here var entries = zr.findEntries('*'); //we use asterik because we want EVERYTHING listed out while (entries.hasMore()) { var entryPointer = entries.getNext(); //just a string of "zip path" (this means path to file in zip, and it uses forward slashes remember) var entry = zr.getEntry(entryPointer); // should return true on `entry instanceof Ci.nsIZipEntry` console.log('entryPointer', entryPointer); /* CONSOLE OUTPUT * "entryPointer" "bootstrap.js" Scratchpad/1:18 */ console.info('entry', entry); /* CONSOLE OUTPUT * "entry" XPCWrappedNative_NoHelper { QueryInterface: QueryInterface(), compression: Getter, size: Getter, realSize: Getter, CRC32: Getter, isD...
Setting HTTP request headers
fileSpec, location, type); LOG("----------------------------> registerSelf"); var catMgr = Components.classes["@mozilla.org/categorymanager;1"].getService(Components.interfaces.nsICategoryManager); catMgr.addCategoryEntry("app-startup", this.myName, this.myProgID, true, true); }, getClassObject: function (compMgr, cid, iid) { LOG("----------------------------> getClassObject"); return this.myFactory; }, myCID: Components.ID("{9cf5f3df-2505-42dd-9094-c1631bd1be1c}"), myProgID: "@dougt/myHTTPListener;1", myName: "Simple HTTP Listener", myFactory: { QueryInterface: function (aIID) { if (!a...
...The good practice is not to have this specific HTTP header (for example "X-site.net-extension") sent all the time but only when do...
XPIDL
objects having the .value property which contains the real value of the parameter; it is not initialized in the case of out parameters and is initialized to the passed-in-value for inout parameters. The script code would need to set this property to assign a value to the parameter. 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. In addition, the jsval type is translated as the appropriate JavaScript value (since a jsval is the internal representation of all JavaScript values), and objects that are marked nsIVariant have their types automatically boxed and unboxed as appropriate. The equivalent rep...
...s of all IDL types in native code is given in the earlier tables; parameters of type inout follow their out form. 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). Representations of types additionally depend on some of the many types of properties they may have. The array property turns the parameter into an array; the parameter must also have a corresponding size_is property whose argument is the parameter that has the size of the array. In native code, the type gains another pointer indirection, and JavaScript arrays are used in script code. Script co...
Xray vision
as expando properties) and even redefine standard DOM objects to do something unexpected. If chrome code relies on such modified objects, it can be tricked into doing things it shouldn't. For example: window.confirm() is a DOM API that's supposed to ask the user to confirm an action, and return a boolean depending on whether they clicked "OK" or "Cancel". A web page could redefine it to return true: window.confirm = function() { return true; } Any privileged code calling this function and expecting its result to represent user confirmation would be deceived. This would be very naive, of course, but there are more subtle ways in which accessing content objects from chrome can cause security problems. This is the problem that Xray vision is designed to solve. When a script accesses an ob...
...+ ' this.address = {"street" : "Main Street"};' + ' this.fullName = function() {' + ' return this.firstName + " " + this.lastName;'+ ' };' + '};' + 'var me = new Person();' + 'Object.defineProperty(me, "lastName", {' + ' enumerable: true,' + ' configurable: true,' + ' writable: true,' + ' value: "Smith"' + '});' + 'Object.defineProperty(me, "middleName", {' + ' enumerable: true,' + ' configurable: true,' + ' get: function() { return "wait, is this really a getter?"; ...
Filelink Providers
matically in order to fit the content of the IFRAME without scrollbars. Custom settings fields To handle custom settings, the settings XHTML page should contain a form with the id "provider-form", with its onsubmit attribute set to "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. For each input event, the checkValidity method of the form is automatically called. The button to set up the account will only become enabled once the chec...
... Saving custom settings in preferences Custom settings for a provider are saved using the Preferences API. Saving the preferences is handled automatically by the dialog code. Providers need only provide an extraArgs function in the IFrame content which returns an object specifying the name, type, and value to save. ...
Mail composition back end
OnStartCopy The OnStartCopy interface is called when the copy operation has begun. NS_IMETHOD OnStartCopy( nsISupports *listenerData) = 0; ...
...he sending operation was successful. Currently, this pref is a "char *" which is the specific name of the folder, but this will more than likely change to a PRBool (boolean) preference. The determiniation of which folder is the "Sent" folder for the user is done by a call to GetFoldersWithFlag() and the message store will control this user defined preference. If the setting for GetFcc() is set to true, the copy operation is automatically performed after a successful send operation. Drafts Saving a message as a draft is controlled by the "nsMsgDeliverMode mode" argument of the CreateAndSendMessage and SendMessageFile methods. If the caller passes in nsMsgSaveAsDraft, the file created or passed in will be stored as a draft in the user specified "Drafts" folder. ...
Mail event system
rMoveMessages Sample code In this example, a listener will be set up to be notified when the message count changes in a folder: // our variable to know if the listener fired var listenerHasFired = false; var totalMessagesListenerHasFired = false; // the listening function that will react to changes function myOnIntPropertyChanged(item, property, oldValue, newValue) { listenerHasFired=true; var propertyString = property.GetUnicode(); dump("OnIntPropertyChanged has fired with property + " + propertyString + "!\n"); if (propertyString == "TotalMessages") { totalMessagesListenerHasFired=true; //now show us visually var folder = item.QueryInterface(Components.interfaces.nsIMsgFolder); dump("The folder " + folder.prettyName + " now has " + newValu...
...var testPropertyAtom = atomService.getAtom("TestProperty"); // now fire the test notification folder.NotifyIntPropertyChanged(testPropertyAtom, 0, 100); // Now we would do some operations to change the message count, such // as copying a message into this folder or something. Then we could // verify that our listener fired by checking if listenerHasFired and // totalMessagesListenerHasFired are true // this is left as an exercise for the reader. Future plans The notification system has two duplicate methods which could be implemented with OnItemEvent/NotifyItemEvent: FolderLoaded , and DeleteOrMoveMessagesCompleted . Both of these could be done by making atoms for each of these events and just firing it with NotifyItemEvent. Completed There are some of redundant methods betw...
Creating a Custom Column
GetCellText() is the text that is displayed to the user while GetSort*ForRow() is what is used internally when sorting by your column A Simple Implementation Objects in Javascript are just "advanced" variables, so an implemen...
...mColumnHandler interface looks like: var columnHandler = { getCellText: function(row, col) { //get the message's header so that we can extract the reply to field var hdr = gDBView.getMsgHdrAt(row); return hdr.getStringProperty("replyTo"); }, getSortStringForRow: function(hdr) {return hdr.getStringProperty("replyTo");}, isString: function() {return true;}, getCellProperties: function(row, col, props){}, getRowProperties: function(row, props){}, getImageSrc: function(row, col) {return null;}, getSortLongForRow: function(hdr) {return 0;} } Basically, all we are doing here is making sure that both the text that is displayed to the user (getCellText()) and the string we sort according to (when the user decided to sort t...
Filter Incoming Mail
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() ...
... You can take a look at a working code in the CapsKiller add-on repository. ...
Using the Multiple Accounts API
erence: mail.server.server.check_new_mail - boolean, should we check for new mail on a regular basis? Preference: mail.server.server.check_time - integer, number of minutes between checks for new mail Preference: mail.server.server.remember_password - boolean, should we remember the password? Preference: mail.server.server.download_on_biff. ...
...isp.com Preference: mail.identity.identity.reply_to - reply to address during message composition, should only be used if different than useremail. ...
Drawing and Event Handling - Plugins
is already drawn into the area to be updated. The plug-in can then draw the part of the update region that corresponds to its opaque areas. This ensures that the transparent areas of the plug-in are always valid. Windowless plug-ins are transparent by default. If you want to make an opaque windowless plug-in transparent, call the NPN_SetValue method and set NPPVpluginTransparentBool to the value true. The plug-in can call this method any time after specifying that it is a windowless plug-in. Creating Pop-up Menus and Dialog Boxes MS Windows and Unix/X11 only A windowless plug-in does not draw in its own native window. Instead, it draws directly in the drawable given to it. This behavior presents a problem if you need to display pop-up menus and modal dialog boxes in a plug-in; a plug-in ne...
...x. Unix/X11 The value parameter for NPN_GetValue must point to an Xlib Window. On successful return this will contain the browser toplevel window. Use this Window to set the WM_TRANSIENT_FOR property on dialog boxes. Event Handling for Windowless Plug-ins On all platforms, platform-specific events are passed to windowless plug-ins through the NPP_HandleEvent method. The plug-in must return true from NPP_HandleEvent if it has handled the event and false if it has not. Mac OS uses this mechanism for both windowed and windowless plug-ins; on this platform, NPP_HandleEvent is the only way the plug-in can receive events from its host application. int16 NPP_HandleEvent(NPP instance, NPEvent *event); The instance parameter represents the current plug-in. For a list of event types the applic...
URLs - Plugins
vered to the plug-in instance in a new stream. Plug-ins can use this capability to post form data to CGI scripts using HTTP or upload files to a remote server using FTP. The browser resolves this method as the HTTP server method POST, which transmits data to the server. The data to post can be contained either in a local temporary file or a new memory buffer. To post a file, set the flag file to true, the buffer buf to the path name string for a file, and len to the length of the path string. The file-type URL prefix "file://" is optional. NPN_PostURL is typically asynchronous: it returns immediately and only later handles the request and calls NPP_Notify (which, in turn, calls NPP_URLNotify). NPError NPN_PostURL(NPP instance, const char *url, const char *target, uint32 len, const char *b...
...URLNotify to upload files to a remote server using FTP. This example uploads a file from the root of the local file system to an FTP server and displays the response in a frame named response: char* myData = "file:///c\/myDirectory/myFileName"; uint32 myLength = strlen(myData) + 1; err = NPN_PostURL(instance, "ftp://fred@ftp.example.com/pub/", "response", myLength, myData, TRUE); Sending Mail A plug-in can send an email message using NPN_PostURL or NPN_PostURLNotify. The following code sends a mail message with the default headers from the client machine. 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 st...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
Tutorial: Show Allocations Per Call Path This page shows how to use the Debugger API to show how many objects a web page allocates, sorted by the function call path that allocated them. Visit the URL about:config, and set the devtools.chrome.enabled preference to true: Setting the 'devtools.chrome.enabled' preference Open a developer Scratchpad (Menu button > Developer > Scratchpad), and select "Browser" from the "Environment" menu. (This menu will not be present unless you have changed the preference as explained above.) Selecting the 'browser' context in the Scratchpad Enter the following code in the Scratchpad: // This simply defines the 'Debugger' constructor in this // Scratchpad; it doesn't actually start debugging anything. Components.utils.imp...
...dleUncaughtException; // Find the current tab's main content window. var w = gBrowser.selectedBrowser.contentWindow; console.log("Tracking allocations in page: " + w.location.href); // Make that window a debuggee of our Debugger. dbg.addDebuggee(w.wrappedJSObject); // Enable allocation tracking in dbg's debuggees. dbg.memory.trackingAllocationSites = true; } window.demoPlotAllocations = function() { // Grab the allocation log. var log = dbg.memory.drainAllocationsLog(); // Neutralize the Debugger, and drop it on the floor // for the GC to collect. console.log("Stopping allocation tracking."); dbg.removeAllDebuggees(); dbg = undefined; // Analyze and display the allocation log. plot(log); } function h...
Page inspector 3-pane mode - Firefox Developer Tools
ou can observe live changes in CSS features as you edit the rules applied to the page. For example, you could edit a CSS Grid property and observe the change immediately in the Grid Inspector. ...
...onfig and flipping the following prefs to true: devtools.inspector.split-rule-enabled -- this switches 3-pane mode on and off. devtools.inspector.split-sidebar-toggle -- this adds the UI toggle button that lets you toggle it on and off. In Firefox 61, these preferences got renamed to: devtools.inspector.three-pane-enabled devtools.inspector.three-pane-toggle You need to flip these two to true in Release/Beta to test the feature in Firefox 61. Note: The 3-pane inspector is already enabled in Nightly/Developer edition before Firefox 62. ...
Examine and edit CSS - Firefox Developer Tools
ected element, ordered from most-specific to least-specific: The four buttons on the right top of the rules view allow you to change the display of certain CSS and rules view features. You can: toggle pseudo-classes; toggle classes; add a new rule; change the display based on the color scheme preference (as of Firefox 72, you must set devtools.inspector.color-scheme-simulation.enabled to true in the Configuration Editor to enable this feature); change the display based on print media rules. A warning icon appears next to unsupported CSS properties or rules that have invalid values. This can help you understand why certain styles are not being applied. In the following example, a spelling error, "background-colour" instead of "background-color" has made the rule invalid: Rule d...
...n: View @media rules for Print You can toggle the display into a mode that emulates @media rules for print. When on, any rules defined for printing the page will be displayed similar to the "Print Preview" mode that many word processing applications provide. View @media rules for color-scheme-preference As of Firefox 72, you must set devtools.inspector.color-scheme-simulation.enabled to true in the Configuration Editor to enable this feature. If you have set privacy.resistFingerprinting to true, prefers-color-scheme preference is overridden to light. In order to use this simulator, you must set privacy.resistFingerprinting to false. You can use the color scheme simulator to see how the styles display based on the prefers-color-scheme media query, if it is defined for the page. The...
Waterfall - Firefox Developer Tools
n, and console.timeEnd() at the end. These functions take an argument which is used to name the section. ...
...e a timestamp every 10 iterations of the loop, labeled with the iteration number: var iterations = 70; var multiplier = 1000000000; function calculatePrimes() { console.time("calculating..."); var primes = []; for (var i = 0; i < iterations; i++) { if (i % 10 == 0) { console.timeStamp(i.toString()); } var candidate = i * (multiplier * Math.random()); var isPrime = true; for (var c = 2; c <= Math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isPrime = false; break; } } if (isPrime) { primes.push(candidate); } } console.timeEnd("calculating..."); return primes; } In the Waterfall you'll now see something like this: ...
Settings - Firefox Developer Tools
's just one of these: Enable persistent logs A setting to control whether or not the Web Console and Network Monitor clear their output when you navigate to a new page. If Common Preferences is not included in the Settings, Web Console logs can be persisted by using the 'about:config' url in browser address bar, searching for: 'devtools.webconsole.persistlog' then toggling this value to true Inspector Show browser styles A setting to control whether styles applied by the browser (user-agent styles) should be displayed in the Inspector's Rules view. Note that this setting is independent of the "Browser styles" checkbox in the Inspector's Computed view. Truncate DOM attributes By default, the Inspector truncates DOM attributes that are more than 120 characters long. Uncheck thi...
...and not only web content. Enable remote debugging Enable the developer tools to debug remote Firefox instances. Enable worker debugging Enable a panel within the debugger to debug workers. Note: This option got removed from the UI in Firefox 56, because this version ships with a new Debugger UI, but it can still be enabled for the old UI by setting the preference devtools.debugger.workers to true. ...
about:debugging (before Firefox 68) - Firefox Developer Tools
bout:debugging opens, on the left-hand side, you'll see a sidebar enabling you to switch between the two main views: one for add-ons and one for workers. Whether or not system add-ons appear in the list on this page depends on the setting of the devtools.aboutdebugging.showSystemAddons preference. If you need to see system add-ons, navigate to about:config and make sure that this value is set to true. Add-ons The Add-ons section in about:debugging only supports restartless add-ons, including basic bootstrapped extensions, Add-on SDK add-ons, and WebExtensions. This page enables you to do two things: Load an add-on temporarily from disk Connect the Add-on Debugger to any restartless add-ons Connecting the Add-on Debugger The Add-ons page in about:debugging lists all restartless a...
...tion. Click "OK", and the Add-on Debugger will start in a separate window. Note that sometimes the debugger window is hidden by the main Firefox window. See the page on the Add-on Debugger for all the things you can do with this tool. The "Enable add-on debugging" button works by turning on the devtools.chrome.enabled and devtools.debugger.remote-enabled preferences. Both preferences must be true to enable add-on debugging. Checking the box sets both preferences to true, and unchecking it sets them both to false. You can also modify the preferences directly in about:config, or by checking "Enable browser chrome and add-on debugging toolboxes" and "Enable remote debugging" in the Developer Tools Settings. Loading a temporary add-on With the "Load Temporary Add-on" button you can load a...
AddressErrors - Web APIs
In this example, only the Basic Card handler is supported, and it's configured to permit both debit and credit cards from Visa, Master Card, American Express, and Discover. defaultPaymentDetails describes the payment being requested. A description of the total amount being requested (including a l...
...scription of the total amount being requested (including a label and the currency used), a list of the line items (in this case only one, "Original donation amount"), and a list of shipping options available; in this case only one. Process the payment The main payment processing code is found in the process() method, up next. let request; function process() { let options = {requestShipping: true}; try { request = new PaymentRequest(supportedHandlers, defaultPaymentDetails, options); // Add event listeners here. request.onshippingaddresschange = handleAddressChange; // Call show() to trigger the browser's payment flow. request.show().then(function(instrumentResponse) { // Do something with the response from the UI. console.log("Got response!"); }) ...
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
late the speed of audio stream rendering. Its nominal range is (-? to +?). The default is 0. loop: A boolean indicating whether the audio should play in a loop. The default is false. If the loop is dynamically modified during playback, the new value will take effect on the next processing block of audio. loopEnd: An optional value, in seconds, where looping should end if the loop attribute is true. The default is 0. Its value is exclusive to the content of the loop. The sample frames, comprising the loop, run from the values loopStart to loopEnd-(1/sampleRate). It's sensible to set this to a value between 0 and the duration of the buffer. If loopEnd is less than 0, looping will end at 0. If loopEnd is greater than the duration of the buffer, looping will end at the end of the buffer. This ...
...f the buffer, looping will end at the end of the buffer. This attribute is converted to an exact sample frame offset within the buffer, by multiplying by the buffer's sample rate and rounding to the nearest integer value. Thus, its behavior is independent of the value of the playbackRate parameter. loopStart: An optional value in seconds, where looping should begin if the loop attribute is true. The default is 0. It's sensible to set this to a value between 0 and the duration of the buffer. If loopStart is less than 0, looping will begin at 0. If loopStart is greater than the duration of the buffer, looping will begin at the end of the buffer. This attribute is converted to an exact sample frame offset within the buffer, by multiplying by the buffer's sample rate and rounding to the nea...
AudioBufferSourceNode.playbackRate - Web APIs
the fly. You can run the example live (or view the source.) Play the song and alter the playback rate for some fun results. ...
...request.open('GET', 'viper.ogg', true); request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { myBuffer = buffer; source.buffer = myBuffer; source.playbackRate.value = playbackControl.value; source.connect(audioCtx.destination); source.loop = true; }, function(e){"Error with decoding audio data" + e.err}); } request.send(); } // wire up buttons to stop and play audio, and range slider control play.onclick = function() { getData(); source.start(0); play.setAttribute('disabled', 'disabled'); playbackControl.removeAttribute('disabled'); } stop.onclick = function() { source.stop(0); play.removeAttribute('disab...
AudioContext.createMediaStreamDestination() - Web APIs
var blob = new Blob(chunk...
... var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); document.querySelector("audio").src = URL.createObjectURL(blob...
AudioContext.createMediaStreamTrackSource() - Web APIs
n the stream returned by getUserMedia(). Then a BiquadFilterNode is created using createBiquadFilter(), and it's configured as desired to perform a lowshelf filter on the audio coming from the source. The output from the microphone is then routed into the new biquad filter, and the filter's output is in turn routed to the audio context's destination. ...
...wshelf filter on the audio coming from the source. The output from the microphone is then routed into the new biquad filter, and the filter's output is in turn routed to the audio context's destination. ...
BaseAudioContext.createPeriodicWave() - Web APIs
terms (traditionally the A terms). imag An array of sine terms (traditionally the B terms). The real and imag arrays have to have the same length, otherwise an error is thrown. constraints Optional An dictionary object that specifies whether normalization should be disabled (if not specified, normalization is enabled by default.) It takes one property: disableNormalization: If set to true, normalization is disabled for the periodic wave. The default is false. If normalized, the resulting wave will have a maximum absolute peak value of 1. Example The following example illustrates simple usage of createPeriodicWave(), to create a PeriodicWave object containing a simple sine wave. var real = new Float32Array(2); var imag = new Float32Array(2); var ac = new AudioContext(); ...
...f 1. Example The following example illustrates simple usage of createPeriodicWave(), to create a PeriodicWave object containing a simple sine wave. var real = new Float32Array(2); var imag = new Float32Array(2); var ac = new AudioContext(); var osc = ac.createOscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createPeriodicWave(real, imag, {disableNormalization: true}); osc.setPeriodicWave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); This works because a sound that contains only a fundamental tone is by definition a sine wave Here, we create a PeriodicWave with two values. The first value is the DC offset, which is the value at which the oscillator starts. 0 is good here, because we want to start the curve at the middle of the [-1.0; 1.0...
BaseAudioContext.decodeAudioData() - Web APIs
document.querySelector('script'); var play = document.querySelector('.play'); var stop = document.querySelector('.stop'); // use XHR to load an audio track, and // decodeAudioData to decode it and stick it in a buffer. ...
... { source = audioCtx.createBufferSource(); var request = new XMLHttpRequest(); request.open('GET', 'viper.ogg', true); request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { source.buffer = buffer; source.connect(audioCtx.destination); source.loop = true; }, function(e){ console.log("Error with decoding audio data" + e.err); }); } request.send(); } // wire up buttons to stop and play audio play.onclick = function() { getData(); source.start(0); play.setAttribute('disabled', 'disabled'); } stop.onclick = function() { source.stop(0); play.removeAttribute('disabled'); } // dump script to pre element pre.innerHTML =...
BasicCardRequest.supportedNetworks - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari ? WebView Android No support NoChrome Android Full support 57Firefox Android ...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS ? Samsung Internet Android Full support 7.0Legend Full support Full support No support ...
BasicCardRequest - Web APIs
// Call show() to trigger the browser's payment flow. request.show().then(function(instrumentResponse) { // Do something with the response from the UI. }) .catch(function(err) { // Do something with the error from re...
... // Call show() to trigger the browser's payment flow. request.show().then(function(instrumentResponse) { // Do something with the response from the UI. }) .catch(function(err) { // Do something with the error from request.show(). }); } catch (e) { // Catch any ot...
BasicCardResponse.billingAddress - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari ? WebView Android No support NoChrome Android Full support 57Firefox Android ...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS ? Samsung Internet Android Full support 7.0Legend Full support Full support No support ...
BasicCardResponse.cardNumber - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari ? WebView Android No support NoChrome Android Full support 57Firefox Android ...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS ? Samsung Internet Android Full support 7.0Legend Full support Full support No support ...
BasicCardResponse.cardSecurityCode - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari ? WebView Android No support NoChrome Android Full support 57Firefox Android ...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS ? Samsung Internet Android Full support 7.0Legend Full support Full support No support ...
BasicCardResponse.cardholderName - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari ? WebView Android No support NoChrome Android Full support 57Firefox Android ...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS ? Samsung Internet Android Full support 7.0Legend Full support Full support No support ...
BasicCardResponse.expiryMonth - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari ? WebView Android No support NoChrome Android Full support 57Firefox Android ...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS ? Samsung Internet Android Full support 7.0Legend Full support Full support No support ...
BasicCardResponse.expiryYear - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari ? WebView Android No support NoChrome Android Full support 57Firefox Android ...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS ? Samsung Internet Android Full support 7.0Legend Full support Full support No support ...
Beacon API - Web APIs
Global context The Beacon API's Navigator.sendBeacon() method is used to send a beacon of data to the server in the global browsing context. The method takes two arguments, the URL and the data to send in the request. The data argument is optional and its type may be an ArrayBufferView, Blob, DOMString, or FormData. If the browser successfully queues the request for delivery, the method returns "true" and returns "false" otherwise. Worker context The Beacon API's Navigator.sendBeacon() method is used to send a beacon of data to the server from the worker global scope. The method takes two arguments, the URL and the data to send in the request. The data argument is optional and its type may be an ArrayBufferView, Blob, DOMString, or FormData. If the browser successfully queues the request fo...
... ...
Bluetooth.getAvailability() - Web APIs
Also, user can configure User Agent to return a fixed value instead of a real one. ...
...Also, user can configure User Agent to return a fixed value instead of a real one. ...
CSS.supports() - Web APIs
Web › API › CSS › supports
t sets of parameters. The first one allows to test the support of a pair property-value: propertyName A DOMString containing the name of the CSS property to check. value A DOMString containing the value of the CSS property to check. The second syntax takes one parameter matching the condition of @supports: supportCondition A DOMString containing the condition to check. 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 ...
... 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. Candidate Recommendation Initial definition. ...
CSSNumericValue.equals() - Web APIs
The equals() method of the CSSNumericValue interface returns a boolean indicating whether the passed value are strictly equal. To return a value of true, all passed values must be of the same type and value and must be in the same order. This allows structural equality to be tested quickly. Syntax var boolean = CSSNumericValue.equals(number); Parameters number Either a Number or a CSSNumericValue. Return value A Boolean. Exceptions None. Examples As stated earlier, all passed values must be of the same type and value and must be in the same order. Some of the following examples illustrate what happens when they are not. ...
...ither a Number or a CSSNumericValue. Return value A Boolean. Exceptions None. Examples As stated earlier, all passed values must be of the same type and value and must be in the same order. Some of the following examples illustrate what happens when they are not. 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. Working ...
CSSStyleSheet.insertRule() - Web APIs
te that an array is needed for declarations and rules since ECMAScript does * not guarantee a predictable object iteration order, and since CSS is * order-dependent. ...
... array is needed for declarations and rules since ECMAScript does * not guarantee a predictable object iteration order, and since CSS is * order-dependent. ...
Cache.keys() - Web APIs
Web › API › Cache › keys
y of requests }); Parameters request Optional The Request want to return, if a specific key is desired. This can be a Request object or a URL. options Optional An object whose properties control how matching is done in the keys operation. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. ...
...nal An object whose properties control how matching is done in the keys operation. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. If set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. 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. ignoreVary: A Boolean that, when set to true, tells the matching operation not to perform VARY header matching. In other words, if the URL matches you will get a match regardless of whether the Response object has a VARY header. It defaults to false. cacheNam...
Cache.match() - Web APIs
Web › API › Cache › match
sponse) { // Do something with the response }); Parameters request The Request for which you are attempting to find responses in the Cache. This can be a Request object or a URL. options Optional An object that sets options for the match operation. The available options are: ignoreSearch: A Boolean that specifies whether to ignore the query string in the URL. ...
...Request object or a URL. options Optional An object that sets options for the match operation. The available options are: ignoreSearch: A Boolean that specifies whether to ignore the query string in the URL. For example, if set to true the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. 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. ignoreVary: A Boolean that when set to true tells the matching operation not to perform VARY header matching -- i.e. if the URL matches you will get a match regardless of whether the Response object has a VARY header. It defaults to false. Return value A P...
Cache.matchAll() - Web APIs
Web › API › Cache › matchAll
es in the Cache. This can be a Request object or a URL. If this argument is omitted, you will get a copy of all responses in this cache. options Optional An options object allowing you to set specific control options for the matching performed. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. ...
...ons object allowing you to set specific control options for the matching performed. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. If set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. 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. ignoreVary: A Boolean that when set to true tells the matching operation not to perform VARY header matching -- i.e. if the URL matches you will get a match regardless of the Response object having a VARY header or not. It defaults to false. Return value A...
CacheStorage.match() - Web APIs
omething with the response }); Parameters request The Request you want to match. This can be a Request object or a URL string. options Optional An object whose properties control how matching is done in the match operation. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. ...
... whose properties control how matching is done in the match operation. The available options are: ignoreSearch: A Boolean that specifies whether the matching process should ignore the query string in the url. For example, if set to true, the ?value=bar part of http://foo.com/?value=bar would be ignored when performing a match. 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. ignoreVary: A Boolean that, when set to true, tells the matching operation not to perform VARY header matching. In other words, if the URL matches you will get a match regardless of whether the Response object has a VARY header or not. It defaults to false. cac...
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
raw a focus ring when appropriate. ...
... id="canvas"> <button id="button1">Continue</button> <button id="button2">Quit</button> </canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const button1 = document.getElementById('button1'); const button2 = document.getElementById('button2'); document.addEventListener('focus', redraw, true); document.addEventListener('blur', redraw, true); canvas.addEventListener('click', handleClick, false); redraw(); function redraw() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawButton(button1, 20, 20); drawButton(button2, 20, 80); } function handleClick(e) { // Calculate click coordinates const x = e.clientX - canvas.offsetLeft; const y = e.clientY - canvas.offsetTop; // Focus button1, if appropriate drawButton(bu...
CanvasRenderingContext2D.ellipse() - Web APIs
s minor-axis radius. Must be non-negative. rotation The rotation of the ellipse, expressed in radians. startAngle The angle at which the ellipse starts, measured clockwise from the positive x-axis and expressed in radians. endAngle The angle at which the ellipse ends, measured clockwise from the positive x-axis and expressed in radians. anticlockwise Optional An optional Boolean which, if true, draws the ellipse anticlockwise (counter-clockwise). The default value is false (clockwise). Examples Drawing a full ellipse This example draws an ellipse at an angle of ?/4 radians (45?). To make a full ellipse, the arc begins at an angle of 0 radians (0?), and ends at an angle of 2? radians (360?). HTML <canvas id="canvas" width="200" height="200"></canvas> JavaScript const canvas = d...
... Living Standard ...
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). On getting the imageSmoothingEnabled property, the last value it was set to is returned. This property is useful for games and other apps that use pixel art. When enlarging images, the default resizing algorithm will blur the pixels. Set this property to false to retain the pixels' sharpness. Note: You can adjust the smoothing quality with the imageSmoothingQuality property. Syntax ctx.imageSmoothingEnabled = value; Options value A Boolean indicating whether to smooth scaled images or not. The default value is true. Examples Disabling image smoothing This example compares three images. The first image...
...lementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = '16px sans-serif'; ctx.textAlign = 'center'; const img = new Image(); img.src = 'https://interactive-examples.mdn.mozilla.net/media/examples/star.png'; img.onload = function() { const w = img.width, h = img.height; ctx.fillText('Source', w * .5, 20); ctx.drawImage(img, 0, 24, w, h); ctx.fillText('Smoothing = TRUE', w * 2.5, 20); ctx.imageSmoothingEnabled = true; ctx.drawImage(img, w, 24, w * 3, h * 3); ctx.fillText('Smoothing = FALSE', w * 5.5, 20); ctx.imageSmoothingEnabled = false; ctx.drawImage(img, w * 4, 24, w * 3, h * 3); }; Result Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.imageSmoothingEnabled...
Constraint validation API - Web APIs
nt is not a candidate for constraint validation, or if the element's value is valid. If the element's value is not valid, it returns a localized validation message. This will be displayed in the UI if the element is the only form control with a validity problem; if a custom error message is set using setCustomValidity(), this will be shown. willValidate A read-only boolean property that returns true if the element is a candidate for constraint validation; and false otherwise. Elements with the HTMLObjectElement interface are never candidates for constraint validation. Others may be barred from constraint validation depending on specific conditions. Methods checkValidity() Checks the element's value against its constraints. If the value is invalid, it fires an invalid event at the eleme...
...nt validation; and false otherwise. Elements with the HTMLObjectElement interface are never candidates for constraint validation. Others may be barred from constraint validation depending on specific conditions. Methods checkValidity() Checks the element's value against its constraints. If the value is invalid, it fires an invalid event at the element and 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. Otherwise, it returns true. setCustomValidity(message) Sets a custom error message strin...
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. ...
...xt(); var convolver = audioCtx.createConvolver(); convolver.normalize = false; Value A boolean. Example var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var convolver = audioCtx.createConvolver(); ... ...
DOMTokenList.contains() - Web APIs
Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then test for the existence of "c" in the list, and write the result into the <span>'s Node.textContent. ...
... Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then test for the existence of "c" in the list, and write the result into the <span>'s Node.textContent. ...
DOMTokenList.replace() - Web APIs
ting token with a new token. If the first token doesn't exist, replace() returns false immediately, without adding the new token to the token list. Syntax tokenList.replace(oldToken, newToken); Parameters oldToken A DOMString representing the token you want to replace. newToken A DOMString representing the token you want to replace oldToken with. Return value A boolean value, which is true if oldToken was successfully replaced, or false if not. Note: In older browsers, replace() returns void. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. We then replace a token in the list, and write the list into the <span>'s Node.textContent. First, the HTML: <span class="a b c"></span> Now the JavaScri...
... } The output looks like this: Polyfill The following polyfill will add the replace method to the DOMTokenList class. The following code will only work with IE10-11. To use with earlier versions of IE, refer to the polyfill at element.classList#Polyfill DOMTokenList.prototype.replace = function (a, b) { if (this.contains(a)) { this.add(b); this.remove(a); return true; } return false; } Specifications Specification Status Comment DOMThe definition of 'replace()' in that specification. Living Standard Initial definition ...
DOMTokenList.supports() - Web APIs
Returns A Boolean indicating whether the token was found. ...
... Returns A Boolean indicating whether the token was found. ...
DOMTokenList.toggle() - Web APIs
Return value A Boolean indicating whether token is in the list after the call. ...
... Return value A Boolean indicating whether token is in the list after the call. Examples In the following example we retrieve the list of classes set on a <span> element as a DOMTokenList using Element.classList. ...
DOMTokenList - Web APIs
operties DOMTokenList.length Read only Is an integer representing the number of objects stored in the object. DOMTokenList.value A stringifier property that returns the value of the list as a DOMString. Methods DOMTokenList.item(index) Returns the item in the list by its index, or undefined if index is greater than or equal to the list's length. ...
... DOMTokenList.toggle(token [, force]) Removes token from the list if it exists, or adds token to the list if it doesn't. Returns a boolean indicating whether token is in the list after the operation. ...
DataTransfer.clearData() - Web APIs
s writeable. Syntax DataTransfer.clearData([format]); Parameters format Optional A string which specifies the type of data to remove. If this parameter is an empty string or is not provided, the data for all types is removed. Example This example shows the use of the DataTransfer object's getData(), setData() and clearData() methods. HTML <span class="tweaked" id="source" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element. </span> <span class="tweaked" id="target">Drop Zone</span> <div>Status: <span id="status">Drag to start</span></div> <div>Data is: <span id="data">uninitialized</span></div> CSS span.tweaked { display: inline-block; margin: 1em 0; padding: 1em 2em; } #source { color: blue; border: 1...
...tener('dragleave', dragLeaveHandler); dropable.removeEventListener('drop', dropHandler); } } function dragOverHandler (event) { status.innerHTML = 'Drop available'; event.preventDefault(); } function dragLeaveHandler (event) { status.innerHTML = 'Drag in process (drop was available)'; event.preventDefault(); } function dropHandler (event) { dropped = true; status.innerHTML = 'Drop done'; event.preventDefault(); // Get data linked to event format << text >> var _data = event.dataTransfer.getData('text/plain'); var element = document.getElementById(_data); // Append drag source element to event's target element event.target.appendChild(element); // Change CSS styles and displayed text element.style.cssText = ...
DataTransfer.mozUserCancelled - Web APIs
Example This example shows the use of the mozUserCancelled property in the dragend event handler. ...
... Example This example shows the use of the mozUserCancelled property in the dragend event handler. ...
Detecting device orientation - Web APIs
orientation events All you need to do in order to begin receiving orientation change is to listen to the deviceorientation event: Note: gyronorm.js is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. This is useful for overcoming some of the differences in device support for device orientation. window.addEventListener("deviceorientation", handleOrientation, true); After registering your event listener (in this case, a JavaScript function called handleOrientation()), your listener function periodically gets called with updated orientation data. The orientation event contains four values: DeviceOrientationEvent.absolute DeviceOrientationEvent.alpha DeviceOrientationEvent.beta DeviceOrientationEvent.gamma The event handler function can look somet...
... deviceorientation doesn't work in a cross-origin <iframe> in all browsers. Warning: Chrome and Firefox do not handle the angles the same way, so on some axes the direction are reversed. Processing motion events Motion events are handled the same way as the orientation events except that they have their own event's name: devicemotion window.addEventListener("devicemotion", handleMotion, true); What's really changed are the information provided within the DeviceMotionEvent object passed as a parameter of the HandleMotion function. The motion event contains four properties: DeviceMotionEvent.acceleration DeviceMotionEvent.accelerationIncludingGravity DeviceMotionEvent.rotationRate DeviceMotionEvent.interval Motion values explained The DeviceMotionEvent objects provide web de...
DisplayMediaStreamConstraints.audio - Web APIs
More precise control over the audio data may be exercised by instead providing a MediaTrackConstraints object, which is used to process the audio prior to adding it to the stream. ...
...he user's microphone, but there is no way to specify which source to use. Syntax displayMediaStreamConstraints.audio = allowAudioFlag; displayMediaStreamConstraints.audio = mediaTrackConstraints; displayMediaStreamConstraints = { audio: allowAudioFlag|mediaTrackConstraints; } Value The value may be either a Boolean or a MediaTrackConstraints object. If a Boolean is specified, a value of true indicates that an audio track should be included in the stream returned by getDisplayMedia(), if an appropriate audio source exists and the user agent supports audio on display media. A value of false--the default--indicates that no audio track is to be included in the stream. If a MediaTrackConstraints object is given, and an audio source is available, an audio track matching the settings given...
DisplayMediaStreamConstraints.video - Web APIs
Since a video track must always be included, a value of false results in a TypeError exception being thrown. ...
...after obtaining it from the device but prior to adding it to the stream. Syntax displayMediaStreamConstraints.video = allowVideoFlag; displayMediaStreamConstraints.video = mediaTrackConstraints; displayMediaStreamConstraints = { video: allowVideoFlag | mediaTrackConstraints; } Value The value may be either a Boolean or a MediaTrackConstraints object. If a Boolean is specified, a value of true (the default) indicates that the stream returned by getDisplayMedia() should be in whatever format the user agent feels is best. A value of false is not permitted and will throw a TypeError. If a MediaTrackConstraints object is given instead, the video track will be processed to match the settings given in the constraints object. Constraints specific to screen sharing These constraints apply t...
Document.fullscreen - Web APIs
though this property is read-only, it will not throw if it is modified (even in strict mode); the setter is a no-operation and it will be ignored. Note: Since this property is deprecated, you can determine if full-screen mode is active on the document by checking to see if Document.fullscreenElement is not null. 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. Example This simple function reports whether or not full-screen mode is currently active, using the obsolete fullscreen property. function isDocumentInFullScreenMode() { return document.fullscreen; } This next example, on the other hand, uses the current fullscreenElement property to dete...
...full-screen mode is currently active, using the obsolete fullscreen property. function isDocumentInFullScreenMode() { return document.fullscreen; } This next example, on the other hand, uses the current fullscreenElement property to determine the same thing: function isDocumentInFullScreenMode() { return document.fullscreenElement !== null; } If fullscreenElement isn't null, this returns true, indicating that full-screen mode is in effect. Specifications Specification Status Comment Fullscreen APIThe definition of 'Document.fullscreen' in that specification. Living Standard Initial definition (as an obsolete property). ...
Document.importNode() - Web APIs
emoved from its original document. The imported node is a clone of the original. Syntax const importedNode = document.importNode(externalNode [, deep]); Parameters externalNode The external Node or DocumentFragment to import into the current document. deep Optional A Boolean which controls whether to include the entire DOM subtree of the externalNode in the import. If deep is set to true, then externalNode and all of its descendants are copied. If deep is set to false, then only externalNode is imported -- the new node has no children. Note: In the DOM4 specification, deep was an optional argument with a default value of true. This default has changed in the latest spec! The new default value is false. Best Practice: Though it's still an optional argument, you should ...
...ted instead of a deep clone. Return value The copied importedNode in the scope of the importing document. Note: importedNode's Node.parentNode is null, since it has not yet been inserted into the document tree! Example const iframe = document.querySelector("iframe"); const oldNode = iframe.contentWindow.document.getElementById("myNode"); const newNode = document.importNode(oldNode, true); document.getElementById("container").appendChild(newNode); Notes Before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importNode(); or adopted using document.adoptNode(). Best Practice: Although Firefox doesn't currently enforce this rule, we encourage you to follow this rule for improved future compatibility. F...
Document.queryCommandState() - Web APIs
The queryCommandState() method will tell you if the current selection has a certain Document.execCommand() command applied. Syntax queryCommandState(String command) Parameters command is a command from Document.execCommand() Return value queryCommandState() can return a Boolean value or null if the state is unknown. ...
... command from Document.execCommand() Return value queryCommandState() can return a Boolean value or null if the state is unknown. ...
EXT_disjoint_timer_query.isQueryEXT() - Web APIs
Examples var ext = gl.getExtension('EXT_disjoint_timer_query'); var query = ext.createQueryEXT(); // ... ...
... Examples var ext = gl.getExtension('EXT_disjoint_timer_query'); var query = ext.createQueryEXT(); // ... ...
Element: blur event - Web APIs
nput[type="password"]'); password.addEventListener('focus', (event) => { event.target.style.background = 'pink'; }); password.addEventListener('blur', (event) => { event.target.style.background = ''; }); Result Event delegation There are two ways of implementing event delegation for this event: by using the focusout event, or by setting the useCapture parameter of addEventListener() to true. ...
...egation for this event: by using the focusout event, or by setting the useCapture parameter of addEventListener() to true. HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> JavaScript const form = document.getElementById('form'); form.addEventListener('focus', (event) => { event.target.style.background = 'pink'; }, true); form.addEventListener('blur', (event) => { event.target.style.background = ''; }, true); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Document Object Model (DOM) Level 3 Events Specification Obsolete Initial definition ...
Element: copy event - Web APIs
tents by calling setData(format, data) on the event's ClipboardEvent.clipboardData property, and cancelling the event's default action using event.preventDefault(). However, the handler cannot read the clipboard data. It's possible to construct and dispatch a synthetic copy event, but this will not affect the system clipboard. ...
... property, and cancelling the event's default action using event.preventDefault(). However, the handler cannot read the clipboard data. It's possible to construct and dispatch a synthetic copy event, but this will not affect the system clipboard. ...
Element: cut event - Web APIs
Web › API › Element › cut event
handler which wants to emulate the default action for "cut" while modifying the clipboard must also manually remove the selection from the document. The handler cannot read the clipboard data. It's possible to construct and dispatch a synthetic cut event, but this will not affect the system clipboard or the document's contents. ...
...pboard must also manually remove the selection from the document. The handler cannot read the clipboard data. It's possible to construct and dispatch a synthetic cut event, but this will not affect the system clipboard or the document's contents. ...
Element: focus event - Web APIs
input[type="password"]'); password.addEventListener('focus', (event) => { event.target.style.background = 'pink'; }); password.addEventListener('blur', (event) => { event.target.style.background = ''; }); Result Event delegation There are two ways of implementing event delegation for this event: by using the focusin event, or by setting the useCapture parameter of addEventListener() to true. ...
...legation for this event: by using the focusin event, or by setting the useCapture parameter of addEventListener() to true. HTML <form id="form"> <input type="text" placeholder="text input"> <input type="password" placeholder="password"> </form> JavaScript const form = document.getElementById('form'); form.addEventListener('focus', (event) => { event.target.style.background = 'pink'; }, true); form.addEventListener('blur', (event) => { event.target.style.background = ''; }, true); Result Specifications Specification Status Comment UI Events Working Draft Added info that this event is composed. Document Object Model (DOM) Level 3 Events Specification Obsolete Initial definition ...
Element.scrollIntoViewIfNeeded() - Web APIs
nt into the visible area of the browser window if it's not already within the visible area of the browser window. If the element is already within the visible area of the browser window, then no scrolling takes place. This method is a proprietary variation of the standard Element.scrollIntoView() method. Syntax TODO Parameters opt_center Is an optional Boolean value with a default value of true: If true, the element will be aligned so it is centered within the visible area of the scrollable ancestor. If false, the element will be aligned to the nearest edge of the visible area of the scrollable ancestor. Depending on which edge of the visible area is closest to the element, either the top of the element will be aligned to the top edge of the visible area, or the bottom edge of the...
...f the scrollable ancestor. Depending on which edge of the visible area is closest to the element, either the top of the element will be aligned to the top edge of the visible area, or the bottom edge of the element will be aligned to the bottom edge of the visible area. Example var element = document.getElementById("my-el"); element.scrollIntoViewIfNeeded(); element.scrollIntoViewIfNeeded(true); // Centers the element in the visible area Specifications Not part of any specification. This is a proprietary, WebKit-specific method. ...
Element.setAttribute() - Web APIs
name A DOMString specifying the name of the attribute whose value is to be set. The attribute name is automatically converted to all lower-case when setAttribute() is called on an HTML element in an HTML document. value A DOMString containing the value to assign to the attribute. Any non-string value specified is converted automatically into a string. Boolean attributes are considered to be true if they're present on the element at all, regardless of their actual value; as a rule, you should specify the empty string ("") in value (some people use the attribute's name; this works but is non-standard). See the example below for a practical demonstration. Since the specified value gets converted into a string, specifying null doesn't necessarily do what you expect. Instead of removing the ...
...ttribute's value to "helloButton". You can see this using your browser's page inspector (Chrome, Edge, Firefox, Safari). To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled. DOM methods dealing with element's attributes: Not namespace-aware, most commonly used methods Namespace-aware variants (DOM Level 2) DOM Level 1 methods for dealing with Attr nodes dire...
Using Fetch - Web APIs
ul A fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server-side, although this usually means permission issues or similar -- a 404 does not constitute a network error, for example. An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true. The code would look something like this: fetch('flowers.jpg') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.blob(); }) .then(myBlob => { myImage.src = URL.createObjectURL(myBlob); }) .catch(error => { console.error('There has been a problem with your fetch operation:', error); }); Supplying your ...
...('X-Custom-Header', 'ProcessThisImmediately'); The same can be achieved by passing an array of arrays or an object literal to the constructor: const myHeaders = new Headers({ 'Content-Type': 'text/plain', 'Content-Length': content.length.toString(), 'X-Custom-Header': 'ProcessThisImmediately' }); The contents can be queried and retrieved: console.log(myHeaders.has('Content-Type')); // true console.log(myHeaders.has('Set-Cookie')); // false myHeaders.set('Content-Type', 'text/html'); myHeaders.append('X-Custom-Header', 'AnotherValue'); console.log(myHeaders.get('Content-Length')); // 11 console.log(myHeaders.get('X-Custom-Header')); // ['ProcessThisImmediately', 'AnotherValue'] myHeaders.delete('X-Custom-Header'); console.log(myHeaders.get('X-Custom-Header')); // [ ] Some of the...
FileSystemDirectoryEntry - Web APIs
r creating the parent directory. Example In the following code snippet, we create a directory called "Documents." // Taking care of the browser-specific prefixes. window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.directoryEntry = window.directoryEntry || window.webkitDirectoryEntry; ... ...
...ments." // Taking care of the browser-specific prefixes. window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.directoryEntry = window.directoryEntry || window.webkitDirectoryEntry; ... 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. Methods This interface inherits methods...
FileSystemFlags.create - Web APIs
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. true false Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. ...
...lse Path exists The existing file or directory is removed and replaced with a new one, then the successCallback is called with a FileSystemFileEntry or a FileSystemDirectoryEntry, as appropriate. true false Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. true true Path exists The errorCallback is called with an appropriate error, such as FileError.PATH_EXISTS_ERR. true true Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. [1] When create is false, the value of exclusive is irrelevant and ignored. Specificati...
FileSystemFlags.exclusive - Web APIs
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. true false Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. ...
...lse Path exists The existing file or directory is removed and replaced with a new one, then the successCallback is called with a FileSystemFileEntry or a FileSystemDirectoryEntry, as appropriate. true false Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. true true Path exists The errorCallback is called with an appropriate error, such as FileError.PATH_EXISTS_ERR. true true Path doesn't exist The file or directory is created, then a FileSystemFileEntry or a FileSystemDirectoryEntry is passed to the successCallback, as appropriate. [1] When create is false, the value of exclusive is irrelevant and ignored. Specificati...
Gamepad.buttons - Web APIs
Web › API › Gamepad › buttons
uttons property of the Gamepad interface returns an array of gamepadButton objects representing the buttons present on the device. Each entry in the array is 0 if the button is not pressed, and non-zero (typically 1.0) if the button is pressed. 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). The value property is a floating point value used to enable representing analog buttons, such as the triggers on many modern gamepads. The values are normalized to the range 0.0 - 1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. Syntax readonly attribute GamepadButton[] buttons; Example The following ...
...ion gameLoop() { if(navigator.webkitGetGamepads) { var gp = navigator.webkitGetGamepads()[0]; if(gp.buttons[0] == 1) { b--; } else if(gp.buttons[1] == 1) { a++; } else if(gp.buttons[2] == 1) { b++; } else if(gp.buttons[3] == 1) { a--; } } else { var gp = navigator.getGamepads()[0]; if(gp.buttons[0].value > 0 || gp.buttons[0].pressed == true) { b--; } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed == true) { a++; } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed == true) { b++; } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed == true) { a--; } } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; var start = rAF(gameLoop); }; Value An array of gam...
GamepadButton - Web APIs
dButton.value Read only A double value used to represent the current state of analog buttons, such as the triggers on many modern gamepads. The values are normalized to the range 0.0 --1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed. GamepadButton.pressed Read only A Boolean value indicating whether the button is currently pressed (true) or unpressed (false). Example The following code is taken from my Gamepad API button demo (you can view the demo live, and find the source code on Github.) Note the code fork -- in Chrome Navigator.getGamepads needs a webkit prefix and the button values are stored as an array of double values, whereas in Firefox Navigator.getGamepads doesn't need a prefix, and the button values are stored as ...
...ion gameLoop() { if(navigator.webkitGetGamepads) { var gp = navigator.webkitGetGamepads()[0]; if(gp.buttons[0] == 1) { b--; } else if(gp.buttons[1] == 1) { a++; } else if(gp.buttons[2] == 1) { b++; } else if(gp.buttons[3] == 1) { a--; } } else { var gp = navigator.getGamepads()[0]; if(gp.buttons[0].value > 0 || gp.buttons[0].pressed == true) { b--; } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed == true) { a++; } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed == true) { b++; } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed == true) { a--; } } ball.style.left = a*2 + "px"; ball.style.top = b*2 + "px"; var start = rAF(gameLoop); }; Specifications ...
Using the Gamepad API - Web APIs
he Array returned by Navigator.getGamepads(). var gamepads = {}; function gamepadHandler(event, connecting) { var gamepad = event.gamepad; // Note: // gamepad === navigator.getGamepads()[gamepad.index] if (connecting) { gamepads[gamepad.index] = gamepad; } else { delete gamepads[gamepad.index]; } } window.addEventListener("gamepadconnected", function(e) { gamepadHandler(e, true); }, false); 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. Querying the Gamepad object As you can see, the gamepad events discussed above include a gamepad property on the even...
...ating whether the browser has remapped the controls on the device to a known layout. Currently there is only one supported known layout -- the standard gamepad. If the browser is able to map controls on the device to that layout the mapping property will be set to the string standard. connected: A boolean indicating whether the gamepad is still connected to the system. If this is so the value is True; if not, it is False. buttons: An array of GamepadButton objects representing the buttons present on the device. 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). The value property is a floating point value used to enable representing analog buttons, such as the trigge...
Geolocation.getCurrentPosition() - Web APIs
tional callback function that takes a GeolocationPositionError object as its sole input parameter. options Optional An optional PositionOptions object. Options includes: maximumAge: integer (milliseconds) | infinity - maximum cached position age. timeout: integer (milliseconds) - amount of time before the error callback is invoked, if 0 it will never invoke. ...
...ror object as its sole input parameter. options Optional An optional PositionOptions object. Options includes: maximumAge: integer (milliseconds) | infinity - maximum cached position age. timeout: integer (milliseconds) - amount of time before the error callback is invoked, if 0 it will never invoke. ...
GeolocationCoordinates.heading - Web APIs
If GeolocationCoordinates.speed is 0, heading is NaN. If the device is not able to provide heading information, this value is null. ...
...If GeolocationCoordinates.speed is 0, heading is NaN. If the device is not able to provide heading information, this value is null. ...
GlobalEventHandlers.onerror - Web APIs
ndow.addEventListener (not only capturing)). When a resource (such as an <img> or <script>) fails to load, an error event using interface Event is fired at the element that initiated the load, and the onerror() handler on the element is invoked. These error events do not bubble up to window, but (at least in Firefox) can be handled with a window.addEventListener configured with useCapture set to True. Installing a global error event handler is useful for automated collection of error reports. Syntax For historical reasons, different arguments are passed to window.onerror and element.onerror handlers (as well as on error-type window.addEventListener handlers). window.onerror window.onerror = function(message, source, lineno, colno, error) { ... }; Function parameters: message: error...
...e, source, lineno, colno, error) { ... }; Function parameters: message: error message (string). Available as event (sic!) in HTML onerror="" handler. source: URL of the script where the error was raised (string) lineno: Line number where error was raised (number) colno: Column number for the line where the error occurred (number) error: Error Object (object) When the function returns true, this prevents the firing of the default event handler. window.addEventListener('error') window.addEventListener('error', function(event) { ... }) event of type ErrorEvent contains all the information about the event and the error. element.onerror element.onerror = function(event) { ... } element.onerror accepts a function with a single argument of type Event. A good example for this is ...
GlobalEventHandlers.onkeypress - Web APIs
ype the word "exit" in any point of your page... */ (function () { const sSecret = /* Choose your hidden word...: */ "exit"; let nOffset = 0; document.onkeypress = function(oPEvt) { let oEvent = oPEvt || window.event, nChr = oEvent.charCode, sNodeType = oEvent.target.nodeName.toUpperCase(); if (nChr === 0 || oEvent.target.contentEditable.toUpperCase() === "TRUE" || sNodeType === "TEXTAREA" || sNodeType === "INPUT" && oEvent.target.type.toUpperCase() === "TEXT") { return true; } if (nChr !== sSecret.charCodeAt(nOffset)) { nOffset = nChr === sSecret.charCodeAt(0) ? 1 : 0; } else if (nOffset < sSecret.length - 1) { nOffset++; } else { nOffset = 0; /* Do something here... */ alert("Yesss!!
....target.type.toUpperCase() === "TEXT") { return true; } if (nChr !== sSecret.charCodeAt(nOffset)) { nOffset = nChr === sSecret.charCodeAt(0) ? 1 : 0; } else if (nOffset < sSecret.length - 1) { nOffset++; } else { nOffset = 0; /* Do something here... */ alert("Yesss!!!"); location.assign("https://developer.mozilla.org/"); } return true; }; })(); Note: A more complete framework for capturing the typing of hidden words is available on GitHub. Specifications Specification Status Comment HTML Living StandardThe definition of 'onkeypress' in that specification. Living Standard ...
HTMLCanvasElement.getContext() - Web APIs
izing the canvas paint cycle from the event loop (Gecko only) willReadFrequently: Boolean that indicates whether or not a lot of read-back operations are planned. This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling getImageData() frequently. This option is only available, if the flag gfx.canvas.willReadFrequently.enable is set to true (which, by default, is only the case for B2G/Firefox OS). (Blink only) storage: String that indicates which storage is used ("persistent" by default). WebGL context attributes: alpha: Boolean that indicates if the canvas contains an alpha buffer. desynchronized: Boolean that hints the user agent to reduce the latency by desynchronizing the canvas paint cycle from the event loop a...
...figuration is most suitable. This is the default value. "high-performance": Prioritizes rendering performance over power consumption. "low-power": Prioritizes power saving over rendering performance. premultipliedAlpha: Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. preserveDrawingBuffer: If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. stencil: Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits. Return value A RenderingContext which is either a CanvasRenderingContext2D for "2d", WebGLRenderingContext for "webgl" and "experimental-webgl", WebGL2RenderingContext for "webgl2" ...
HTMLCanvasElement.mozOpaque - Web APIs
r or not translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized. This has been standardized as setting the alpha option to false when creating a drawing context with HTMLCanvasElement.getContext(). Use of mozOpaque should be avoided. Firefox will stop supporting it in the future. Syntax var opaque = canvas.mozOpaque; canvas.mozOpaque = true; Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300" moz-opaque></canvas> You can get or set the mozOpaque property. For example, you could conditionally set it to true if mimeType == 'image/jpeg', or similar, to gain performance in your application when translucency is not needed. var canvas = document.getElementById('canvas'); console.log(canvas.mozOpaque);...
...Examples Given this <canvas> element: <canvas id="canvas" width="300" height="300" moz-opaque></canvas> You can get or set the mozOpaque property. For example, you could conditionally set it to true if mimeType == 'image/jpeg', or similar, to gain performance in your application when translucency is not needed. var canvas = document.getElementById('canvas'); console.log(canvas.mozOpaque); // true // deactivate it canvas.mozOpaque = false; Specifications Not part of any standard. ...
HTMLDialogElement.open - Web APIs
false means it not set, and therefore the dialog is not shown. The property is now read only -- it is possible to set the value to programmatically show or hide the dialog. ...
...false means it not set, and therefore the dialog is not shown. The property is now read only -- it is possible to set the value to programmatically show or hide the dialog. ...
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. ...
... The HTMLElement.isContentEditable read-only property returns a Boolean that is true if the contents of the element are editable; otherwise it returns false. ...
HTMLFormElement - Web APIs
rm should not be validated. Named inputs are added to their owner form instance as properties, and can overwrite native properties if they share the same name (e.g. a form with an input named action will have its action property return that input instead of the form's action HTML attribute). Methods This interface also inherits methods from its parent, HTMLElement. 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. Fires an event named invalid at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to false. reportValidity() Retu...
...the element's child controls are subject to constraint validation and satisfy those contraints; returns false if some controls do not satisfy their constraints. Fires an event named invalid at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to false. reportValidity() Returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user. requestSubmit() Requests that the form be submitted using the specified submit button and its corresponding configuration. reset() Resets the form to its initial state. submit() Submits the ...
HTMLImageElement.alt - Web APIs
y an empty string (""). For compatibility reasons, browsers generally will accept an image without an alt attribute, but you should try to get into the habit of using it. Usage notes The fundamental guideline for the alt attribute is that every image's alternate text should be able to replace the image without altering the meaning of the page. You should never use alt for text that could be construed as a caption or title. There are separate attributes and elements designed for those purposes. Examples Beyond that, there are additional guidelines for using alt appropriately which vary depending on what the image is being used for. These are shown in the examples below. Decorative images Images with no semantic meaning--such as those which are solely decorative--or of limited informationa...
...s"</a> <a href="artists.html" aria-role="button"><img src="artisticon.svg" alt="Artists"</a> <a href="playlists.html" aria-role="button"><img src="playlisticon.svg" alt="Playlists"</a> </li> Images containining diagrams or maps When an image contains information presented as a diagram, chart, graph, or map, the alt text should provide the same information, at least in summary form. This is true whether the /me image is in a bitmapped format such as PNG or JPEG or in a vector format like SVG. For a map, the alt text could be directions to the place indicated by the map, similarly to how you would explain it verbally. For a chart, the text could describe the items in the chart and their values. For a diagram, the text could be an explanation of the concept presented by the diagram. ...
HTMLImageElement.complete - Web APIs
The srcset attribute is absent and the src attribute, while specified, is the empty string (""). ...
... The srcset attribute is absent and the src attribute, while specified, is the empty string (""). ...
HTMLImageElement.currentSrc - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support YesSafari Full support 10.1WebView Android Full support 45Chrome Android Full support ...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support 10.3Samsung Internet Android Full support 5.0Legend Full support Full support ...
HTMLImageElement.srcset - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 21Safari Full support 8WebView Android Full support 37Chrome Android Full support 34...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support 8Samsung Internet Android Full support 2.0Legend Full support Full support ...
HTMLMediaElement.autoplay - Web APIs
The HTMLMediaElement.autoplay property reflects the autoplay HTML attribute, indicating whether playback should automatically begin as soon as enough media is available to do so without interruption. A media element whose source is a MediaStream and whose autoplay property is true will begin playback when it becomes active (that is, when MediaStream.active becomes true). Note: Sites which automatically play audio (or videos with an audio track) can be an unpleasant experience for users, so it should be avoided when possible. If you must offer autoplay functionality, you should make it opt-in (requiring a user to specifically enable it). However, autoplay can be useful when creating media elements whose source will be set at a later time, under user control. For a much more in-depth look ...
... (requiring a user to specifically enable it). However, autoplay can be useful when creating media elements whose source will be set at a later time, under user control. For a much more in-depth look at autoplay, autoplay blocking, and how to respond whena autoplay is blocked by the user's browser, see our article Autoplay guide for media and Web Audio 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. Note: Some browsers offer users the ability to override autoplay in order to prevent disruptive audio or video from playing without permission or in the background. Do not rely on autopl...
HTMLMediaElement: pause event - Web APIs
The pause event is sent when a request to pause an activity is handled and the activity has entered its paused state, most commonly after the media has been paused through a call to the element's pause() method. The event is sent once the pause() method returns and after the media element's paused property has been changed to true. General info Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onpause Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's pause event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = docu...
...entHandlers.onpause Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's pause event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('pause', (event) => { console.log('The Boolean paused property is now true. Either the ' + 'pause() method was called or the autoplay attribute was toggled.'); }); Using the onpause event handler property: const video = document.querySelector('video'); video.onpause = (event) => { console.log('The Boolean paused property is now true. Either the ' + 'pause() method was called or the autoplay attribute was toggled.'); }; Specifications Specification ...
HTMLMediaElement.srcObject - Web APIs
Usage notes Older versions of the Media Source specification required using createObjectURL() to create an object URL then setting src to that URL. Now you can just set srcObject to the MediaStream directly. Examples Basic example In this example, a MediaStream from a camera is assigned to a newly-created <video> element. const mediaStream = await navigator.mediaDevices.getUserMedia({video: true}); const video = document.createElement('video'); video.srcObject = mediaStream; In this example, a new MediaSource is assigned to a newly-created <video> element. const mediaSource = new MediaSource(); const video = document.createElement('video'); video.srcObject = mediaSource; Supporting fallback to the src property The examples below support older browser versions that require you to crea...
...o.srcObject = mediaSource; Supporting fallback to the src property The examples below support older browser versions that require you to create an object URL and assign it to src if srcObject isn't supported. First, a MediaStream from a camera is assigned to a newly-created <video> element, with fallback for older browsers. const mediaStream = await navigator.mediaDevices.getUserMedia({video: true}); const video = document.createElement('video'); if ('srcObject' in video) { video.srcObject = mediaStream; } else { // Avoid using this in new browsers, as it is going away. video.src = URL.createObjectURL(mediaStream); } Second, a new MediaSource is assigned to a newly-created <video> element, with fallback for older browsers and browsers that don't yet support assignment of MediaSourc...
HTMLMediaElement - Web APIs
s, when the audio info is known, but before the audio has started or MozAudioAvailable events have begun firing. HTMLMediaElement.mozSampleRate Read only Returns a double representing the number of samples per second that will be played. For example, 44100 samples per second is the sample rate used by CD audio. HTMLMediaElement.muted Is a Boolean that determines whether audio is muted. true if the audio is muted and false otherwise. HTMLMediaElement.networkState Read only Returns a unsigned short (enumeration) indicating the current state of fetching the media over the network. HTMLMediaElement.paused Read only Returns a Boolean that indicates whether the media element is paused. HTMLMediaElement.playbackRate Is a double that indicates the rate at which the media is being pl...
...e of the media has finished loading. loadedmetadata Fired when the metadata has been loaded loadstart Fired when the browser has started to load a resource. pause Fired when a request to pause play is handled and the activity has entered its paused state, most commonly occurring when the media's HTMLMediaElement.pause() method is called. 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. ratechange Fired when the playback rate has changed. seeked Fired when a seek operation completes seeking Fired when a seek operation begi...
Option() - Web APIs
lue of text is used as the value, e.g. for the associated <select> element's value when the form is submitted to the server. defaultSelected Optional A Boolean that sets the selected attribute value, i.e. so that this <option> will be the default value selected in the <select> element when the page is first loaded. If this is not specified, a default value of false is used. Note that a value of true does not set the option to selected if it is not already selected. selected Optional A Boolean that sets the option's selected state; the default is false (not selected). If omitted, even if the defaultSelected argument is true, the option is not selected. Examples Just add new options /* assuming we have the following HTML <select id='s'> </select> */ var s = document.getElementById('s'...
...t</option> <option>Second</option> <option>Third</option> </select> */ var s = document.getElementById('s'); var options = [ 'zero', 'one', 'two' ]; options.forEach(function(element, key) { if (element == 'zero') { s[s.options.length] = new Option(element, s.options.length, false, false); } if (element == 'one') { s[s.options.length] = new Option(element, s.options.length, true, false); // Will add the "selected" attribute } if (element == 'two') { s[s.options.length] = new Option(element, s.options.length, false, true); // Just will be selected in "view" } }); /* Result <select id="s"> <option value="0">zero</option> <option value="1" selected="">one</option> <option value="2">two</option> // User will see this as 'selected' </select> */ Specification...
HTMLElement.focus() - Web APIs
control aspects of the focusing process. This object may contain the following property: preventScroll Optional A Boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view. A value of false for preventScroll (the default) means that the browser will scroll the element into view after focusing it. If preventScroll is set to true, no scrolling will occur. Examples Focus on a text field JavaScript focusMethod = function getFocus() { document.getElementById("myTextField").focus(); } HTML <input type="text" id="myTextField" value="Text field."> <p></p> <button type="button" onclick="focusMethod()">Click me to focus on the text field!</button> Result Focus on a button JavaScript focusMethod = fun...
...ton> <p></p> <button type="button" onclick="focusMethod()">Click me to focus on the button!</button> Result Focus with focusOption JavaScript focusScrollMethod = function getFocus() { document.getElementById("myButton").focus({preventScroll:false}); } focusNoScrollMethod = function getFocusWithoutScrolling() { document.getElementById("myButton").focus({preventScroll:true}); } HTML <button type="button" onclick="focusScrollMethod()">Click me to focus on the button!</button> <button type="button" onclick="focusNoScrollMethod()">Click me to focus on the button without scrolling!</button> <div id="container" style="height: 1000px; width: 1000px;"> <button type="button" id="myButton" style="margin-top: 500px;">Click Me!</button> </div> Result Specification...
HTMLSelectElement - Web APIs
ng reflecting the index of the first selected <option> element. The value -1 indicates no element is selected. HTMLSelectElement.selectedOptionsRead only An HTMLCollection representing the set of <option> elements that are selected. HTMLSelectElement.size A long reflecting the size HTML attribute, which contains the number of visible items in the control. The default is 1, unless multiple is true, in which case it is 4. HTMLSelectElement.typeRead only A DOMString represeting the form control's type. When multiple is true, it returns "select-multiple"; otherwise, it returns "select-one". HTMLSelectElement.validationMessageRead only A DOMString representing a localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the e...
...hod explicitly. HTMLSelectElement.remove() Removes the element at the specified index from the options collection for this select element. HTMLSelectElement.reportValidity() This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns true. HTMLSelectElement.setCustomValidity() Sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does not have a custom validity error. Events Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface: input event Fires when the value of an <i...
HTMLSlotElement.assignedElements() - Web APIs
The assignedElements() property of the HTMLSlotElement interface returns a sequence of the elements assigned to this slot (and no other nodes). If the flatten option is set to true, it also returns the assigned elements of any other slots that are descendants of this slot. If no assigned nodes are found, it returns the slot's fallback content. Syntax var assignedElements = HTMLSlotElement.assignedElements(options) Parameters options Optional An object that sets options for the nodes to be returned. 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. Return value An array of elements. Examples let slots = this.shadowRoot.querySelector('slot'); let el...
...tional An object that sets options for the nodes to be returned. 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. Return value An array of elements. Examples let slots = this.shadowRoot.querySelector('slot'); let elements = slots.assignedElements({flatten: true}); Specifications Specification Status Comment HTML Living StandardThe definition of 'assignedElements()' in that specification. Living Standard Browser Compatibility The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us...
HTMLSlotElement.assignedNodes() - Web APIs
Defaults to false. ...
... are descendants of this slot. If no assigned nodes are found, it returns the slot's fallback content. Syntax var assignedNodes = HTMLSlotElement.assignedNodes(options) Parameters options Optional An object that sets options for the nodes to be returned. 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. Return value An array of nodes. Examples The following snippet is taken from our slotchange example (see it live also). let slots = this.shadowRoot.querySelectorAll('slot'); slots[1].addEventListener('slotchange', function(e) { let nodes = slots[1].assignedNodes(); console.log('Element in Slot "' + slots[1].name + '" changed to "' + nodes[0].outer...
HTMLTextAreaElement - Web APIs
ity Read only ValidityState object: Returns the validity states that this element is in. value string: Returns / Sets the raw value contained in the control. willValidate Read only boolean: Returns whether the element is a candidate for constraint validation. false if any conditions bar it from constraint validation, including its readOnly or disabled property is true. wrap string: Returns / Sets the wrap HTML attribute, indicating how the control wraps text. HTMLTextAreaElement.labelsRead only NodeList: Returns a list of label elements associated with this element. The two properties tabIndex and accessKey are inherited from HTMLElement from HTML5 on, but were defined on HTMLTextAreaElement in DOM Level 2 HTML and earlier ...
... setRangeText() Replaces a range of text in the element with new text. setSelectionRange() Selects a range of text in the element (but does not focus it). checkValidity() Returns false if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires a cancelable invalid event at the control. It returns true if the control is not a candidate for constraint validation, or if it satisfies its constraints. reportValidity() This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable invalid event at the element, and returns false; if there are no problems, it returns true. setCustomValidity(DOMstring...
HTMLVideoElement.msHorizontalMirror - Web APIs
also be large incompatibilities between implementations and the behavior may change in the future. msHorizontalMirror is a read/write property which gets or sets whether a video element is flipped horizontally in the display. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax HTMLVideoElement.msHorizontalMirror: boolean; Value Boolean value set to true flips the video playback horizontally. Video perspective is flipped on a horizontal axis - this may be useful for playback of a webcam video, providing the user with better mirroring of their real behaviors (ie. when user moves left, their representation on-screen would move left as well). Example var myVideo = document.getElementById("videoTag1"); myVideo.msHorizontalMirror = tr...
...ter mirroring of their real behaviors (ie. when user moves left, their representation on-screen would move left as well). ...
HTMLVideoElement.msInsertVideoEffect() - Web APIs
ideoEffect() method inserts the specified video effect into the media pipeline. This proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax str = HTMLMediaElement.msInsertVideoEffect(activatableClassId: DOMString, effectRequired: boolean, config); Parameters activatableClassId A DOMString defining the video effects class. ...
...ing the video effects class. effectRequired A Boolean which if set to true requires a video effect to be defined. configOptional An optional Object to help with defining any additional configuration needed. Return value This method does not return a value. ...
HTMLVideoElement.msIsLayoutOptimalForPlayback - Web APIs
be large incompatibilities between implementations and the behavior may change in the future. msIsLayoutOptimalForPlayback is a read-only property which indicates whether the video can be rendered more efficiently. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax HTMLVideoElement.msIsLayoutOptimalForPlayback: DOMString; Value Boolean value set to true indicates that video is being rendered optimally (better performance and using less battery power). If false, improvements can be made to optimize performance. For msIsLayoutOptimalForPlayback to be true, avoid the following: Video elements with Cascading Style Sheets (CSS) outlines set. Rendering a video element through a canvas element. Embedding video elements in a Scalable Vector Graphi...
...id the following: Video elements with Cascading Style Sheets (CSS) outlines set. Rendering a video element through a canvas element. Embedding video elements in a Scalable Vector Graphics (SVG). You can listen to the onMSVideoOptimalLayoutChanged event to be notified when the msIsLayoutOptimalForPlayback property changes. *To enable Stereo 3D playback, msIsLayoutOptimalForPlayback must be true. See also HTMLVideoElement Microsoft API extensions ...
The HTML DOM API - Web APIs
ch sent or is sending server-sent events. EventSource Examples In this example, an <input> element's input event is monitored in order to update the state of a form's "submit" button based on whether or not a given field currently has a value. ...
...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. With these, we can access the properties and methods that provide information about and grant control over these elements. The HTMLInputElement object for the "Send" button's disabled property is set to true, which disables the ...
HTML Drag and Drop API - Web APIs
Each data item is a string of a particular type -- typically a MIME type such as text/html. Each drag event has a dataTransfer property that holds the event's data. This prope...
... This event fires regardless of whe...
IDBDatabase.createObjectStore() - Web APIs
s object whose attributes are optional parameters to the method. It includes the following properties: Attribute Description keyPath The key path to be used by the new object store. If empty or not specified, the object store is created without a key path and uses out-of-line keys. You can also pass in an array as a keyPath. autoIncrement If true, the object store has a key generator. Defaults to false. Unknown parameters are ignored. Returns A new IDBObjectStore. Exceptions This method may raise a DOMException with a DOMError of one of the following types: Exception Description InvalidStateError Occurs if the method was not called from a versionchange transaction callback. For older WebKit b...
...'t exist (e.g. has been deleted or removed.) In Firefox previous to version 41, an InvalidStateError was raised in this case as well, which was misleading; this has now been fixed (see bug 1176165.) ConstraintError An object store with the given name (based on case-sensitive comparison) already exists in the connected database. InvalidAccessError If autoIncrement is set to true and keyPath is either an empty string or an array containing an empty string. Example // Let us open our database var request = window.indexedDB.open("toDoList", 4); // This handler is called when a new version of the database // is created, either when one has not been created before // or when a new version number is submitted by calling // window.indexedDB.open(). // This handler is o...
IDBKeyRange.includes() - Web APIs
The key you want to check for in your key range. This can be any type. Return value A Boolean. Exceptions This method may raise a DOMException of the following type: Attribute Description DataError The supplied key was not a valid key. Example var keyRangeValue = IDBKeyRange.bound('A', 'K', false, false); var myResult = keyRangeValue.includes('F'); // Returns true var myResult = keyRangeValue.includes('W'); // Returns false Polyfill The includes() method was added in the second edition of the Indexed DB specification. For browsers that do not support it, the following polyfill can be used. IDBKeyRange.prototype.includes = IDBKeyRange.prototype.includes || function(key) { var r = this, c; if (r.lower !== undefined) { c = indexedDB.cmp(key, r.lo...
... Recommendation Indexed Database API DraftThe definition of 'includes()' in that specification. Recommendation Browser compatibility The compatibility table on this page is generated from structured data. If you'...
IDBObjectStore.createIndex() - Web APIs
that it is possible to create an index with an empty name. keyPath The key path for the index to use. Note that it is possible to create an index with an empty keyPath, and also to pass in a sequence (array) as a keyPath. objectParameters Optional An IDBIndexParameters object, which can include the following properties: Attribute Description unique If true, the index will not allow duplicate values for a single key. multiEntry If true, the index will add an entry in the index for each array element when the keyPath resolves to an Array. If false, it will add one single entry containing the Array. locale Currently Firefox-only (43+), this allows you to specify a locale for the index. Any sorting operations perfo...
... An IDBIndex object: the newly created index. Exceptions This method may raise a DOMException of one of the following types: Exception Description ConstraintError Occurs if an index with the same name already exists in the database. Index names are case-sensitive. InvalidAccessError Occurs if the provided key path is a sequence, and multiEntry is set to true in the objectParameters object. InvalidStateError Occurs if either: The method was not called from a versionchange transaction mode callback, i.e. from inside a IDBOpenDBRequest.onupgradeneeded handler. The object store has been deleted. SyntaxError Occurs if the provided keyPath is not a valid key path. TransactionInactiveError Oc...
IDBObjectStoreSync - Web APIs
ta being stored could not be serialized by the internal structured cloning algorithm. createIndex() Creates and returns a new index with the given name in the connected database. IDBIndexSync createIndex ( in DOMString name, in DOMString keypath, in optional boolean unique ); Parameters name The name of a new index. keyPath The key path used by the new index. unique If true, keys in the index must be unique; if false, duplicate keys are allowed. Returns IDBIndexSync An object to access the newly created index. get() Retrieves and returns the value from this object store for the record that corresponds to the given key. any get ( in any key ) raises (IDBDatabaseException); Parameters key The key that identifies the record to be retrieved. Returns ...
... the given key, it is overwritten. any put ( in any value, in optional any key ) raises (IDBDatabaseException); Parameters value The value to be stored in the record. key The key to be used to identify the record. Returns any The key for the stored record. Exceptions This method can raise an IDBDatabaseException with the following codes: CONSTRAINT_ERR If noOverwrite was true, and a record exists in this index for the given key or this index is auto-populated; or if no record exists with the given key in the index's referenced object store. DATA_ERR If this object store uses out-of-line keys and no key generator, but no key was given. SERIAL_ERR If the data being stored could not be serialized by the internal structured cloning algorithm. remove() Removes from ...
IdleDeadline.didTimeout - Web APIs
Idle callbacks support the concept of a timeout in order to ensure that whatever task they're meant to perform actually happens, even if the user agent never has enough idle time available. ...
...heck the value of didTimeout if it needs to perform an action even if the browser is too busy to grant you the time; you should react by performing the needed task or, ideally, a minimal amount of work that can be done to keep things moving along, then schedule a new callback to try again to get the rest of the work done. 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. Example See our complete example in the article Cooperative Scheduling of Background Tasks API. Specifications Specification Status Comment Cooperative Scheduling of Background Tasks Propose...
KeyboardEvent.code - Web APIs
Handle keyboard events in a game This example establishes an event listener for keydown events that handle keyboard input for a game that uses the typical "WASD" keyboard layout for steering forward, left, backward, and right. This will use the same four keys physically regardless of...
... There are several ways this code can be made better. Most real games would watch for keydown events, start motion when that happens, and stop the motion when the corresponding keyup occurs, instead of relying on key repeats. That would allow both smoother and faste...
KeyboardEvent.keyCode - Web APIs
ent is usually better (at least when Gecko is the runtime in use). See Gecko Keypress Event for details. 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. ...
...indow.addEventListener("keydown", function (event) { if (event.defaultPrevented) { return; // Should do nothing if the default action has been cancelled } var handled = false; if (event.key !== undefined) { // Handle the event with KeyboardEvent.key and set handled true. } else if (event.keyCode !== undefined) { // Handle the event with KeyboardEvent.keyCode and set handled true. } if (handled) { // Suppress "double action" if event handled event.preventDefault(); } }, true); Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.keyCode' in that specification. Obsolete Initial definition; specified as deprecated ...
LargestContentfulPaint - Web APIs
LargestContentfulPaint.toJSON() Returns the above properties as JSON. Examples The following example shows how to create a PerformanceObserver that listens for largest-contentful-paint entries and logs the LCP value to the console. This example also demonstrates how to include buffered entries (those that ocurred before observer() was called), which is done by setting the buffered option to true. Note that in this example data is only sent to the server when the user leaves the tab. // Catch errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let lcp; const po = new PerformanceObserver((entryList) => { const entries = entryList.getEntries(); const lastEntry = entries[entries.length - 1]; // Update ...
...Entry = entries[entries.length - 1]; // Update `lcp` to the latest value, using `renderTime` if it's available, // otherwise using `loadTime`. (Note: `renderTime` may not be available on // image elements loaded cross-origin without the `Timing-Allow-Origin` header.) lcp = lastEntry.renderTime || lastEntry.loadTime; }); po.observe({type: 'largest-contentful-paint', buffered: true}); // Send data to the server. addEventListener('visibilitychange', function fn() { if (lcp && document.visibilityState === 'hidden') { console.log('LCP:', lcp); removeEventListener('visibilitychange', fn, true); } }, true); } catch (e) { // Do nothing if the browser doesn't support this API. } Specifications Specification Status Comment Lar...
LayoutShift - Web APIs
The LayoutShift interface of the Layout Instability API provides insights into the stability of web pages based on movements of the elements on the page. Properties LayoutShift.value Returns the impact fraction (fraction of the viewport that was shifted) times the distance fraction (distance moved as a fraction of viewport). LayoutShift.hadRecentInput Returns true if there was a user input in the past 500 milliseconds. LayoutShift.lastInputTime Returns the time of the most recent user input. LayoutShift.sources Returns an array of LayoutShiftAttribution objects with information on the elements that were shifted. Methods LayoutShift.toJSON() Converts the properties to JSON. Examples The following example shows how to capture layout shifts and log them to the console.
...https://bugs.webkit.org/show_bug.cgi?id=209216 try { let cumulativeLayoutShiftScore = 0; const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { // Only count layout shifts without recent user input. if (!entry.hadRecentInput) { cumulativeLayoutShiftScore += entry.value; } } }); observer.observe({type: 'layout-shift', buffered: true}); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') { // Force any pending records to be dispatched. observer.takeRecords(); observer.disconnect(); console.log('CLS:', cumulativeLayoutShiftScore); } }); } catch (e) { // Do nothing if the browser doesn't support this API. } Specifications Specification Statu...
LockManager.request() - Web APIs
nsactions which have the same semantics. Syntax LockManager.request(var promise = name[, {options}], callback) Parameters name An identifier for the lock you want to request. options Optional An object describing characteristics of the lock you want to create. Valid values are: mode Optional: Either "exclusive" or "shared". The default value is "exclusive". ifAvailable Optional: If true, the lock request will only be granted if it is not already held. If it cannot be granted, the callback will be invoked with null instead of a Lock instance. The default value is false. steal Optional: If true, then any held locks with the same name will be released, and the request will be granted, preempting any queued requests for it. The default value is false. signal Optional: An AbortSi...
.../ Write code here. }); } ifAvailable Example To grab a lock only if it isn't already being held, use the ifAvailable option. In this function await means the method will not return until the callback is complete. Since the lock is only granted if it was available, this call avoids needing to wait on the lock being released elsehwere. await navigator.locks.request('my_resource', {ifAvailable: true}, async lock => { if (!lock) { // The lock was not granted - get out fast. return; } // The lock was granted, and no other running code in this origin is holding // the 'my_res_lock' lock until this returns. }); signal Example To only wait for a lock for a short period of time, use the signal option. const controller = new AbortController(); // Wait at most 200ms. setTimeout(...
MediaQueryList - Web APIs
t object stores information on a media query applied to a document, with support for both immediate and event-driven matching against the state of the document. You can create a MediaQueryList by calling matchMedia() on the window object. The resulting object handles sending notifications to listeners when the media query state changes (i.e. when the media query test starts or stops evaluating to true). This is very useful for adaptive design, since this makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, and allows you to programmatically make changes to a document based on media query status. Properties The MediaQueryList interface inherits properties from its parent interface, EventTarget. matchesRead only A Bo...
...eful for adaptive design, since this makes it possible to observe a document to detect when its media queries change, instead of polling the values periodically, and allows you to programmatically make changes to a document based on media query status. Properties The MediaQueryList interface inherits properties from its parent interface, EventTarget. matchesRead only A Boolean that returns true if the document currently matches the media query list, or false if not. mediaRead only A DOMString representing a serialized media query. Methods The MediaQueryList interface inherits methods from its parent interface, EventTarget. addListener() Adds to the MediaQueryList a callback which is invoked whenever the media query status--whether or not the document matches the media queries ...
MediaRecorder: dataavailable event - Web APIs
all the possible reasons this event may raise, see the documentation for the event handler property: ondataavailable. Examples Using addEventListener to listen for dataavailable events: ... var chunks = []; mediaRecorder.addEventListener('stop', (event) => { console.log("data available after MediaRecorder.stop() called."); var audio = document.createElement('audio'); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); }); mediaRecorder.addEventListener('dataavailable', (event) => { chunks.push(event.data); }); ... The same, but using the ondataavailable event handler property: ... var chunks = []; mediaRecorder.onstop = func...
...; console.log("recorder stopped"); }); mediaRecorder.addEventListener('dataavailable', (event) => { chunks.push(event.data); }); ... The same, but using the ondataavailable event handler property: ... var chunks = []; mediaRecorder.onstop = function(e) { console.log("data available after MediaRecorder.stop() called."); var audio = document.createElement('audio'); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); } mediaRecorder.ondataavailable = function(e) { chunks.push(e.data); } ... Specifications Specification Status MediaStream Recording Working Draft ...
MediaRecorder: error event - Web APIs
Bubbles No Cancelable No Interface MediaRecorderErrorEvent Event handler property onerror For details of the all the possible errors see the documentation for the event handler property: onerror. ...
...vices.getUserMedia({audio: true}); const recorder = new MediaRecorder(stream); recorder.addEventListener('error', (event) => { console.error(`error recording stream: ${event.error.name}`) }); recorder.start(); } record(); The same, but using the onerror event handler property: async function record() { const stream = await navigator.mediaDevices.getUserMedia({audio: true}); const recorder = new MediaRecorder(stream); recorder.onerror = (event) => { console.error(`error recording stream: ${event.error.name}`) }; recorder.start(); } record(); Specifications Specification Status MediaStream Recording Working Draft ...
MediaRecorder.isTypeSupported - Web APIs
Recording may still fail if there are insufficient resources to support the recording and encoding process. If the value is false, the user agent is incapable of recording the specified format. ...
...Recording may still fail if there are insufficient resources to support the recording and encoding process. If the value is false, the user agent is incapable of recording the specified format. ...
MediaRecorder - Web APIs
ese events using addEventListener() or by assigning an event listener to the oneventname property of this interface. error Fired when an error occurs: for example because recording wasn't allowed or was attempted using an unsupported codec. Also available via the onerror property. ...
...document.createElement('button'); clipContainer.classList.add('clip'); audio.setAttribute('controls', ''); deleteButton.innerHTML = "Delete"; clipLabel.innerHTML = clipName; clipContainer.appendChild(audio); clipContainer.appendChild(clipLabel); clipContainer.appendChild(deleteButton); soundClips.appendChild(clipContainer); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); chunks = []; var audioURL = URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); deleteButton.onclick = function(e) { evtTgt = e.target; evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode); } } mediaRecorder.ondataavailable =...
MediaSessionActionDetails.fastSeek - Web APIs
The Boolean property fastSeek in the MediaSessionActionDetails dictionary is an optional value which, when specified and true, indicates that the requested seekto operation is part of an ongoing series of seekto operations. Your handler should take steps to return as quickly as possible by skipping any steps of its operation which are only necessary when the seek operation is complete. 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. ...
...ing any steps of its operation which are only necessary when the seek operation is complete. 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. Syntax let mediaSessionActionDetails = { fastSeek: shouldFastSeek }; let shouldFastSeek = mediaSessionActionDetails.fastSeek; Value A Boolean which is true if the action is part of an ongoing series of seek actions which should be treated as part of an overall seek operation. If the value is false or this property isn't present, the seek is final. Specifications Specification Status Comment Media Session StandardThe definition of 'MediaSessionActionDetails.fastSeek' in that specification. Draft Initial definition. ...
MediaStream.getAudioTracks() - Web APIs
the type for each entry in the list of audio streams; however, this has since been merged into the main MediaStreamTrack interface. Example This example gets a webcam's audio and video in a stream using getUserMedia(), attaches the stream to a <video> element, then sets a timer that, upon expiring, will stop the first audio track found on the stream. ...
...each entry in the list of audio streams; however, this has since been merged into the main MediaStreamTrack interface. Example This example gets a webcam's audio and video in a stream using getUserMedia(), attaches the stream to a <video> element, then sets a timer that, upon expiring, will stop the first audio track found on the stream. navigator.mediaDevices.getUserMedia({audio: true, video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; // Stop the audio stream after 5 seconds setTimeout(() => { const tracks = mediaStream.getAudioTracks() tracks[0].stop() }, 5000) }) Specifications Specification Status Comment Media Capture and StreamsThe definition of 'getAudioTracks()' in that specification. Candi...
MediaStream.id - Web APIs
Web › API › MediaStream › id
Candidate Recommendation Initial definition. ...
... Candidate Recommendation Initial definition. ...
MediaStreamTrack.enabled - Web APIs
This can be used to intentionally mute a track. When enabled, a track's data is output from the source to the destination; otherwise, empty frames are output. In the case of audio, a disabled track generates frames of silence (that is, frames in which every sample's value is 0). For video tracks, every frame is filled entirely with black pixels. ...
...nts what a typical user would consider the muting state for a track, whereas the muted property indicates a state in which the track is temporarily unable to output data, such as a scenario in which frames have been lost in transit. Note: If the track has been disconnected, the value of this property can be changed, but has no effect. 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. Empty audio frames have every sample's value set to 0. Empty video frames have every pixel set to black. Note: When implementing a mute/unmute feature, you should use the enabled property. Usage notes If the ...
Recording a media element - Web APIs
This works by calling MediaStream.getTracks(), using forEach() to call MediaStreamTrack.stop() on each track in the stream. ...
...lling MediaStream.getTracks(), using forEach() to call MediaStreamTrack.stop() on each track in the stream. ...
MediaTrackConstraints.displaySurface - Web APIs
Later code can use this flag to determine whether or not to perform special processing, such as to remove or replace the backdrop, or to "cut" the individual display areas out of the received frames of video. Exa...
...Later code can use this flag to determine whether or not to perform special processing, such as to remove or replace the backdrop, or to "cut" the individual display areas out of the received frames of video. Examples Here are some example constraints objects fo...
MediaTrackConstraints.logicalSurface - Web APIs
by checking the value of MediaTrackSupportedConstraints.logicalSurface as returned by a call to MediaDevices.getSupportedConstraints(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Syntax var constraintsObject = { logicalSurface: constraint }; constraintsObject.logicalSurface = constraint; Value A ConstrainBoolean which is true if logical surfaces should be permitted among the selections available to the user. See How constraints are defined in Capabilities, constraints, and settings for an explanation of how to define constraints. Usage notes You can check the setting selected by the user agent after the display media has been created by getDisplayMedia() by calling getSettings() on the display media's video MediaSt...
...isplayMedia() by calling getSettings() on the display media's video MediaStreamTrack, then checking the value of the returned MediaTrackSettings object's logicalSurface object. For example, if your app needs to know if the selected display surface is a logical one: let isLogicalSurface = displayStream.getVideoTracks()[0].getSettings().logicalSurface; Following this code, isLogicalSurface is true if the display surface contained in the stream is a logical surface; that is, one which may not be entirely onscreen, or may even be entirely offscreen. Specifications Specification Status Comment Screen CaptureThe definition of 'MediaTrackConstraints.logicalSurface' in that specification. Working Draft Initial specification. ...
MediaTrackSettings.logicalSurface - Web APIs
the display area being captured is a logical surface. Logical surfaces are those which are not necessarily entirely onscreen, or may even be off-screen, such as windows' backing buffers (where only part of the buffer is visible without scrolling the containing window) and offscreen rendering contexts. Syntax isLogicalSurface = mediaTrackSettings.logicalSurface; Value A Boolean value which is true if the video track in the stream of captured video is taken from a logical display surface. The most common scenario in which a display surface may be a logical one is if the selected surface contains the entire content area of a window which is too large to display onscreen at once. Since the window that contains the surface has to be scrolled to show the rest of the contents, the surface is a ...
...rface has to be scrolled to show the rest of the contents, the surface is a logical one. A visible display surface (that is, a surface for which logicalSurface 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). Specifications Specification Status Comment Screen CaptureThe definition of 'MediaTrackSettings.logicalSurface' in that specification. Working Draft Initial definition ...
MediaTrackSupportedConstraints.autoGainControl - Web APIs
If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). ...
...browser offers the ability to automatically control the gain (volume) on media tracks; this obviously is contingent on whether or not the individual device supports automatic gain control as well; it's typically a feature provided by microphones. Syntax autoGainSupported = supportedConstraintsDictionary.autoGainControl; Value This property is present in the dictionary (and its value is always true) if the user agent supports the autoGainControl constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example This example simply displays whether or not your browser supports the autoGainControl constraint. HTML content <div id="result"> </div> CSS content #result { font: 1...
MediaTrackSupportedConstraints.frameRate - Web APIs
If the constraint isn't supported, it's not included in the list, so this value will never be false. The frameRate constraint can be used to establish acceptable upper and lower bounds on the video frame rate for a new video track, or to specify an exact frame rate that must be provided for the request to succeed. ...
...te. See the example to see how this can be used. Syntax frameRateConstraintSupported = supportedConstraintsDictionary.frameRate; Value This property is present in the dictionary if the user agent supports the frameRate constraint. If the property isn't present, the user agent doesn't allow specifying limits on the frame rate for video tracks. If this property is present, its value is always true. Example This simple example looks to see if your browser supports constraining the frame rate when requesting video tracks. JavaScript let result = document.getElementById("result"); if (navigator.mediaDevices.getSupportedConstraints().frameRate) { result.innerHTML = "Supported!"; } else { result.innerHTML = "Not supported!"; } HTML <div id="result"> </div> CSS #result { ...
MediaTrackSupportedConstraints.noiseSuppression - Web APIs
If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). ...
... constraint indicates whether or not the browser offers the ability to automatically control the gain (volume) on media tracks; this obviously is contingent on whether or not the individual device supports automatic gain control as well. Syntax noiseSuppressionSupported = supportedConstraintsDictionary.noiseSuppression; Value This property is present in the dictionary (and its value is always true) if the user agent supports the noiseSuppression constraint (and therefore supports noise suppression on audio tracks). If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you try to look at its value. Example This example simply displays whether or not your browser supports the noiseSuppression constraint. HTML conten...
Metadata.modificationTime - Web APIs
nged. Example This example tries to get a particular working file at tmp/workfile.json. Once that file has been found, its metadata is obtained and the file's modification timestamp year is compared to the current year. If it was last modified in a year at least five prior to the current year, the file is removed and a new one is created. ...
... Browser compatibility The compatibility table on this page is generated from structured data. ...
MouseEvent.initMouseEvent() - Web APIs
Obsolete From Document Object Model (DOM) Level 2 Events Sp...
... Obsolete From Document Object Model (DOM) Level 2 Events Specific...
msIsBoxed - Web APIs
Web › API › MsIsBoxed
t use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. msIsBoxed is a property which gets or sets when the video player control is in boxed (letterbox or pillarbox) mode. This proprietary property is specific to Internet Explorer and Microsoft Edge. Returns true if the video is in letterbox or pillarbox mode. Letterbox format displays black bars on the top and bottom of a video to fill in between the wide screen format of a video, and the aspect ratio of the screen. Typically the video's left and right edges go to the full width of the screen. Pillarbox format displays black bars on the left and right of a video to fill in the difference between a video ...
...t ratio of the screen. Typically the video's left and right edges go to the full width of the screen. Pillarbox format displays black bars on the left and right of a video to fill in the difference between a video and a wider screen. With pillarbox format, the top and bottom edges of the video go to the full height of the screen. Syntax isBoxed = object.msIsBoxed Value Boolean value set to true activates boxed mode for the video player. Boolean value set to false means the video player is zoomed to fill the screen. ...
MutationObserver.MutationObserver() - Web APIs
when calling observe() to begin watching the DOM. The kind of change that took place (either a change to the list of children, or a change to an attribute) is detected by looking at the mutation.type property. Creating and starting the observer This code actually sets up the observation process. 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. A set of options for the observer is also established in the observerOptions record. In it, we specify values of...
... Then the observer is instantiated, specifying the callback() function. We begin observing the DOM nodes of interest by calling observe(), specifying the target node and the options object. ...
MutationObserverInit.characterData - Web APIs
to their textual contents. Character data changes are detectable on any text node, including nodes based on the Text, ProcessingInstruction, and Comment interfaces. Note that this doesn't monitor content of an HTMLElement, even if it only contains text inside, as it only monitors text nodes themselves. So either pass directly a text node to the observe() method or you need to also set subtree: true. Syntax var options = { characterData: true | false } Value A Boolean value indicating whether or not to call the observer's callback function when textual nodes' values change. If true, the callback specified when observe() was used to start observing the node or subtree is called any time the contents of a text node are changed. You can expand the capabilities of attribute mutation mo...
... called any time the contents of a text node are changed. You can expand the capabilities of attribute mutation monitoring using other options: characterDataOldValue lets you specify whether or not you want the previous value of changed text nodes to be provided using the MutationRecord's oldValue property. subtree lets you specify whether to watch the target node and all of its descendants (true), or just the target node (false). If you set characterDataOldValue to true, characterData is automatically assumed to be true, even if you don't expressly set it as such. Example Specifications Specification Status Comment DOMThe definition of 'MutationObserverInit.characterData' in that specification. Living Standard ...
MutationObserverInit.subtree - Web APIs
The MutationObserverInit dictionary's optional subtree property can be set to true to monitor the targeted node and all of its descendants. The default value, false, indicates only the target node itself is to be monitored for changes. subtree can be used in concert with the other options to extend monitoring of attributes, text content, and child lists to the entire subtree rooted at the target node. 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. Changing this value to true causes the entire subtree rooted at the specified target node to be monitored for the changes indicated by the other options. For example, to watch the t...
...e specified when calling MutationObserver.observe() is to be monitored for changes. Changing this value to true causes the entire subtree rooted at the specified target node to be monitored for the changes indicated by the other options. 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. To monitor the entire subtree for attribute changes, simply set subtree to true: var options = { attributes: true, subtree: true }; Example Specifications Specification Status Comment DOMThe definition of 'MutationObserverInit.subtree' in that specification. Living Standa...
Navigator.canShare() - Web APIs
Syntax var canShare = navigator.canShare(data); Parameters data Optional An object containing data to share that matches what you would pass to Navigator.share(). Return value A Boolean. True if data can be shared with Navigator.share(). Exceptions None. ...
... The Navigator.canShare() method of the Web Share API returns true if a call to Navigator.share() would succeed. Syntax var canShare = navigator.canShare(data); Parameters data Optional An object containing data to share that matches what you would pass to Navigator.share(). Return value A Boolean. True if data can be shared with Navigator.share(). Exceptions None. Examples if(navigator.canShare(data)) { // We can use share() to share the data! Woop! } Specifications Specification Status Comment Web Share API - Level 2The definition of 'canShare' in that specification. Draft Initial definition. ...
Navigator.cookieEnabled - Web APIs
It returns false in Firefox and Chromium-based browsers. ...
...It returns false in Firefox and Chromium-based browsers. ...
Navigator - Web APIs
Web › API › Navigator
this property to return the correct value. Navigator.battery Read only Returns a BatteryManager object you can use to get information about the battery charging status. Navigator.connection Read only Provides a NetworkInformation object containing information about the network connection of a device. Navigator.cookieEnabled Read only Returns false if setting a cookie will be ignored and true otherwise. Navigator.geolocation Read only Returns a Geolocation object allowing accessing the location of the device. NavigatorConcurrentHardware.hardwareConcurrency Read only Returns the number of logical processor cores available. NavigatorPlugins.javaEnabled Read only Returns a Boolean flag indicating whether the host browser is Java-enabled or not. Navigator.keyboard Read only ...
...ame of the current browser (e.g., "Netscape6"). Navigator.vendorSub Returns the vendor version number (e.g. "6.1"). Navigator.webkitPointer Returns a PointerLock object for the Mouse Lock API. Methods Doesn't inherit any method, but implements those defined in NavigatorID, NavigatorContentUtils, NavigatorUserMedia, and NavigatorStorageUtils. Standard Navigator.canShare() Returns true if a call to Navigator.share() would succeed. Navigator.getUserMedia() After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer. Navigator.registerContentHandler() Obsolete since Gecko 59 Allows web sites to register themselves as a possible handler for a given MIME type. Navigator.registerProtocolHandler() ...
Navigator.onLine - Web APIs
Returns the online status of the browser. The property returns a boolean value, with true meaning online and false meaning offline. The property sends updates whenever the browser's ability to connect to the network changes. The update occurs when the user follows links or when a script requests a remote page. For example, the property should return false when users click links soon after they lose internet connection. Browsers implement this property differently. In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. Y...
...that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking. To learn more, see the HTML5 Rocks article, Working Off the Grid. In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. Until Firefox 41, all other conditions return a true value; testing actual behavior on Nightly 68 on Windows shows that it only looks for LAN connection like Chrome and Safari giving false positives. You can see changes in the network state by listening for the events on window.ononline and window.onoffline. Syntax online = window.navigator.onLine; Value online is a boolean true or false. Example View a live example. To check if you are o...
Node.nodeType - Web APIs
Web › API › Node › nodeType
ger implement the Node interface as of DOM4. Node.ENTITY_REFERENCE_NODE 5 An XML Entity Reference node, such as &foo;. Removed in DOM4. Node.ENTITY_NODE 6 An XML <!ENTITY ...> node. Removed in DOM4. Node.NOTATION_NODE 12 An XML <!NOTATION ...> node. Removed in DOM4. ...
...TY_REFERENCE_NODE 5 An XML Entity Reference node, such as &foo;. Removed in DOM4. Node.ENTITY_NODE 6 An XML <!ENTITY ...> node. Removed in DOM4. Node.NOTATION_NODE 12 An XML <!NOTATION ...> node. Removed in DOM4. Examples Different types of nodes document.nodeType === Node.DOCUMENT_NODE; // true document.doctype.nodeType === Node.DOCUMENT_TYPE_NODE; // true document.createDocumentFragment().nodeType === Node.DOCUMENT_FRAGMENT_NODE; // true var p = document.createElement("p"); p.textContent = "Once upon a time..."; p.nodeType === Node.ELEMENT_NODE; // true p.firstChild.nodeType === Node.TEXT_NODE; // true Comments This example checks if the first node inside the document element is a comment, and displays a message if not. var node = document.
Node - Web APIs
Web › API › Node
rns the context object's root which optionally includes the shadow root if it is available. Node.hasChildNodes() Returns a Boolean indicating whether or not the element has any child nodes. Node.insertBefore() Inserts a Node before the reference node as a child of a specified parent node. 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. Node.isEqualNode() Returns a Boolean which indicates whether or not two nodes are of the same type and all their defining data points match. Node.isSameNode() Returns a Boolean value indicating whether or not the two nodes are the same (that is, they reference the same object). Node.lookupPrefix() Returns a DOMStri...
...ode(parentNode, function(node){ if (endScan) { return false } // Ignore anything which isn't a text node if (node.nodeType !== Node.TEXT_NODE) { return } if (typeof pattern === "string") { if (-1 !== node.textContent.indexOf(pattern)) { matches.push(node) } } else if (pattern.test(node.textContent)) { if (!pattern.global) { endScan = true matches = node } else { matches.push(node) } } }) return matches } For example, to find Text nodes that contain typos: const typos = ["teh", "adn", "btu", "adress", "youre", "msitakes"] const pattern = new RegExp("\\b(" + typos.join("|") + ")\\b", "gi") const mistakes = grep(document.body, pattern) console.log(mistakes) Specifications Spec...
NodeList - Web APIs
Web › API › NodeList
since they will also enumerate its length and item properties and cause errors if your script assumes it only has to deal with element objects. Also, for..in is not guaranteed to visit the properties in any particular order. ...
... Living Standard Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'NodeList' in that specification. ...
Notification.renotify - Web APIs
Note: This feature is available in Web Workers. The renotify read-only property of the Notification interface specifies whether the user should be notified after a new notification replaces an old one, as specified in the renotify option of the Notification() constructor. Syntax var renotify = Notification.renotify; Value A Boolean. false is the default; true makes the notification renotify the user. ...
...ification.renotify; Value A Boolean. false is the default; true makes the notification renotify the user. Examples The following snippet is intended to fire a notification that renotifies the user after it has been replaced; a simple options object is created, and then the notification is fired using the Notification() constructor. var options = { body: 'Do you like my body?', renotify: true } var n = new Notification('Test notification',options); console.log(n.renotify) // should log true Specifications Specification Status Comment Notifications APIThe definition of 'renotify' in that specification. Living Standard Living standard ...
Notification.silent - Web APIs
This feature is available in Web Workers. The silent read-only property of the Notification interface specifies whether the notification should be silent, i.e., no sounds or vibrations should be issued, regardless of the device settings. This is specified in the silent option of the Notification() constructor. Syntax var silent = Notification.silent; Value A Boolean. ...
...of the Notification() constructor. Syntax var silent = Notification.silent; Value A Boolean. false is the default; true makes the notification silent. Examples The following snippet is intended to fire a silent notification; a simple options object is created, and then the notification is fired using the Notification() constructor. var options = { body: 'Do you like my body?', silent: true } var n = new Notification('Test notification', options); console.log(n.silent) // should log true Specifications Specification Status Comment Notifications APIThe definition of 'silent' in that specification. Living Standard Living standard ...
OES_vertex_array_object.isVertexArrayOES() - Web APIs
Examples var ext = gl.getExtension('OES_vertex_array_object'); var vao = ext.createVertexArrayOES(); ext.bindVertexArrayOES(vao); // ... ...
... Examples var ext = gl.getExtension('OES_vertex_array_object'); var vao = ext.createVertexArrayOES(); ext.bindVertexArrayOES(vao); // ... ...
OffscreenCanvas.getContext() - Web APIs
p drawing of transparent content and images then. (Gecko only) willReadFrequently: Boolean that indicates whether or not a lot of read-back operations are planned. This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling getImageData() frequently. This option is only available, if the flag gfx.canvas.willReadFrequently.enable is set to true (which, by default, is only the case for B2G/Firefox OS). (Blink only) storage: String that indicates which storage is used ("persistent" by default). WebGL context attributes: alpha: Boolean that indicates if the canvas contains an alpha buffer. depth: Boolean that indicates that the drawing buffer has a depth buffer of at least 16 bits. stencil: Boolean that indicates that the d...
...as a depth buffer of at least 16 bits. stencil: Boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits. antialias: Boolean that indicates whether or not to perform anti-aliasing. premultipliedAlpha: Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. preserveDrawingBuffer: If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. failIfMajorPerformanceCaveat: Boolean that indicates if a context will be created if the system performance is low. Return value A RenderingContext which is either a CanvasRenderingContext2D for "2d", WebGLRenderingContext for "webgl" and "experimental-webgl", WebGL2Rend...
PaymentAddress.toJSON() - Web APIs
Disabled Full support 62Notes Disabled Notes Available only in nightly builds. Requires the comma-delineated list in dom.payments.request.supportedRegions to contain one or more of the supported 2-character ISO locales, currently US and CA.Disabled From version 62: this feature is behind the dom.payments.request.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support YesWebView Android No support NoChrome Android Full support 61Di...
... Disabled Full support 62Notes Disabled Notes Available only in nightly builds. Requires the comma-delineated list in dom.payments.request.supportedRegions to contain one or more of the supported 2-character ISO locales, currently US and CA.Disabled From version 62: this feature is behind the dom.payments.request.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support YesSamsung Internet Android No support NoLegend Full support Full support ...
PaymentAddress - Web APIs
// Call show() to trigger the browser's payment flow. const response = await request.show(); // Process payment. const json = response.toJSON(); const httpResponse = await fetch("/pay...
... // Call show() to trigger the browser's payment flow. const response = await request.show(); // Process payment. const json = response.toJSON(); const httpResponse = await fetch("/pay/", { method: "POST", body: json }); const result = htt...
PaymentRequest.abort() - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support 11.1WebView Android No support NoChrome Android Full support 53F...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support 11.3Samsung Internet Android Full support 6.0Legend Full support Full support ...
PaymentRequest.prototype.id - Web APIs
Web › API › PaymentRequest › id
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support 11.1WebView Android No support NoChrome Android Full support 60F...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support 11.3Samsung Internet Android Full support 8.0Legend Full support Full support ...
PaymentRequest.onshippingaddresschange - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support 11.1WebView Android No support NoChrome Android Full support 53F...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support 11.3Samsung Internet Android Full support 6.0Legend Full support Full support ...
PaymentRequest.shippingAddress - Web APIs
The shippingAddress read-only property of the PaymentRequest interface returns the shipping address provided by the user. It is null by default. Syntax var paymentAddress = PaymentRequest.shippingAddress; Example Generally, the user agent will fill the shippingAddress property value. You can trigger this by setting PaymentOptions.requestShipping to true when calling the PaymentRequest constructor. In the example below, the cost of shipping varies by geography. When the PaymentRequest.onshippingaddresschange is called, updateDetails() is called to update the details of the PaymentRequest, using shippingAddress to set the correct shipping cost. // Initialization of PaymentRequest arguments are excerpted for the sake of // brevity. var payment = new PaymentRequest(supportedInstruments...
...on(paymentResponse) { // Processing of paymentResponse exerpted for brevity. ...
PaymentRequest.shippingType - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support 11.1WebView Android No support NoChrome Android Full support 55F...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support 11.3Samsung Internet Android Full support 6.0Legend Full support Full support ...
PaymentResponse.complete() - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support YesWebView Android No support NoChrome Android Full support 56 ...
...eds to be set to Enabled). To change preferences in Chrome, visit chrome://flags.Firefox Android Full support 56Notes Disabled Full support 56Notes Disabled Notes Available only in nightly builds.Disabled From version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support YesSamsung Internet Android Full support 6.0Legend Full support Full support ...
PaymentResponse.details - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support YesWebView Android No support NoChrome Android Full support 56 ...
...eds to be set to Enabled). To change preferences in Chrome, visit chrome://flags.Firefox Android Full support 56Notes Disabled Full support 56Notes Disabled Notes Available only in nightly builds.Disabled From version 56: this feature is behind the dom.payments.request.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support YesSamsung Internet Android Full support 6.0Legend Full support Full support ...
PaymentResponse.onpayerdetailchange - Web APIs
request form. Examples In the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to validate the information entered by the user, requesting that any mistakes be corrected // Options for PaymentRequest(), indicating that shipping address, // payer email address, name, and phone number all be collected. ...
...n the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to validate the information entered by the user, requesting that any mistakes be corrected // Options for PaymentRequest(), indicating that shipping address, // payer email address, name, and phone number all be collected. const options = { requestShipping: true, requestPayerEmail: true, requestPayerName: true, requestPayerPhone: true, }; const request = new PaymentRequest(methods, details, options); const response = request.show(); // Get the data from the response let { payerName: oldPayerName, payerEmail: oldPayerEmail, payerPhone: oldPayerPhone, } = response; // Set up a handler for payerdetailchange events, to // request corrections as needed. response.onpayer...
PaymentResponse: payerdetailchange event - Web APIs
hange Examples In the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to validate the information entered by the user, requesting that any mistakes be corrected // Options for PaymentRequest(), indicating that shipping address, // payer email address, name, and phone number all be collected. ...
...n the example below, onpayerdetailchange is used to set up a listener for the payerdetailchange event in order to validate the information entered by the user, requesting that any mistakes be corrected // Options for PaymentRequest(), indicating that shipping address, // payer email address, name, and phone number all be collected. const options = { requestShipping: true, requestPayerEmail: true, requestPayerName: true, requestPayerPhone: true, }; const request = new PaymentRequest(methods, details, options); const response = request.show(); // Get the data from the response let { payerName: oldPayerName, payerEmail: oldPayerEmail, payerPhone: oldPayerPhone, } = response; // Set up a handler for payerdetailchange events, to // request corrections as needed. response.onpayer...
PaymentResponse.requestId - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari Full support YesWebView Android No support NoChrome Android Full support 60Fi...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS Full support YesSamsung Internet Android Full support 8.0Legend Full support Full support ...
Permissions - Web APIs
To change preferences in Firefox, visit about:config. No support 47 -- 51IE No support NoOpera ? Safari No support NoWebView Android Full support 46Chrome Android Full support ...
...To change preferences in Firefox, visit about:config. No support 47 -- 51Opera Android ? Safari iOS No support NoSamsung Internet Android Full support 5.0Legend Full support Full sup...
Using the Permissions API - Web APIs
ptors The Permissions.query() method takes a PermissionDescriptor dictionary as a parameter -- this contains the name of the API you are interested in. Some APIs have more complex PermissionDescriptors containing additional information, which inherit from the default PermissionDescriptor. For example, the PushPermissionDescriptor should also contain a Boolean that specifies if userVisibleOnly is true or false. Revoking permissions Starting in Firefox 47, you can now revoke existing permissions, using the Permissions.revoke() method. This works in exactly the same way as the Permissions.query() method, except that it causes an existing permission to be reverted back to its default state when the promise successfully resolves (which is usually prompt). See the following code in our demo: va...
... ... function revokePermission() { navigator.permissions.revoke({name:'geolocation'}).then(function(result) { report(result.state); }); } The revoke() function has been disabled by default starting in Firefox 51, since its design has been brought into question in the Web Applications Security Working Group. It can be re-enabled by setting the preference dom.permissions.revoke.enable to true. Responding to permission state changes You'll notice that there is an onchange event handler in the code above, attached to the PermissionStatus object -- this allows us to respond to any changes in the permission status for the API we are interested in. At the moment we are just reporting the change in state. Conclusion and future work At the moment this doesn't offer much more than what w...
PointerEvent.isPrimary - Web APIs
In a multi-pointer scenario (such as a touch screen that supports more than one touch point), this property is used to identify a master pointer among the set of active pointers for each pointer type. Only a primary pointer will produce compatibility mouse events. Authors who desire only single-pointer interaction can achieve that by ignoring non-primary pointers. ...
...ry. For example, a touch contact and a mouse cursor moved simultaneously will produce pointers that are both considered primary. If there are multiple primary pointers, these pointers will all produce compatibility mouse events (see Pointer_events for more information about pointer, mouse and touch interaction). Syntax var isPrimary = pointerEvent.isPrimary; Return value isPrimary Returns true if the pointer for this event is the primary pointer and returns false otherwise. Example This example illustrates using the value of isPrimary to call the appropriate processing function. target.addEventListener('pointerdown', function(event) { if (event.isPrimary) process_primary_pointer(event); else process_secondary_pointer(event); }, false); Specifications Sp...
Proximity Events - Web APIs
iceProximityEvent event provides an exact match for the distance between the device and the object through its value property. It also provides the closest and farthest distance the device is able to detect something through its min and max properties. The UserProximityEvent event provides a rough approximation of the distance, expressed through a boolean. ...
...stance, expressed through a boolean. 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. Working Draft Initial specification ...
PublicKeyCredential.getClientExtensionResults() - Web APIs
nt. This object contains a map between the extensions' identifiers and their results from the processing. Warning! As of March 2019, only appId (used during creation with PublicKeyCredentialRequestOptions.extensions) is supported by Chrome and Edge. Firefox does not seem to support any extension. ...
...ssing. Warning! As of March 2019, only appId (used during creation with PublicKeyCredentialRequestOptions.extensions) is supported by Chrome and Edge. Firefox does not seem to support any extension. ...
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
icatorAttestationResponse.attestationObject) "discouraged": user verification should not be employed as to minimize the user interaction during the process. The default value is "preferred". The authenticator used for the creation of the public key credential must comply with the requirements. ...
...". The authenticator used for the creation of the public key credential must comply with the requirements. Note: See PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() which resolves to true when a user-verifiying platform authenticator is available. ...
RTCDataChannel: close event - Web APIs
e Event Event handler property RTCDataChannel.onclose Examples This example sets up a handler for the close event for the RTCDataChannel named dc; its responsibility in this example is to update user interface elements to reflect that there is no longer an ongoing call, and to allow a new call to be started. 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 event...
...ed = 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. Candidate Recommendation Initial specification. ...
RTCDataChannel: open event - Web APIs
n established. It enables the message input box and send button as well as enabling the disconnect button and disabling the connect button. Finally, the message input box is focused so the user can immediately begin to type. ...
...ssageButton.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. ...
RTCDataChannel - Web APIs
If no...
...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. If no protocol was specified when the data channel was created, then this property's value is "" (the empty string).readyState Read only The read-only RTCDataChannel property readyState returns an enum of ...
RTCIceCandidatePairStats.selected - Web APIs
The non-standard, Firefox-specific RTCIceCandidatePairStats property selected indicates whether or not the candidate pair described by the object is the one currently being used to communicate with the remote peer. Syntax isSelected = icpStats.selected; Value A Firefox-specific Boolean value which is true if the candidate pair described by this object is the one currently in use. In any other browser, you can determine the selected candidate pair by looking for a stats object of type transport, which is an RTCTransportStats object. That object's selectedCandidatePairId property indicates whether or not the specified transport is the one being used. Example The function shown in this example identifies the currently-selected candidate pair from a statistics report by first iterating o...
...urrently-selected candidate pair from a statistics report by first iterating over each report, looking for a transport report; when one is found, that transport's selectedCandidatePairId is used to get the RTCIceCandidatePair describing the connection. If that fails, then the second section iterates over the reports, looking for a candidate-pair record whose Firefox-specific selected property is true. This candidate pair is then returned as the currently-selected one. function getCurrentCandidatePair(statsResults) { statsResults.forEach(report => { if (report.type === "transport") { currentPair = statsResults.get(report.selectedCandidatePairId); } }); if (!currentPair) { statsResults.forEach(report => { if (report.type === "candidate-pair" && report.selected) {...
RTCIceCandidatePairStats - Web APIs
that specifies the time at which the last (most recent) STUN response was received by the local candidate from the remote candidate in this pair. localCandidateId Optional The unique ID string corresponding to the RTCIceCandidate from the data included in the RTCIceCandidateStats object providing statistics for the candidate pair's local candidate. nominated Optional A Boolean value which, if true, indicates that the candidate pair described by this object is one which has been proposed for use, and will be (or was) used if its priority is the highest among the nominated candidate pairs. See RFC 5245, section 7.1.3.2.4 for details. packetsReceived Optional The total number of packets received on this candidate pair. packetsSent Optional The total number of packets sent on this candidat...
...cating the candidate pair's priority. readable Optional A Boolean value indicating whether or not data can be sent over the connection described by the candidate pair. writable Optional A Boolean value indicating whether or not data can be received on the connection described by the candidate pair. Non-standard properties selected Optional A Firefox-specific Boolean value which is true if the candidate pair described by this object is the one currently in use. The spec-compliant way to determine the selected candidate pair is to look for a stats object of type transport, which is an RTCTransportStats object. That object's selectedCandidatePairId property indicates whether or not the specified transport is the one being used. Usage notes The currently-active ICE candidate pai...
RTCIceCandidateStats - Web APIs
was previously named ip and only accepted IP addresses. candidateType Optional A string matching one of the values in the RTCIceCandidateType enumerated type, indicating what kind of candidate the object provides statistics for. deleted Optional A Boolean value indicating whether or not the candidate has been released or deleted; the default value is false. For local candidates, it's value is true if the candidate has been deleted or released. For host candidates, true means that any network resources (usually a network socket) associated with the candidate have already been released. For TURN candidates, the TURN allocation is no longer active for deleted candidates. This property is not present for remote candidates. networkType Optional A string from the RTCNetworkType enumerated type...
...ect's networkType and determine whether or not the type of network is acceptable for use. This function is then called for RTCStats objects whose type is local-candidate, indicating that the object is in fact an RTCIceCandidateStats with information about a local ICE candidate. ...
RTCOfferAnswerOptions.voiceActivityDetection - Web APIs
The voiceActivityDetection property of the RTCOfferAnswerOptions dictionary is used to specify whether or not to use automatic voice detection for the audio on an RTCPeerConnection. The default value, true, indicates that voice detection should be used and that if possible, the user agent should automatically disable or mute outgoing audio when the audio source is not sensing a human voice. Syntax var options = { voiceActivityDetection: trueOrFalse }; Value A Boolean value indicating whether or not the connection should use voice detection once running. ...
...default value, true, indicates that voice detection should be used and that if possible, the user agent should automatically disable or mute outgoing audio when the audio source is not sensing a human voice. Syntax var options = { voiceActivityDetection: trueOrFalse }; Value A Boolean value indicating whether or not the connection should use voice detection once running. The default value, true, indicates that the user agent should monitor the audio coming from the microphone or other audio source and automatically cease transmitting data or mute when the user isn't speaking into the microphone, A value of false indicates that the audio should continue to be transmitted regardless of whether or not speech is detected. ...
RTCPeerConnection.setConfiguration() - Web APIs
t negotiation needs to be done using a different ICE server. var restartConfig = { iceServers: [{ urls: "turn:asia.myturnserver.net", username: "allie@oopcode.com", credential: "topsecretpassword" }] }; myPeerConnection.setConfiguration(restartConfig); myPeerConnection.createOffer({"iceRestart": true}).then(function(offer) { return myPeerConnection.setLocalDescription(offer); }) .then(function() { // send the offer to the other peer using the signaling server }) .catch(reportError); First, a new RTCConfiguration is created, restartConfig, specifying the new ICE server and its credentials. This is then passed into setConfiguration(). ICE negotiation is restarted by calling createOffer(), ...
...ction(offer) { return myPeerConnection.setLocalDescription(offer); }) .then(function() { // send the offer to the other peer using the signaling server }) .catch(reportError); First, a new RTCConfiguration is created, restartConfig, specifying the new ICE server and its credentials. This is then passed into setConfiguration(). ICE negotiation is restarted by calling createOffer(), specifying true as the value of the iceRestart option. From there, we handle the process as usual, by setting the local description to the returned offer and then sending that offer to the other peer. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'setConfiguration()' in that specification. Candidate Recommendation ...
RTCRtpContributingSource.source - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari ? WebView Android Full support 59Chrome Android Full support 59Firefox Android ...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS ? Samsung Internet Android Full support 7.0Legend Full support Full support No supp...
ReadableStream.cancel() - Web APIs
stream is used to fetch the WHATWG HTML spec chunk by chunk; each chunk is searched for the string "service workers". When the search terms is found, cancel() is used to cancel the stream -- the job is finished so it is no longer needed. ...
... if (matchFoundAt === -1) { matchFoundAt = (caseInsensitive ? buffer.toLowerCase() : buffer).indexOf(toMatch); } if (matchFoundAt === -1) { buffer = buffer.slice(-bufferSize); } else if (buffer.slice(matchFoundAt + toMatch.length).length >= contextAfter) { console.log("Here's the match:") console.
ReadableStream.pipeThrough() - Web APIs
writable stream can be read in some transformed state by the readable stream. For example, a TextDecoder, has bytes written to it and strings read from it, while a video decoder has encoded bytes written to it and uncompressed video frames read from it. options Optional The options that should be used when piping to the writable stream. ...
...writable stream. Available options are: preventClose: If this is set to true, the source ReadableStream closing will no longer cause the destination WritableStream to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. preventAbort: If this is set to true, errors in the source ReadableStream will no longer abort the destination WritableStream. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. preventCancel: If this is set to true, errors in the destination WritableStream will no longer cancel the source ReadableStream. In this case the method will return a promise re...
ReadableStream.pipeTo() - Web APIs
lock it for the duration of the pipe, preventing other readers from locking it. Syntax var promise = readableStream.pipeTo(destination[, options]); Parameters destination A WritableStream that acts as the final destination for the ReadableStream. options Optional The options that should be used when piping to the writable stream. ...
...writable stream. Available options are: preventClose: If this is set to true, the source ReadableStream closing will no longer cause the destination WritableStream to be closed. The method will return a fulfilled promise once this process completes, unless an error is encountered while closing the destination in which case it will be rejected with that error. preventAbort: If this is set to true, errors in the source ReadableStream will no longer abort the destination WritableStream. The method will return a promise rejected with the source's error, or with any error that occurs during aborting the destination. preventCancel: If this is set to true, errors in the destination WritableStream will no longer cancel the source ReadableStream. In this case the method will return a promise re...
ReadableStream.tee() - Web APIs
if (done) { console.log("Stream complete"); return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Read ' + charsReceived + ' c...
...hStream(stream, list) { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent = 'Read ' + charsReceived + ' characters so far. Current chunk = ' + chunk; list.appendChild(listItem); // Read some more, and call t...
ReadableStreamDefaultReader.read() - Web APIs
); Parameters None. Return value A Promise, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: If a chunk is available, the promise will be fulfilled with an object of the form { value: theChunk, done: false }. If the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. If the stream becomes errored, the promise will be rejected with the relevant error. Exceptions TypeError The source object is not a ReadableStreamDefaultReader, or the stream has no owner. Examples Example 1 - simple example This example shows the basic API usage, but doesn't try to deal with complications like stream chunks not ending on line boundaries for example. In this examp...
...t which point we return out of the recursive function and print the entire stream to another part of the UI. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textConten...
Reporting API - Web APIs
ailable in the observer's report queue, and a copy of the same ReportingObserver object, so observation can be controlled directly from inside the callback. The callback runs when observation starts An options dictionary that allows you to specify the type of reports to collect, and whether the reports that were generated before the observer was able to be created should be observable (buffered: true). Methods are then available on the observer to start collecting reports (ReportingObserver.observe()), retrieve the reports currently in the report queue (ReportingObserver.takeRecords()), and disconnect the observer so it can no longer collect records (ReportingObserver.disconnect()). Reporting API interfaces ReportingObserver Create ReportingObserver instances using its constructor, whi...
...ith a InterventionReportBody return value. Crash report Indicates that the website stopped running due to a browser crash. Indicated by a Report.body property with a CrashReportBody return value. ...
Using server-sent events - Web APIs
f a script that generates the events. For example: const evtSource = new EventSource("ssedemo.php"); If the event generator script is hosted on a different origin, a new EventSource object should be created with both the URL and an options dictionary. ...
...g the MIME type text/event-stream. Each notification is sent as a block of text terminated by a pair of newlines. For details on the format of the event stream, see Event stream format. The PHP code for the example we're using here follows: date_default_timezone_set("America/New_York"); header("Cache-Control: no-cache"); header("Content-Type: text/event-stream"); $counter = rand(1, 10); while (true) { // Every second, send a "ping" event. echo "event: ping\n"; $curDate = date(DATE_ISO8601); echo 'data: {"time": "' . $curDate . '"}'; echo "\n\n"; // Send a simple message at random intervals. $counter--; if (!$counter) { echo 'data: This is a message at time ' . $curDate . "\n\n"; $counter = rand(1, 10); } ob_end_flush(); flush(); sleep(1); } The code ab...
ServiceWorkerRegistration.showNotification() - Web APIs
ining the URL of an image to be used as an icon by the notification. image: a USVString containing the URL of an image to be displayed in the notification. lang: Specify the lang used within the notification. This string must be a valid BCP 47 language tag. renotify: A boolean that indicates whether to suppress vibrations and audible alerts when reusing a tag value. If options's renotify is true and options's tag is the empty string a TypeError will be thrown. The default is false. requireInteraction: Indicates that on devices with sufficiently large screens, a notification should remain active until the user clicks or dismisses it. If this value is absent or false, the desktop version of Chrome will auto-minimize notifications after approximately twenty seconds. The default value is f...
...action: Indicates that on devices with sufficiently large screens, a notification should remain active until the user clicks or dismisses it. 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. silent: When set indicates that no sounds or vibrations should be made. If options's silent is true and options's vibrate is present a TypeError exception will be thrown. The default value is false. tag: An ID for a given notification that allows you to find, replace, or remove the notification using a script if necessary. timestamp: A DOMTimeStamp representing the time when the notification was created. It can be used to indicate the time at which a notification is actual. For example, th...
ServiceWorkerRegistration.unregister() - Web APIs
Note: This feature is available in Web Workers. ...
... Working Draft Initial definition. ...
SourceBuffer - Web APIs
r(), SourceBuffer.appendStream(), or SourceBuffer.remove() operation is currently in progress. SourceBuffer.videoTracks Read only A list of the video tracks currently contained inside the SourceBuffer. Event handlers SourceBuffer.onabort Fired whenever SourceBuffer.appendBuffer() or SourceBuffer.appendStream() is ended by a call to SourceBuffer.abort(). SourceBuffer.updating changes from true to false. SourceBuffer.onerror Fired whenever an error occurs during SourceBuffer.appendBuffer() or SourceBuffer.appendStream(). SourceBuffer.updating changes from true to false. SourceBuffer.onupdate Fired whenever SourceBuffer.appendBuffer() method or the SourceBuffer.remove() completes. SourceBuffer.updating changes from true to false. This event is fired before onupdateend. SourceBuffer.
... Methods Inherits methods from its parent interface, EventTarget. SourceBuffer.abort() Aborts the current segment and resets the segment parser. SourceBuffer.appendBuffer() Appends media segment data from an ArrayBuffer or ArrayBufferView object to the SourceBuffer. ...
SpeechRecognition.interimResults - Web APIs
Examples This code is excerpted from our Speech color changer example. ...
... Examples This code is excerpted from our Speech color changer example. ...
SpeechSynthesis.pending - Web APIs
The pending read-only property of the SpeechSynthesis interface is a Boolean that returns true if the utterance queue contains as-yet-unspoken utterances. Syntax var amIPending = speechSynthesisInstance.pending; Value A Boolean. ...
...g; Value A Boolean. Examples var synth = window.speechSynthesis; var utterance1 = new SpeechSynthesisUtterance('How about we say this now? This is quite a long sentence to say.'); var utterance2 = new SpeechSynthesisUtterance('We should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); var amIPending = synth.pending; // will return true if utterance 1 is still being spoken and utterance 2 is in the queue Specifications Specification Status Comment Web Speech APIThe definition of 'pending' in that specification. Draft ...
SpeechSynthesis.speaking - Web APIs
The speaking read-only property of the SpeechSynthesis interface is a Boolean that returns true if an utterance is currently in the process of being spoken -- even if SpeechSynthesis is in a paused state. Syntax var amISpeaking = speechSynthesisInstance.speaking; Value A Boolean. ...
... Value A Boolean. Examples var synth = window.speechSynthesis; var utterance1 = new SpeechSynthesisUtterance('How about we say this now? This is quite a long sentence to say.'); var utterance2 = new SpeechSynthesisUtterance('We should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); var amISpeaking = synth.speaking; // will return true if utterance 1 or utterance 2 are currently being spoken Specifications Specification Status Comment Web Speech APIThe definition of 'speaking' in that specification. Draft ...
Using writable streams - Web APIs
ew TextDecoder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink err...
... defaultWriter.
Text.isElementContentWhitespace - Web APIs
onsists solely of whitespace. ...
...e below, we create a node with mixed display and whitespace characters and the attribute is false. ...
TouchEvent.altKey - Web APIs
Web › API › TouchEvent › altKey
Example This example illustrates how to access the TouchEvent key modifier properties: TouchEvent.altKey, TouchEvent.ctrlKey, TouchEvent.metaKey and TouchEvent.shiftKey. ...
... Example This example illustrates how to access the TouchEvent key modifier properties: TouchEvent.altKey, TouchEvent.ctrlKey, TouchEvent.metaKey and TouchEvent.shiftKey. ...
TouchEvent.ctrlKey - Web APIs
Example The TouchEvent.altKey example includes an example of this property's usage. ...
... Example The TouchEvent.altKey example includes an example of this property's usage. ...
TouchEvent.metaKey - Web APIs
Example The TouchEvent.altKey example includes an example of this property's usage. ...
... Example The TouchEvent.altKey example includes an example of this property's usage. ...
TouchEvent.shiftKey - Web APIs
Example The TouchEvent.altKey example includes an example of this property's usage. ...
... Example The TouchEvent.altKey example includes an example of this property's usage. ...
Multi-touch interaction - Web APIs
s, the first touchstart event will have // targetTouches length of one, the second event will have a length // of two, and so on. ev.preventDefault(); // Cache the touch points for later processing of 2-touch pinch/zoom if (ev.targetTouches.length == 2) { for (var i=0; i < ev.targetTouches.length; i++) { tpCache.push(ev.targetTouches[i]); } } if (logEvents) log("touchStart", ev, true); update_background(ev); } Touch move handler The touchmove handler calls preventDefault() for the same reason mentioned above, and invokes the pinch/zoom handler. function move_handler(ev) { // Note: if the user makes more than one "simultaneous" touches, most browsers // fire at least one touchmove event and some will fire several touchmoves. // Consequently, an application might want t...
... // Two simultaneous touches ev.target.style.background = "pink"; break; default: // More than two simultaneous touches ev.target.style.background = "lightblue"; } } Event logging The functions are used to log event activity to the application window, to support debugging and learning about the event flow. ...
ValidityState.typeMismatch - Web APIs
The read-only typeMismatch property of a ValidityState object indicates if the value of an <input>, after having been edited by the user, does not conform to the constraints set by the element's type attribute. If the type attribute expects specific strings, such as the email and url types and the value don't doesn't conform to the constraints set by the type, the typeMismatch property will be true. The email input type expects one or more valid email addresses, depending on whether the multiple attribute is present. A valid email address includes an email prefix and a domain, with or without a top level domain. If the value of the email input is not an empty string, a single valid e-mail address, or one or more comma separated email address if the multiple attribute is present, there is a ...
... the value expected via the type attribute and the data that is actually present. The typeMismatch is only one of the many possible errors and is only relevant for the email and url types. When the value provided doesn't match the expected value based on the type for other input types, you get different errors. For example, if the number input value is not a floating point number, the badInput is true. If the email is required but is empty, the valueMissing will be true. Specifications Specification Status Comment HTML Living StandardThe definition of 'ValidityState.typeMismatch' in that specification. Living Standard HTML 5.1The definition of 'ValidityState.typeMismatch' in that specification. Recommendation HTML5The definition of 'Val...
VideoTrack - Web APIs
e represents a single video track from a <video> element. The most common use for accessing a VideoTrack object is to toggle its selected property in order to make it the active video track for its <video> element. Properties selected A Boolean value which controls whether or not the video track is active. Only a single video track can be active at any given time, so setting this property to true for one track while another track is active will make that other track inactive. id Read only A DOMString which uniquely identifies the track within the media. This ID can be used to locate a specific track within a video track list by calling VideoTrackList.getTrackById(). The ID can also be used as the fragment part of the URL if the media supports seeking by media fragment per the Media Fra...
... such as forEach(). This first example gets the first video track on the media: var firstTrack = tracks[0]; The next example scans through all of the media's video tracks, activating the first video track that is in the user's preferred language (taken from a variable userLanguage). for (var i = 0; i < tracks.length; i++) { if (tracks[i].language === userLanguage) { tracks[i].selected = true; break; } }); The language is in standard (RFC 5646) format. For US English, this would be "en-US", for example. Specifications Specification Status Comment HTML Living StandardThe definition of 'VideoTrack' in that specification. Living Standard ...
WebGL2RenderingContext.isTransformFeedback() - Web APIs
Examples gl must be a WebGL2RenderingContext. WebGLTransformFeedback objects are not available in WebGL 1. var transformFeedback = gl.createTransformFeedback(); // ... ...
... Examples gl must be a WebGL2RenderingContext. WebGLTransformFeedback objects are not available in WebGL 1. var transformFeedback = gl.createTransformFeedback(); // ... ...
WebGL2RenderingContext.isVertexArray() - Web APIs
Examples var vao = gl.createVertexArray(); gl.bindVertexArray(vao); // ... gl.isVertexArray(vao); Specifications Specification Status Comment WebGL 2.0The definition of 'isVertexArray' in that specification. Editor's Draft Initial definition. ...
... Examples var vao = gl.createVertexArray(); gl.bindVertexArray(vao); // ... gl.isVertexArray(vao); Specifications Specification Status Comment WebGL 2.0The definition of 'isVertexArray' in that specification. Editor's Draft Initial definition. ...
WebGLRenderingContext.colorMask() - Web APIs
The WebGLRenderingContext.colorMask() method of the WebGL API sets which color components to enable or to disable when drawing or rendering to a WebGLFramebuffer. Syntax void gl.colorMask(red, green, blue, alpha); Parameters red A GLboolean specifying whether or not the red color component can be written into the frame buffer. Default value: true. green A GLboolean specifying whether or not the green color component can be written into the frame buffer. Default value: true. blue A GLboolean specifying whether or not the blue color component can be written into the frame buffer. Default value: true. alpha A GLboolean specifying whether or not the alpha (transparency) component can be written into the frame buffer. Default value: true. Return value None. Examples gl.colorMask...
...the green color component can be written into the frame buffer. Default value: true. blue A GLboolean specifying whether or not the blue color component can be written into the frame buffer. Default value: true. alpha A GLboolean specifying whether or not the alpha (transparency) component can be written into the frame buffer. Default value: true. Return value None. Examples gl.colorMask(true, true, true, false); To get the current color mask, query the COLOR_WRITEMASK constant which returns an Array. gl.getParameter(gl.COLOR_WRITEMASK); // [true, true, true, false] Specifications Specification Status Comment WebGL 1.0The definition of 'colorMask' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glCo...
WebGLRenderingContext.getVertexAttrib() - Web APIs
information about a vertex attribute at a given position. Syntax any gl.getVertexAttrib(index, pname); Parameters index A GLuint specifying the index of the vertex attribute. pname A GLenum specifying the information to query. Possible values: gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: Returns the currently bound WebGLBuffer. gl.VERTEX_ATTRIB_ARRAY_ENABLED: Returns a GLboolean that is true if the vertex attribute is enabled at this index. Otherwise false. gl.VERTEX_ATTRIB_ARRAY_SIZE: Returns a GLint indicating the size of an element of the vertex array. gl.VERTEX_ATTRIB_ARRAY_STRIDE: Returns a GLint indicating the number of bytes between successive elements in the array. 0 means that the elements are sequential. gl.VERTEX_ATTRIB_ARRAY_TYPE: Returns a GLenum representing the a...
...X_ATTRIB_ARRAY_STRIDE: Returns a GLint indicating the number of bytes between successive elements in the array. 0 means that the elements are sequential. gl.VERTEX_ATTRIB_ARRAY_TYPE: Returns a GLenum representing the array type. One of gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FLOAT. gl.VERTEX_ATTRIB_ARRAY_NORMALIZED: Returns a GLboolean that is true if fixed-point data types are normalized for the vertex attribute array at the given index. gl.CURRENT_VERTEX_ATTRIB: Returns a Float32Array (with 4 elements) representing the current value of the vertex attribute at the given index. When using a WebGL 2 context, the following values are available additionally: gl.VERTEX_ATTRIB_ARRAY_INTEGER: Returns a GLboolean indicating whether or ...
Color masking - Web APIs
anvas"); var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { document.querySelector("p").innerHTML = "Failed to get WebGL context." + "Your browser or device may not support WebGL."; return; } gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); var timer = setInterval(drawAnimation, 1000); var mask = [true, true, true]; var redtoggle = document.querySelector("#red-toggle"), greentoggle = document.querySelector("#green-toggle"), bluetoggle = document.querySelector("#blue-toggle"); redtoggle.addEventListener("click", setColorMask, false); greentoggle.addEventListener("click", setColorMask, false); bluetoggle.addEventListener("click", setColorMask, false); function setColorMask(evt)...
...ector("#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()]...
Lifetime of a WebRTC session - Web APIs
hannel, and to handle errors. Information needed in order to set up the connection: the IP addressing and port information needed for the peers to be able to talk to one another. Media capability negotiation: what codecs and media data formats can the peers understand? These need to be agreed upon before the WebRTC session can begin. Only once signaling has been successfully completed can the true process of opening the WebRTC peer connection begin. It's worth noting that the signaling server does not actually need to understand or do anything with the data being exchanged through it by the two peers during signaling. The signaling server is, in essence, a relay: a common point which both sides connect to knowing that their signaling data can be transferred through it. The server doesn't ...
...the connection in some way (such as changing to a different set of ICE servers), you can do so before restarting ICE by calling RTCPeerConnection.setConfiguration() with an updated RTCConfiguration dictionary before restarting ICE. To explicitly trigger ICE restart, simply start the renegotiation process by calling RTCPeerConnection.createOffer(), specifying the iceRestart option with a value of true. Then handle the connection process from then on just like you normally would. This generates new values for the ICE username fragment (ufrag) and password, which will be used by the renegotiation process and the resulting connection. The answerer side of the connection will automatically begin ICE restart when new values are detected for the ICE ufrag and ICE password. Transmission Reception ...
Using WebRTC data channels - Web APIs
Channel. let dataChannel = pc.createDataChannel("MyApp Channel"); dataChannel.addEventListener("open", (event) => { beginTransmission(dataChannel); }); Manual negotiation To manually negotiate the data channel connection, you need to first create a new RTCDataChannel object using the createDataChannel() method on the RTCPeerConnection, specifying in the options a negotiated property set to true. This signals to the peer connection to not attempt to negotiate the channel on your behalf. Then negotiate the connection out-of-band, using a web server or other means. This process should signal to the remote peer that it should create its own RTCDataChannel with the negotiated property also set to true, using the same id. This will link the two objects across the RTCPeerConnection. let data...
...e the channel on your behalf. Then negotiate the connection out-of-band, using a web server or other means. This process should signal to the remote peer that it should create its own RTCDataChannel with the negotiated property also set to true, using the same id. This will link the two objects across the RTCPeerConnection. let dataChannel = pc.createDataChannel("MyApp Channel", { negotiated: true }); dataChannel.addEventListener("open", (event) => { beginTransmission(dataChannel); }); requestRemoteChannel(dataChannel.id); In this code snippet, the channel is created with negotiated set to true, then a function called requestRemoteChannel() is used to trigger negotiation, to create a remote channel with the same ID as the local channel. Doing this lets you create data channels with e...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
natural. The human eye doesn't have a zoom lens on it. We make things smaller or larger by moving away from or toward them. In cinematography, that's called a dolly shot. There are two techniques in 3D graphics that can create similar though not identical results, and whose methods apply more easily in different situations. Zooming by adjusting field of view You can do something more akin to a true "zoom" by altering the camera's field of view (FOV). The field of view is an angle defining the length of the arc on the entire viewable area surrounding the camera that should be visible at once. This is an effect of the focal length in a physical camera, so since there is no true camera, altering the FOV is a passable substitute. Recall that the circumference of a circle is 2??r radians (360?)...
...spectiveMatrix(viewport, 130, 1, 100); const translateVec = vec3.fromValues(-trackDistance, -craneDistance, pushDistance); mat4.translate(transform, transform, translateVec); This starts with the perspective matrix representing a 130? vertical field of view, then applies a translation that moves the camera in a manner that includes track, crane, and push movements. Scaling transforms Unlike a true "zoom", scaling involves multiplying each of the x, y, and z coordinate values in a position or vertex by a scaling factor for that axis. These may or may not necessarily be identical for each axis, though the closest result you can get to a zoom effect would involve using the same value for each. This would need to be applied to every vertex in the scene--ideally in the vertex shader. If you wa...
Lighting a WebXR setting - Web APIs
lthough it affects the entire scene; however, the amount of ambient light in a scene should be very low. Because the bouncing and scattering of light can be expensive to compute in real time, especially if multiple light sources are involved, it's common to use ambient lighting to simulate the scattered light caused by all the other light sources in the scene, instead of actually calculating the true effect of light scattering. Care needs to be taken to try to match the ambient light to what would really be the effect of the scene's lighting when doing this, however. Ambient light can also be used to apply a color tint to a scene; for example, in a game in which the player has a special pair of yellow-tinted glasses, you can add a yellow ambient light. Saturn's fifth-largest moon, Tethys...
...nd how it changes over time to attempt to determine a spatial relationship between the devices; this could in theory indicate that the devices are in the same general area, for example. How browsers mitigate these issues In order to help mitigate these risks, browsers are required by the WebXR Lighting Estimation API specification to report lighting information that is fudged somewhat from the true value. There are many ways this could be done. Spherical harmonics precision Browsers can mitigate the risk of fingerprinting by reducing the precision of spherical harmonics. When performing real-time rendering--as is the case with any virtual or augmented reality application--spherical harmonic lighting is used to simplify and accelerate the process of generating highly realistic shadows and ...
WebXR permissions and security - Web APIs
en setting up an AR session, as well. Immersive presentation of VR First, any requests to activate the immersive-vr mode are rejected if the domain issuing the request does not have permission to enable an immersive session. This permission comes from the xr-spatial-tracking feature policy. ...
...Otherwise, an appropriate exception is thrown, such as SecurityError if the document doesn't have permission to enter immersive mode. ...
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
at the user should see), and getPose() to get any other poses, such as the positions of the hand controllers and any other parts of the XR system. Detecting and functioning after tracking loss If tracking fails, such as due to a temporary loss of connectivity between the headset and the user's device, the XR layer will continue to return poses, but those poses' emulatedPosition property will be true, indicating that the computation of the pose is based on a guess of the current position of the user. Some XR hardware uses algorithms to compute the estimated position of the user based on the movement currently ongoing, while other hardware will report no movement at all, but with emulatedPosition set to true. In either case, you may wish to adjust your rendering to compensate for the loss, de...
...How you handle this depends on your application. If your app provides a way for the user to move through the virtual world without physically moving in the real world (a so-called teleportation mechanic), you can simply accept the new position and continue, allowing the jump from your previously-assumed position to be immediately corrected with the new position. ...
Starting up and shutting down a WebXR session - Web APIs
trying to create a new WebXR session, it's often wise to first check to see if the user's hardware and software support the presentation mode you wish to use. This can also be used to determine whether to use an immersive or an inline presentation, for example. To find out if a given mode is supported, simply call the XRSystem method isSessionSupported(). This returns a promise which resolves to true if the given type of session is available for use or false otherwise. const immersiveOK = await navigator.xr.isSessionSupported("immersive-vr"); if (immersiveOK) { // Create and use an immersive VR session } else { // Create an inline session instead, or tell the user about the // incompatibility if inline is required } Creating and starting the session A WebXR session is represented by...
... Perform calculations for the initial position and scale of your objects as needed. Begin the frame rendering cycle. ...
Controlling multiple parameters with ConstantSourceNode - Web APIs
Set the oscillator's type to "sine" to use a sine wave as the audio waveform. Set the oscillator's frequency to the desired value; in this case, oscNode1 is set to a middle C, while oscNode2 and oscNode3 round out the chord by playing the E and G notes. Connect the...
...o waveform. Set the oscillator's frequency to the desired value; in this case, oscNode1 is set to a middle C, while oscNode2 and oscNode3 round out the chord by playing the E and G notes. Connect the new oscillator to the corresponding gain node. Once all three oscillators have been created, they're started by calling each one's ConstantSourceNode.start() method in turn, and playing is set to true to track that the tones are playing. Stopping the oscillators Stopping the oscillators when the user toggles the play state to pause the tones is as simple as stopping each node. function stopOscillators() { oscNode1.stop(); oscNode2.stop(); oscNode3.stop(); playing = false; } Each node is stopped by calling its ConstantSourceNode.stop() method, then playing is set to false. Result ...
Using the Web Audio API - Web APIs
Our HTMLMediaElement fires an ended event once it's finished playing, so we can listen for that and run code accordingly: audioElement.addEventListener('ended', () => { playB...
...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); Mo...
window.cancelIdleCallback() - Web APIs
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support YesSafari No support NoWebView Android Full support 47Chrome Android Full support 47...
...To change preferences in Firefox, visit about:config.Opera Android Full support YesSafari iOS No support NoSamsung Internet Android Full support 5.0Legend Full support Full support ...
Window.closed - Web APIs
Web › API › Window › closed
false: The window is open. Examples Change the URL of a window from a popup The following example demonstrates how a popup window can change the URL of the window that opened it. ...
...ned popup In this example the function refreshPopupWindow() calls the reload() method of the popup's location object to refresh its data. If the popup hasn't been opened yet or the user has closed it a new window is opened. const popupWindow = null; function refreshPopupWindow() { if (popupWindow && !popupWindow.closed) { // popupWindow is open, refresh it popupWindow.location.reload(true); } else { // Open a new popup window popupWindow = window.open('popup.html', 'dataWindow'); } } Specification Specification Status Comment HTML Living StandardThe definition of 'window.closed' in that specification. Living Standard ...
Window.event - Web APIs
Web › API › Window › event
To change preferences in Firefox, visit about:config.IE Full support 4Opera Full support 7Safari Full support 1.1WebView Android Full support 1Chrome Android Full support 1...
...To change preferences in Firefox, visit about:config.Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0Legend Full support Full supportSee impleme...
Window.matchMedia() - Web APIs
Web › API › Window › matchMedia
s properties and events to detect matches and to monitor for changes to those matches over time. Usage notes You can use the returned media query to perform both instantanteous and event-driven checks to see if the document matches the media query. To perform a one-time, instantaneous check to see if the document matches the media query, look at the value of the matches property, which will be true if the document meets the media query's requirements. If you need to be kept aware of whether or not the document matches the media query at all times, you can instead watch for the change event to be delivered to the object. There's a good example of this in the article on Window.devicePixelRatio. Examples This example runs the media query (max-width: 600px) and displays the value of the res...
...whether or not the document matches the media query at all times, you can instead watch for the change event to be delivered to the object. There's a good example of this in the article on Window.devicePixelRatio. 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. JavaScript let mql = window.matchMedia('(max-width: 600px)'); document.querySelector(".mq-value").innerText = mql.matches; The JavaScript code simply passes the media query to match into matchMedia() to compile it, then sets the <span>'s innerText to the value of the results' mat...
Privileged features - Web APIs
so that starting in Gecko 2.0, you can use window.showModalDialog() without UniversalBrowserWrite privileges. titlebar By default, all new secondary windows have a titlebar. If set to no or 0, this feature removes the titlebar from the new secondary window. Mozilla and Firefox users can force new windows to always render the titlebar by setting dom.disable_window_open_feature.titlebar to true in about:config or in their user.js file. alwaysRaised If on, the new window will always be displayed on top of other browser windows, regardless of whether it is active or not. alwaysLowered If on, the new created window floats below, under its own parent when the parent window is not minimized. alwaysLowered windows are often referred as pop-under windows. The alwaysLowered window can not b...
...refox 66 (see bug 1519893). z-lock Same as alwaysLowered. close When set to no or 0, this feature removes the system close command icon and system close menu item. It will only work for dialog windows (dialog feature set). close=no will override minimizable=yes. Mozilla and Firefox users can force new windows to always have a close button by setting dom.disable_window_open_feature.close to true in about:config or in their user.js file. ...
Window.open() - Web APIs
Web › API › Window › open
references. We recommend to always set the resizability and scrollbars presence (if needed) to yes to insure accessibility to content and usability of windows. This is in the best interests of both the web author and the users. How do I resize a window to fit its content? You cannot reliably because the users can prevent the window from being resized by setting dom.disable_window_move_resize to true in about:config or by editing accordingly their user.js file. In general, users usually disable moving and resizing of existing windows because allowing authors' scripts to do so has been abused overwhelmingly in the past and the rare scripts that do not abuse such feature are often wrong, inaccurate when resizing the window. 99% of all those scripts disable window resizability and disable scrol...
...if their calculations are wrong. The window method sizeToContent() can also be disabled. Moving and resizing a window remotely on the user's screen via script will very often annoy the users, will disorient the user, and will be wrong at best. The web author expects to have full control of (and can decide about) every position and size aspects of the users' browser window ... which is simply not true. How do I open a referenced resource of a link in a new tab? or in a specific tab? To open a resource in a new tab see Tabbed browser. Some Code snippets are available. If you are using the SDK, tabs are handled a bit differently K-meleon 1.1, a Mozilla-based browser, gives complete control and power to the user regarding how links are opened. Only the user can set his advanced preferences to ...
Window - Web APIs
Web › API › Window
functionality such as storing assets for offline use, and generating custom responses to requests. WindowOrWorkerGlobalScope.indexedDB Read only Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an IDBFactory object. WindowOrWorkerGlobalScope.isSecureContext Read only Returns a boolean indicating whether the current context is secure (true) or not (false). WindowOrWorkerGlobalScope.origin Read only Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.) Deprecated properties Window.content and Window._content Read only Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only avail...
...s a paste action through the browser's user interface. Also available via the onpaste property. Connection events offline Fired when the browser has lost access to the network and the value of navigator.onLine has switched to false. Also available via the onoffline property. online Fired when the browser has gained access to the network and the value of navigator.onLine has switched to true. Also available via the ononline property. Focus events blur Fired when an element has lost focus. Also available via the onblur property. focus Fired when an element has gained focus. Also available via the onfocus property Gamepad events gamepadconnected Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used. Als...
WorkerGlobalScope.navigator - Web APIs
lue A WorkerNavigator object. ...
... Specifications Specification Status...
WorkerGlobalScope - Web APIs
functionality such as storing assets for offline use, and generating custom responses to requests. WindowOrWorkerGlobalScope.indexedDB Read only Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an IDBFactory object. WindowOrWorkerGlobalScope.isSecureContext Read only Returns a boolean indicating whether the current context is secure (true) or not (false). WindowOrWorkerGlobalScope.origin Read only Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.) Events error Fired when an error occured. Also available via the WorkerGlobalScope.onerror property. offline Fired when the browser has lost access to the network and the value of navigator.onLine switched ...
...) Events error Fired when an error occured. Also available via the WorkerGlobalScope.onerror property. offline Fired when the browser has lost access to the network and the value of navigator.onLine switched to false. Also available via the WorkerGlobalScope.onoffline property. online Fired when the browser has gained access to the network and the value of navigator.onLine switched to true. Also available via the WorkerGlobalScope.ononline property. languagechange Fired at the global/worker scope object when the user's preferred languages change. Also available via the WorkerGlobalScope.onlanguagechange property. close Is an EventHandler representing the code to be called when the close event is raised. Also available via the WorkerGlobalScope.onclose property. rejec...
WritableStream.WritableStream() - Web APIs
() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelector('ul'); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter const defaultWriter = writableStream.getWriter(); const encoder = new TextEncoder(); const encoded = encoder.encode(message, { stream: true }); encoded.forEach((chunk) => { defaultWriter.ready .then(() => { return defaultWriter.write(chunk); }) .then(() => { console.log("Chunk written to sink."); }) .catch((err) => { console.log("Chunk error:", err); }); }); // Call ready again to ensure that all chunks are written // before closing the writer. defaultWriter.
...ew TextDecoder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink err...
WritableStream.getWriter() - Web APIs
() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelector('ul'); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter const defaultWriter = writableStream.getWriter(); const encoder = new TextEncoder(); const encoded = encoder.encode(message, { stream: true }); encoded.forEach((chunk) => { defaultWriter.ready .then(() => { return defaultWriter.write(chunk); }) .then(() => { console.log("Chunk written to sink."); }) .catch((err) => { console.log("Chunk error:", err); }); }); // Call ready again to ensure that all chunks are written // before closing the writer. defaultWriter.
...ew TextDecoder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink err...
WritableStream - Web APIs
() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelector('ul'); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter const defaultWriter = writableStream.getWriter(); const encoder = new TextEncoder(); const encoded = encoder.encode(message, { stream: true }); encoded.forEach((chunk) => { defaultWriter.ready .then(() => { return defaultWriter.write(chunk); }) .then(() => { console.log("Chunk written to sink."); }) .catch((err) => { console.log("Chunk error:", err); }); }); // Call ready again to ensure that all chunks are written // before closing the writer. defaultWriter.
...ew TextDecoder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink err...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelector('ul'); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter const defaultWriter = writableStream.getWriter(); const encoder = new TextEncoder(); const encoded = encoder.encode(message, { stream: true }); encoded.forEach((chunk) => { defaultWriter.ready .then(() => { return defaultWriter.write(chunk); }) .then(() => { console.log("Chunk written to sink."); }) .catch((err) => { console.log("Chunk error:", err); }); }); // Call ready again to ensure that all chunks are written // before closing the writer. defaultWriter.
...ew TextDecoder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink err...
WritableStreamDefaultWriter.close() - Web APIs
() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelector('ul'); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter const defaultWriter = writableStream.getWriter(); const encoder = new TextEncoder(); const encoded = encoder.encode(message, { stream: true }); encoded.forEach((chunk) => { defaultWriter.ready .then(() => { return defaultWriter.write(chunk); }) .then(() => { console.log("Chunk written to sink."); }) .catch((err) => { console.log("Chunk error:", err); }); }); // Call ready again to ensure that all chunks are written // before closing the writer. defaultWriter.
...ew TextDecoder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink err...
WritableStreamDefaultWriter.write() - Web APIs
() and close() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelector('ul'); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter const defaultWriter = writableStream.getWriter(); const encoder = new TextEncoder(); const encoded = encoder.encode(message, { stream: true }); encoded.forEach((chunk) => { defaultWriter.ready .then(() => { return defaultWriter.write(chunk); }) .then(() => { console.log("Chunk written to sink."); }) .catch((err) => { console.log("Chunk error:", err); }); }); // Call ready again to ensure that all chunks are written // before closing the writer. defaultWriter.
...ew TextDecoder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console.log("Sink err...
WritableStreamDefaultWriter - Web APIs
ose() return promises that are processed to deal with success or failure of chunks and streams. const list = document.querySelector('ul'); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter const defaultWriter = writableStream.getWriter(); const encoder = new TextEncoder(); const encoded = encoder.encode(message, { stream: true }); encoded.forEach((chunk) => { defaultWriter.ready .then(() => { return defaultWriter.write(chunk); }) .then(() => { console.log("Chunk written to sink."); }) .catch((err) => { console.log("Chunk error:", err); }); }); // Call ready again to ensure that all chunks are written // before closing the writer. ...
...oder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream({ // Implement the sink write(chunk) { return new Promise((resolve, reject) => { var buffer = new ArrayBuffer(2); var view = new Uint16Array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listItem = document.createElement('li'); listItem.textContent = "Chunk decoded: " + decoded; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { var listItem = document.createElement('li'); listItem.textContent = "[MESSAGE RECEIVED] " + result; list.appendChild(listItem); }, abort(err) { console...
XMLHttpRequest() - Web APIs
const request = new XMLHttpRequest(); Parameters None. Return value A new XMLHttpRequest object. The object must be prepared by at least calling open() to initialize it before calling send() to send the request to the server. Non-standard Firefox syntax Firefox 16 added a non-standard parameter to the constructor that can enable anonymous mode (see bug 692677). ...
...the constructor that can enable anonymous mode (see bug 692677). Setting the mozAnon flag to true effectively resembles the AnonXMLHttpRequest() constructor described in older versions of the XMLHttpRequest specification. const request = new XMLHttpRequest(paramsDictionary); Parameters (non-standard) objParameters There are two flags you can set: mozAnon Boolean: Setting this flag to true will cause the browser not to expose the origin and user credentials when fetching resources. Most important, this means that cookies will not be sent unless explicitly added using setRequestHeader. mozSystem Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting mozAnon: true, i.e. this can't be combined wit...
XMLHttpRequest.send() - Web APIs
conjunction with the send() method. Return value undefined. Exceptions Exception Description InvalidStateError send() has already been invoked for the request, and/or the request is complete. NetworkError The resource type to be fetched is a Blob, and the method is not GET. ...
...tched is a Blob, and the method is not GET. Example: GET var xhr = new XMLHttpRequest(); xhr.open('GET', '/server', true); xhr.onload = function () { // Request finished. Do processing here. }; xhr.send(null); // xhr.send('string'); // xhr.send(new Blob()); // xhr.send(new Int8Array()); // xhr.send(document); Example: POST var xhr = new XMLHttpRequest(); xhr.open("POST", '/server', true); //Send the proper header information along with the request xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { // Call a function when the state changes. if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { // Request finished. Do processing here. } } xhr.send("foo=bar&lorem=ipsum"); // xhr.send(new...
XRSession.updateRenderState() - Web APIs
for an inline XRSession. The projection matrix calculation also takes into account the output canvas's aspect ratio. This property must not be specified for immersive sessions, so the value is null by default for immersive sessions. The default value is otherwise ? * 0.5 (half of the value of pi). Return value None. Exceptions This method may throw any of the following exceptions. These are true exceptions, since this method does not return a promise. InvalidStateError This may occur for one of the following reasons: The XRSession has already ended, so you cannot change its render state. The baseLayer specified in newState was created by an XRSession other than the one on which updateRenderState() was called. The inlineVerticalFieldOfView property was set, but the session ...
... not allow this property to be used. Examples This example creates a WebGL context that is compatible with an immersive XR device and then uses it to create an XRWebGLLayer. updateRenderState() is then called to associate the new XRWebGLLayer. function onXRSessionStarted(xrSession) { let glCanvas = document.createElement("canvas"); let gl = glCanvas.getContext("webgl", { xrCompatible: true }); loadWebGLResources(); xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSession, gl) }); } Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSession.updateRenderState()' in that specification. Working Draft Initial definition. ...
XRSystem: isSessionSupported() - Web APIs
The XRSystem method isSessionSupported() returns a promise which resolves to true if the specified WebXR session mode is supported by the user's WebXR device. Otherwise, the promise resolves with false. If the no devices are available or the browser doesn't have permission to use the XR device, the promise is rejected with an appropriate DOMException. Syntax var isSupportedPromise = xr.isSessionSupported(xrSessionMode) Parameters xrSessionMode A DOMString specifying the WebXR session mode for which support is to be checked. This string must be one of inline (to present the WebXR content inline within the context of an HTML document) or immersive-vr for a fully-immersive virtual experience. ...
...ion. Syntax var isSupportedPromise = xr.isSessionSupported(xrSessionMode) Parameters xrSessionMode A DOMString specifying the WebXR session mode for which support is to be checked. This string must be one of inline (to present the WebXR content inline within the context of an HTML document) or immersive-vr for a fully-immersive virtual experience. Return value A Promise that resolves to true if the specified session mode is supported; otherwise the promise resolves to false. Exceptions Rather than throwing true exceptions, isSessionSupported() rejects the returned promise, passing to the rejection handler a DOMException whose name is one of the following strings. SecurityError The document's origin does not have permission to use the xr-spatial-tracking feature policy. Exampl...
XRSystem - Web APIs
Web › API › XRSystem
nteract with the Augmented Reality (AR) or Virtual Reality (VR) device. Properties While XRSystem directly offers no properties, it does inherit properties from its parent interface, EventTarget. Methods In addition to inheriting methods from its parent interface, EventTarget, the XRSystem interface includes the following methods: isSessionSupported() Returns a promise which resolves to true if the browser supports the given XRSessionMode. Resolves to false if the specified mode isn't supported. requestSession() Returns a promise that resolves to a new XRSession with the specified XRSessionMode. Events devicechange Sent when the set of available XR devices has changed. Also available using the ondevicechange event handler. Usage notes Thsi interface was previously kno...
...mply replace that with XRSystem. Examples The following example shows how to use both isSessionSupported() and requestSession(). 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. onSessionStarted(xrSession); }); } else { // Shut down the already running XRSession xrSession.end() .then(() => xrSession = null); } } This code starts by checking to see i...
XRWebGLLayer.antialias - Web APIs
Otherwise, this property is false. When the WebXR compositor is enabled, this value corresponds to the value of the antialias property on the object returned by the WebGL context's getContentAttributes() method. ...
...Otherwise, this property is false. When the WebXR compositor is enabled, this value corresponds to the value of the antialias property on the object returned by the WebGL context's getContentAttributes() method. ...
XRWebGLLayerInit.depth - Web APIs
; 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. This means that the only source for depth information is the vertex coordinates, and reduces the accuracy and quality of rendering, but may potentially affect the performance of rendering as well. The default value is true. ...
...cify that the new WebGL layer should not have a depth buffer. This means that the only source for depth information is the vertex coordinates, and reduces the accuracy and quality of rendering, but may potentially affect the performance of rendering as well. The default value is true. Usage notes This property differs from ignoreDepthValues in that a layer created with ignoreDepthValues set to true may still have a depth buffer, but will not make use of it. You can determine whether or not the depth buffer is being used by a given WebGL rendering layer during your XR session by checking the value returned by XRWebGLLayer.ignoreDepthValues. If this is true, then the depth buffer is either not present or is being ignored. if (glLayer.ignoreDepthValues) { /* not using the depth buffer */ }...
XRWebGLLayerInit.ignoreDepthValues - Web APIs
depth in that depth requests a WebGL layer that does not have a depth buffer at all, while ignoreDepthValues merely asks that the depth layer be ignored. Syntax let layerInit = { ignoreDepthValues: boolValue }; let glLayer = new XRWebGLLayer(xrSession, gl, layerInit); let glLayer = new XRWebGLLayer(xrSession, gl, { ignoreDepthValues: boolValue }); Value A Boolean value which can be set to true to disable the use of the depth buffer by the WebGL rendering layer created by the XRWebGLLayer() constructor. The default value, false, means the depth buffer will be used, if available. Usage notes If ignoreDepthValues is true, the WebXR compositor will ignore the contents of the depth buffer, if it exists, while compositing and rendering the scene. If false, the depth buffer's contents are u...
...depth, and may result in less effective and less comfortable 3D effects. The default is false (depth values are used by default). Example In this example, a new XRWebGLLayer is created for a WebXR session, xrSession. It's configured to ignore depth values or an alpha channel. 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. Working Draft Initial definition. ...
msCapsLockWarningOff - Web APIs
f read/write property turns automatic caps lock warning on or off for validated password input fields. This proprietary property is specific to Internet Explorer and Microsoft Edge. Starting with Internet Explorer 10, input type=password fields will automatically display a warning if the caps lock is on. This property enables this warning to be disabled. Syntax document.msCapsLockWarningOff = true; Value Type: boolean False: Default. Automatic caps lock warning is turned on. True: Automatic caps lock warning is turned off. Example Fiddle: http://jsfiddle.net/jonathansampson/mqcHA/1/ Example 2 <html> <head> <title>msCapsLockWarningOff example</title> <script type="text/javascript"> function capsOff() { if (document.msCapsLockWarningOff == false) {...
...ic caps lock warning is turned on. True: Automatic caps lock warning is turned off. ...
ARIA Screen Reader Implementors Guide - Accessibility
create a second, additional queue if the user configures a second hardware channel: If there are two channels for presentation (e.g. text to speech and a Braille display), then two queues can be maintained to allow for parallel presentation. The channels could be user configured for presenting live regions based on role or politeness. Busy regions: Any changes in a region marked with aria-busy="true" should not be added to the queue until that attribute is cleared. Politeness (aria-live or from role) takes first precedence,: items should be added to the queue based on their politeness level from the aria-live property or inherited from the role (e.g. role="log" is polite by default). Assertive items are first then politeness level. Alternatively, implementations may choose to have a policy ...
...vel. Alternatively, implementations may choose to have a policy of clearing more polite items, e.g. assertive items clear any polite items from the queue. Time takes second precedence: Prioritize items with the same politeness level according to when the event occurs (earlier events come first). Present items of the same politeness level in the order of what occurred first. Atomic (aria-atomic="true") regions with multiple changes should not be presented twice with the same content. As a new event for an atomic region is added to the queue remove an earlier event for the same region. It is probably desirable to have at least a tiny timeout before presenting atomic region changes, in order to avoid presenting the region twice for two changes that occur quickly one after the other. Include la...
Using the progressbar role - Accessibility
is indeterminate, the developer should omit the aria-valuenow attribute. As the task progresses, the aria-valuenow value has to be updated dynamically to indicate this progress to assistive technology products. If the progressbar is describing the loading progress of a particular region of a page, the author SHOULD use aria-describedby to point to the status, and set the aria-busy attribute to true on the region until it is finished loading. It is not possible for the user to alter the value of a progressbar because it is always readonly. Note: Assistive technologies generally will render the value of aria-valuenow as a percent of the range between the value of aria-valuemin and aria-valuemax, unless aria-valuetext is specified. It is best to set the values for aria-valuemin, aria-valuemax...
...tive technologies generally will render the value of aria-valuenow as a percent of the range between the value of aria-valuemin and aria-valuemax, unless aria-valuetext is specified. It is best to set the values for aria-valuemin, aria-valuemax, and aria-valuenow in a manner that is appropriate for this calculation. Note: Elements with the role progressbar have an implicit aria-readonly value of true. Possible effects on user agents and assistive technology Screen readers should announce the progress updates as they occur. If the progress bar is labeled, the label text should be mentioned as well. Note: Opinions may differ on how assistive technology should handle this. The information provided above is one of those opinions and therefore not normative. Examples Example 1: Basic progres...
ARIA: timer role - Accessibility
ontent will be announced. For instance, when the clock changes from "17:33" to "17:34", assistive technologies will only announce "4", which won't be very useful to users. One way around this would be to first clear the contents of the live region, and then inject the new content. However, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates. ...
...is would be to first clear the contents of the live region, and then inject the new content. However, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates. aria-atomic="true" ensures that each time the live region is updated, the entirety of the content is announced in full (e.g. "Time: 17:34"). <div id="clock" role="timer" aria-live="polite" aria-atomic="true"></div> Accessibility concerns Improperly using the timer role can unintentionally XXX Specifications Specification Status Accessible Rich Internet Applications (WAI-ARIA) 1.1The definition of 'timer' in that specification. Recommendation Precedence order Applying the timer role will cause this and all of the descendant elements of this element to be treated li...
ARIA: row role - Accessibility
wheader" A header cell that is the structural equivalent of the HTML <th> element with a row scope. Unlike a plain cell, the rowheader role establishes a relationship between it and all cells in the corresponding row. States and properties aria-expanded state The aria-expanded attribute, which defines the state of the row, can take one of three values, or be omitted: aria-expanded="true: Row is currently expanded. aria-expanded="false": Row is currently collapsed. aria-expended="undefined" or the attribute is missing: The row is neither expandable nor collapsible. If the element with the aria-expanded attribute controls the expansion of another grouping container that is not 'owned by' the element, the author should reference the container by using the aria-controls attr...
...expansion of another grouping container that is not 'owned by' the element, the author should reference the container by using the aria-controls attribute. aria-selected state Only relevant if the row is in an interactive container, such as a grid or treegrid, but not relevant if the row is in a table. 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-selected="undefined" or the attribute is missing: The row is not selectable. aria-colindex attribute The aria-colindex attribute is only needed if columns are hidden from the DOM. It is generally placed on row children, rather than on the row itself. If the columns displayed are contiguous, then it ...
An overview of accessible web applications and widgets - Accessibility
e should be used to declare CSS to visually hide an element using display:none. Here is an example of a tooltip that uses aria-hidden to control the visibility of the tooltip. The example shows a simple web form with tooltips containing instructions associated with the entry fields. In this example, the HTML for the tooltip has the form shown in Example 2a. Line 9 sets the aria-hidden state to true. ...
... Line 9 sets the aria-hidden state to true. Example 2a. 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. Note that there is no custom classname used, only the status of the aria-hidden attribute on line 1. Example 2b. Attribute-based selector for indicating state div.tooltip[aria-hidden="true"] { display: none; } The JavaScript to update the aria-hidden property has the form shown in Example 2c. Note th...
Text labels and names - Accessibility
ing a name that describes the symbol. Since mglyph elements are used for non-standard symbols without Unicode definitions, screen readers won't automatically be able to name them. Alternative text helps users of screen readers understand the symbol. Headings must be labeled Make sure that your headings have non-empty text content, and are not hidden, such as with CSS display:none or aria-hidden=true. Users of screen readers rely on headings to understand the structure and content of a document. Also, be sure you are using heading elements only for actual section headings, and not as a shortcut way to make text stand out. Screen reader users typically "skim" a page's headings, much like sighted users; non-heading text that is marked-up with heading elements can cause confusion. Headings sho...
...ctual section headings, and not as a shortcut way to make text stand out. Screen reader users typically "skim" a page's headings, much like sighted users; non-heading text that is marked-up with heading elements can cause confusion. Headings should have visible text content Make sure that your headings have non-empty text content, and are not hidden, such as with CSS display:none or aria-hidden=true. Users of screen readers rely on headings to understand the structure and content of a document. Do not use heading elements to mark up images or other graphical content. Use title attribute to describe <iframe> content Make sure that <iframe> elements have a title attribute to describe the contents of the frame. Without a title, users of assistive technologies have to navigate into the frame i...
:host() - CSS: Cascading Style Sheets
Web › CSS › :host()
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 41Safari Full support 10Notes Full support 10Notes Notes Certain CSS selectors do not work (:host > .local-child) and styling sl...
...To change preferences in Firefox, visit about:config.Opera Android Full support 41Safari iOS Full support 10Notes Full support 10Notes Notes Certain CSS selectors do not work (:host > .local-child) and styling slotted content (::slotted) is buggy.Samsung Intern...
:host - CSS: Cascading Style Sheets
Web › CSS › :host
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 41Safari Full support 10WebView Android Full support 54Chrome Android Full support 5...
...To change preferences in Firefox, visit about:config.Opera Android Full support 41Safari iOS Full support 10Samsung Internet Android Full support 6.0Legend Full support Full support ...
:scope - CSS: Cascading Style Sheets
Web › CSS › :scope
e scoped> made it possible to explicitly set up element scopes, but ongoing discussions about the design of this feature as well as lack of other implementations resulted in the decision to remove it. No support 20 -- 32Disabled Disabled From version 20 until version 32 (exclusive): this feature is behind the layout.css.scope-pseudo.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 15Safari Full support 7WebView Android Full support <=37Chrome Android Full support ...
...pported. <style scoped> made it possible to explicitly set up element scopes, but ongoing discussions about the design of this feature as well as lack of other implementations resulted in the decision to remove it. Full support 20Disabled Disabled From version 20: this feature is behind the layout.css.scope-pseudo.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.Opera Android Full support 15Safari iOS Full support 7Samsung Internet Android Full support 1.5Support in DOM API such as in querySelector() and querySelectorAll()Chrome Full support ...
font-stretch - CSS: Cascading Style Sheets
<percentage> A <percentage> value between 50% and 200% (inclusive). Negative values are not allowed for this property. In earlier versions of the font-stretch specification, the property accepts only the nine keyword values. CSS Fonts Level 4 extends the syntax to accept a <percentage> value as well. This enables variable fonts to offer something more like a continuum of character widths. For TrueType or OpenType variable fonts, the "wdth" variation is used to implement varying widths. If the font does not provide a face that exactly matches the given value, then values less than 100% map to a narrower face, and values greater than or equal to 100% map to a wider face. Keyword to numeric mapping The table below shows the mapping between keyword values and numeric percentages: ...
...expanded 150% ultra-expanded 200% Variable fonts Most fonts have a particular width which corresponds to one of the keyterm values. However some fonts, called variable fonts, can support a range of stretching with more or less fine granularity, and this can give the designer a much closer degree of control over the chosen weight. For this, percentage ranges are useful. For TrueType or OpenType variable fonts, the "wdth" variation is used to implement varying glyph widths. Accessibility concerns People with dyslexia and other cognitive conditions may have difficulty reading fonts that are too condensed, especially if the font has a low contrast color ratio. MDN Understanding WCAG, Guideline 1.4 explanations Understanding Success Criterion 1.4.8 | W3C Understanding ...
Detecting CSS animation support - CSS: Cascading Style Sheets
demonstrates a technique for doing this. Testing for CSS animation support This code will check to see if CSS animation support is available: var animation = false, animationstring = 'animation', keyframeprefix = '', domPrefixes = 'Webkit Moz O ms Khtml'.split(' '), pfx = '', elem = document.createElement('div'); if( elem.style.animationName !== undefined ) { animation = true; } if( animation === false ) { for( var i = 0; i < domPrefixes.length; i++ ) { if( elem.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) { pfx = domPrefixes[ i ]; animationstring = pfx + 'Animation'; keyframeprefix = '-' + pfx.toLowerCase() + '-'; animation = true; break; } } } For starters we define a few variables. We assume that animation i...
...to date, none of them do. 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. Once this code is finished running, the value of animation will be false if CSS animation support isn't available, or it will be true. If it is true then both the animation property name and the keyframe prefix will be the right ones. So if you use a new Firefox, the property will be MozAnimation and the keyframe prefix -moz- and with Chrome it'll be WebkitAnimation and -webkit-. Notice browsers don't make it easy with the switching between camelCase and hyphen-ation. Animating using the correct syntax for different browsers ...
Using CSS transitions - CSS: Cascading Style Sheets
ertyName A string indicating the name of the CSS property whose transition completed. elapsedTime A float indicating the number of seconds the transition had been running at the time the event fired. This value isn't affected by the value of transition-delay. ...
...affected by the value of transition-delay. As usual, you can use the addEventListener() method to monitor for this event: el.addEventListener("transitionend", updateTransition, true); You detect the beginning of a transition using transitionrun (fires before any delay) and transitionstart (fires after any delay), in the same kind of fashion: el.addEventListener("transitionrun", signalStart, true); el.addEventListener("transitionstart", signalStart, true); Note: The transitionend event doesn't fire if the transition is aborted before the transition is completed because either the element is made display: none or the animating property's value is changed. Specifications Specification Status Comment CSS Transitions Working Draft Initial definition ...
animation-delay - CSS: Cascading Style Sheets
y some platforms, such as Windows. Full support 49Prefixed Prefixed Implemented with the vendor prefix: -webkit- Full support 44Prefixed Disabled Prefixed Implemented with the vendor prefix: -webkit-Disabled From version 44: this feature is behind the layout.css.prefixes.webkit preference (needs to be set to true). To change preferences in Firefox, visit about:config. Full support 5Prefixed Prefixed Implemented with the vendor prefix: -moz-IE Full support 10Opera Full support 30 Full support 30 Full support ...
...To change preferences in Firefox, visit about:config. Full support 5Prefixed Prefixed Implemented with the vendor prefix: -moz-Opera Android Full support 30 Full support 30 Full support 14Prefixed Prefixed Implemented...
animation-direction - CSS: Cascading Style Sheets
To change preferences in Firefox, visit about:config. Full support 5Prefixed Prefixed Implemented with the vendor prefix: -moz-IE Full support 10Opera Full support 30 Full support 30 Full support ...
...To change preferences in Firefox, visit about:config. Full support 5Prefixed Prefixed Implemented with the vendor prefix: -moz-Opera Android Full support 30 Full support 30 Full support 14Prefixed Prefixed Implemented...
aspect-ratio - CSS: Cascading Style Sheets
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari No support NoWebView Android Partial support 79Notes Partial support 79Notes Notes Webview 79 adds internal suppor...
...To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari No support NoWebView Android Full support 79Chrome Android Full support 79Fir...
box-direction - CSS: Cascading Style Sheets
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 15Prefixed Full support 15Prefixed Prefixed Implemented with the vendor prefix: -webkit-Safari Full support 3Prefixed ...
...To change preferences in Firefox, visit about:config.Opera Android Full support 14Prefixed Full support 14Prefixed Prefixed Implemented with the vendor prefix: -webkit-Safari iOS Full support 1Prefixed Full support ...
<color> - CSS: Cascading Style Sheets
ored item completely visible. Technically, transparent is a shortcut for rgba(0,0,0,0). Compatibility note: To prevent unexpected behavior, such as in a <gradient>, the current CSS spec states that transparent should be calculated in the alpha-premultiplied color space. However, be aware that older browsers may treat it as black with an alpha value of 0. Historical note: transparent wasn't a true color in CSS Level 2 (Revision 1). It was a special keyword that could be used instead of a regular <color> value on two CSS properties: background and border. It was essentially added to allow developers to override an inherited solid color. With the advent of alpha channels in CSS Colors Level 3, transparent was redefined as a true color. It can now be used wherever a <color> value can be used.
...document.querySelector('div'); function validTextColor(stringToTest) { if (stringToTest === "") { return false; } if (stringToTest === "inherit") { return false; } if (stringToTest === "transparent") { return false; } const image = document.createElement("img"); image.style.color = "rgb(0, 0, 0)"; image.style.color = stringToTest; if (image.style.color !== "rgb(0, 0, 0)") { return true; } image.style.color = "rgb(255, 255, 255)"; image.style.color = stringToTest; return image.style.color !== "rgb(255, 255, 255)"; } inputElem.addEventListener('change', () => { if(validTextColor(inputElem.value)) { divElem.style.backgroundColor = inputElem.value; divElem.textContent = ''; } else { divElem.style.backgroundColor = 'white'; divElem.textContent = 'Invalid c...
font-variant-caps - CSS: Cascading Style Sheets
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 39Safari No support NoWebView Android Full support 52Chrome Android Full support 52F...
...To change preferences in Firefox, visit about:config.Opera Android Full support 41Safari iOS No support NoSamsung Internet Android Full support 6.0Legend Full support Full support ...
font-variant-position - CSS: Cascading Style Sheets
To change preferences in Firefox, visit about:config.IE No support NoOpera No support NoSafari No support NoWebView Android No support NoChrome Android No support NoFirefox...
...To change preferences in Firefox, visit about:config.Opera Android No support NoSafari iOS No support NoSamsung Internet Android No support NoLegend Full support Full support ...
font-variant - CSS: Cascading Style Sheets
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 39Safari Full support 9.1WebView Android Full support 52Chrome Android Full support ...
...To change preferences in Firefox, visit about:config.Opera Android Full support 41Safari iOS Full support 9.3Samsung Internet Android Full support 6.0Greek accented charactersChrome No support NoNotes ...
position - CSS: Cascading Style Sheets
Web › CSS › position
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 43Safari Full support 6.1Prefixed Full support 6.1Prefixed Prefixed Implemented with the vendor prefix: -webkit-WebView Android ...
...To change preferences in Firefox, visit about:config.Opera Android Full support 43Safari iOS Full support 6.1Prefixed Full support 6.1Prefixed Prefixed Implemented with the vendor prefix: -webkit-Samsung Internet Android Full support ...
<url> - CSS: Cascading Style Sheets
Web › CSS › url
as an image or a font. URLs can be used in numerous CSS properties, such as background-image, cursor, and list-style. URI or URL? There is a difference between a URI and a URL. A URI simply identifies a resource. A URL is a type of URI, and describes the location of a resource. A URI can be either a URL or a name (URN) of a resource. In CSS Level 1, the url() functional notation described only true URLs. In CSS Level 2, the definition of url() was extended to describe any URI, whether a URL or a URN. Confusingly, this meant that url() could be used to create a <uri> CSS data type. This change was not only awkward but, debatably, unnecessary, since URNs are almost never used in actual CSS. To alleviate the confusion, CSS Level 3 returned to the narrower, initial definition. Now, url() denote...
...In CSS Level 2, the definition of url() was extended to describe any URI, whether a URL or a URN. Confusingly, this meant that url() could be used to create a <uri> CSS data type. This change was not only awkward but, debatably, unnecessary, since URNs are almost never used in actual CSS. To alleviate the confusion, CSS Level 3 returned to the narrower, initial definition. Now, url() denotes only true <url>s. Syntax The <url> data type is specified using the url() functional notation. It may be written without quotes, or surrounded by single or double quotes. Relative URLs are allowed, and are relative to the URL of the stylesheet (not to the URL of the web page). If you choose to write the URL without quotes, use a backslash (\) before any parentheses, whitespace characters, single quotes...
Cross-browser audio basics - Developer guides
These are also deprecated, and soon won't work in any modern browsers. Manipulating the Audio Element with JavaScript...
...value to 0. canPlayType The canPlayType() method asks the browser whether a certain audio file type is supported. It takes the mime type of the type to check as a parameter. if (myAudio.canPlayType('audio/mpeg')) { // It's supported. // Do something here! } canPlayType() returns one of three values: probably maybe "" (an empty string) In practice, we usually check if the result is true or false. Non-empty strings are true. Note: A very early spec specified that the browser should return no instead of an empty string, but thankfully the number of people using older browsers that implement this version of the spec are few and far between. currentTime The currentTime property gets or sets the current time the audio should play at. This is useful in many ways, for example sinc...
Setting up adaptive streaming media sources - Developer guides
dash:schema:mpd:2011" xsi:schemaLocation="urn:mpeg:dash:schema:mpd:2011 DASH-MPD.xsd" type="static" mediaPresentationDuration="PT654S" minBufferTime="PT2S" profiles="urn:mpeg:dash:profile:isoff-on-demand:2011"> <BaseURL>http://example.com/ondemand/</BaseURL> <Period> <!-- English Audio --> <AdaptationSet mimeType="audio/mp4" codecs="mp4a.40.5" lang="en" subsegmentAlignment="true" subsegmentStartsWithSAP="1"> <Representation id="1" bandwidth="64000"> <BaseURL>ElephantsDream_AAC48K_064.mp4.dash</BaseURL> </Representation> </AdaptationSet> <!-- Video --> <AdaptationSet mimeType="video/mp4" codecs="avc1.42401E" subsegmentAlignment="true" subsegmentStartsWithSAP="1"> <Representation id="2" bandwidth="100000" width="480" height="360"> ...
...rsion="1.0"?> <MPD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:mpeg:DASH:schema:MPD:2011" xsi:schemaLocation="urn:mpeg:DASH:schema:MPD:2011" profiles="urn:mpeg:dash:profile:isoff-main:2011" type="static" mediaPresentationDuration="PT0H9M56.46S"> <BaseURL> http://example.com/segments </BaseURL> <Period start="PT0S"> <AdaptationSet bitstreamSwitching="true"> <Representation id="0" codecs="avc1" mimeType="video/mp4" width="320" height="240" startWithSAP="1" bandwidth="46986"> <SegmentBase> <Initialization sourceURL="main/news100/1.m4s" range="0-862"/> </SegmentBase> <SegmentList duration="1"> <SegmentURL media="main/news100/2.m4s" mediaRange="863-7113"/> <SegmentURL media="ma...
Creating a cross-browser video player - Developer guides
o/tears-of-steel-battle-clip-medium.ogg" type="video/ogg"> <!-- Flash fallback --> <object type="application/x-shockwave-flash" data="flash-player.swf?videoUrl=video/tears-of-steel-battle-clip-medium.mp4" width="1024" height="576"> <param name="movie" value="flash-player.swf?videoUrl=video/tears-of-steel-battle-clip-medium.mp4" /> <param name="allowfullscreen" value="true" /> <param name="wmode" value="transparent" /> <param name="flashvars" value="controlbar=over&amp;image=img/poster.jpg&amp;file=flash-player.swf?videoUrl=video/tears-of-steel-battle-clip-medium.mp4" /> <img alt="Tears of Steel poster image" src="img/poster.jpg" width="1024" height="428" title="No video playback possible, please download the video from the link below" />...
...e); } else { if (videoContainer.requestFullscreen) videoContainer.requestFullscreen(); else if (videoContainer.mozRequestFullScreen) videoContainer.mozRequestFullScreen(); else if (videoContainer.webkitRequestFullScreen) videoContainer.webkitRequestFullScreen(); else if (videoContainer.msRequestFullscreen) videoContainer.msRequestFullscreen(); setFullscreenData(true); } } First of all the function checks if the browser is already in fullscreen mode by calling another function isFullScreen: var isFullScreen = function() { return !!(document.fullscreen || document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement); } This function checks all the various browser prefixed versions to try and det...
Media events - Developer guides
ormation as they're going to. loadstart Sent when loading of the media begins. mozaudioavailable Sent when an audio buffer is provided to the audio layer for processing; the buffer contains raw audio samples that may or may not already have been played by the time you receive the event. pause Sent when the playback state is changed to paused (paused property is true). play Sent when the playback state is no longer paused, as a result of the play method, or the autoplay attribute. playing Sent when the media has enough data to start playing, after the play event, but also when recovering from being stalled, when looping media restarts, and after seeked, if it was playing before seeking. progress Sent periodically to inform ...
...h when the volume is set and when the muted attribute is changed). waiting Sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek). You can easily watch for these events, using code such as the following: var v = document.getElementsByTagName("video")[0]; v.addEventListener("seeked", function() { v.play(); }, true); v.currentTime = 10.0; This example fetches the first video element in the document and attaches an event listener to it, watching for the seeked event, which is sent whenever a seek operation completes. The listener simply calls the element's play() method, which starts playback. Then, in line 3, the example sets the element's currentTime attribute to 10.0, which initiates a seek operation ...
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 DOMEl...
...}, 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. ...
The Web Open Font Format (WOFF) - Developer guides
Web › Guide › WOFF
WOFF (the Web Open Font Format) is a web font format developed by Mozilla in concert with Type Supply, LettError, and other organizations. It uses a compressed version of the same table-based sfnt structure used by TrueType, OpenType, and Open Font Format, but adds metadata and private-use data structures, including predefined fields allowing foundries and vendors to provide license information if desired. There are three main benefits to using WOFF: The font data is compressed, so sites using WOFF will use less bandwidth and will load faster than if they used equivalent uncompressed TrueType or OpenType files. Many font vendors that are unwilling to license their TrueType or OpenType format fonts for use on the web will license WOFF format fonts. This improves availability of fon...
...le font format for the web, unlike other current font formats. There are two versions of WOFF; WOFF and WOFF2, they mostly differ in regard to the compression algorithm used. In @font-face they are identified by the 'woff' and respectively 'woff2' format descriptor. Using WOFF You can use the @font-face CSS property to use WOFF fonts for text in web content. It works exactly like OpenType and TrueType format fonts do, except it will likely let your content download more efficiently due to the addition of compression. Tools for working with WOFF fonts Tools for working with WOFF fonts are available. sfnt2woff and woff2sfnt convert between WOFF and OpenType. Specifications Specification Status Comment WOFF File Format 2.0 Recommendation New compressio...
HTML attribute: required - HTML: Hypertext Markup Language
roup must be check, though it doesn't have to be the one with the attribute is applied. For this reason, to improve code maintenance, it is recommened to either include the required attribute in every same-named radio button in the group or none. In the case of a same named group of checkbox input types, only the checkboxes with the required attribute are required. Note: Setting aria-required="true" tells a screen reader that an element (any element) is required, but has no bearing on the optionality of the element. Attribute interactions Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified. Usability When including the required attribute, provide a visible indication near the control informing the user ...
...dication near the control informing the user that the input, select or textarea is required. In addition, target required form controls with the :required pseudo-class, styling them in a way to indicate they are required. This improves usability for sited user. Assistive technology should inform the user that the form control in mandatory based on the required attribute, but adding aria-required="true" doesn't hurt, in case the browser / screen reader combination does not support required yet. Constraint validation If the element is required and the element's value is the empty string, then the element is suffering from valueMissing and the element will match the :invalid pseudo class. Specifications Specification Status Comment HTML Living StandardThe definiti...
HTML attribute reference - HTML: Hypertext Markup Language
ications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly (select.size, for example) and you should read the specifications to understand how exactly they behave. Boolean Attributes Some content attributes (e.g. required, readonly, disabled) are called boolean attributes. If a boolean attribute is present, its value is true, and if it's absent, its value is false. HTML5 defines restrictions on the allowed values of boolean attributes: If the attribute is present, its value must either be the empty string (equivalently, the attribute may have an unassigned value), or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace. The following examples are ...
...itespace. The following examples are valid ways to mark up a boolean attribute: <div itemscope> This is valid HTML but invalid XML. </div> <div itemscope=itemscope> This is also valid HTML but invalid XML. </div> <div itemscope=""> This is valid HTML and also valid XML. </div> <div itemscope="itemscope"> This is also valid HTML and XML, but perhaps a bit verbose. </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. ...
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › content
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 26Safari No support NoWebView Android Full support 37Chrome Android Full support 37F...
...To change preferences in Firefox, visit about:config.Opera Android ? Safari iOS No support NoSamsung Internet Android Full support 3.0Legend Full support Full support No supp...
<input type="reset"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › reset
ser/OS combination; see accesskey for a useful list of those). <form> <div> <label for="example">Type in some sample text</label> <input id="example" type="text"> </div> <div> <input type="reset" value="Reset the form" accesskey="r"> </div> </form> The problem with the above example is that there's no way for the user to know what the access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the title attribute) can also help, although it's not a complete solu...
...e). Adding a tooltip to the button (using the title attribute) can also help, although it's not a complete solution for accessibility purposes. 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. Note: See the <input type="button"> page for more ideas about enabling and disabling buttons. Validation Buttons don't participate in constraint validation; they have no real value to be constrained. Examples We've included simple examples above. There isn't really anything more to say about reset buttons.
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
x114" href="apple-icon-114.png" type="image/png"> The sizes attribute indicates the icon size, while the type contains the MIME type of the resource being linked. These provide useful hints to allow the browser to choose the most appropriate icon available. You can also provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is true. For example: <link href="print.css" rel="stylesheet" media="print"> <link href="mobile.css" rel="stylesheet" media="screen and (max-width: 600px)"> Some interesting new performance and security features have been added to the <link> element too. Take this example: <link rel="preload" href="myFont.woff2" as="font" type="font/woff2" crossorigin="anonymous"> A rel value of preload indicat...
...x72" href="favicon72.png"> <!-- non-Retina iPhone, iPod Touch, and Android 2.1+ devices: --> <link rel="apple-touch-icon-precomposed" href="favicon57.png"> <!-- basic favicon --> <link rel="icon" href="favicon32.png"> Conditionally loading resources with media queries You can provide a media type or query inside a media attribute; this resource will then only be loaded if the media condition is true. For example: <link href="print.css" rel="stylesheet" media="print"> <link href="mobile.css" rel="stylesheet" media="all"> <link href="desktop.css" rel="stylesheet" media="screen and (min-width: 600px)"> <link href="highres.css" rel="stylesheet" media="screen and (min-resolution: 300dpi)"> Stylesheet load events You can determine when a style sheet has been loaded by watching for a load event...
contenteditable - HTML: Hypertext Markup Language
indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. The attribute must take one of the following values: true or an empty string, which indicates that the element is editable. false, which indicates that the element is not editable. If the attribute is given without a value, like <label contenteditable>Example Label</label>, its value is treated as an empty string. If this attribute is missing or its value is invalid, its value is inherited from its parent element: so the element is editable if its p...
... false, which indicates that the element is not editable. If the attribute is given without a value, like <label contenteditable>Example Label</label>, its value is treated as an empty string. If this attribute is missing or its value is invalid, its value is inherited from its parent element: so the element is editable if its parent is editable. Note that although its allowed values include true and false, this attribute is an enumerated one and not a Boolean one. You can set the color used to draw the text insertion caret with the CSS caret-color property. Specifications Specification Status Comment HTML Living StandardThe definition of 'contenteditable' in that specification. Living Standard No change from latest snapshot, HTML 5.2 HTML 5.2...
draggable - HTML: Hypertext Markup Language
The correct usage is <img draggable="false">. ...
...The correct usage is <img draggable="false">. ...
MIME types (IANA media types) - HTTP
iple files to an email. Discrete types The discrete types currently registered with the IANA are: applicationList at IANA Any kind of binary data that doesn't fall explicitly into one of the other types; either data that will be executed or interpreted in some way or binary data that requires a specific application or category of application to use. Generic binary data (or binary data whose true type is unknown) is application/octet-stream. Other common examples include application/pdf, application/pkcs8, and application/zip. audio List at IANA Audio or music data. Examples include audio/mpeg, audio/vorbis. example Reserved for use as a placeholder in examples showing how to use MIME types. These should never be used outside of sample code listings and documentation. example can also...
...f9b5-- Importance of setting the correct MIME type Most web servers send unrecognized resources as the application/octet-stream MIME type. For security reasons, most browsers do not allow setting a custom default action for such resources, forcing the user to save it to disk to use it. Some common incorrect server configurations: RAR-compressed files. In this case, the ideal would be the true type of the original files; this is often impossible as .RAR files can hold several resources of different types. In this case, configure the server to send application/x-rar-compressed. Audio and video. Only resources with the correct MIME Type will be played in <video> or <audio> elements. Be sure to specify the correct media type for audio and video. Proprietary file types. Avoid u...
HTTP headers - HTTP
Web › HTTP › Headers
er, but has been obsoleted. Use Cookie instead. Set-Cookie2 Sends cookies from the server to the user-agent, but has been obsoleted. Use Set-Cookie instead. CORS Learn more about CORS here. Access-Control-Allow-Origin Indicates whether the response can be shared. Access-Control-Allow-Credentials Indicates whether the response to the request can be exposed when the credentials flag is true. Access-Control-Allow-Headers Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request. Access-Control-Allow-Methods Specifies the methods allowed when accessing the resource in response to a preflight request. Access-Control-Expose-Headers Indicates which headers can be exposed as part of the response by listing their names. Access-...
...ates the request's mode to a server. It is a Structured Header whose value is a token with possible values cors, navigate, nested-navigate, no-cors, same-origin, and websocket. Sec-Fetch-User It is a request header that indicates whether or not a navigation request was triggered by user activation. It is a Structured Header whose value is a boolean so possible values are ?0 for false and ?1 for true. Sec-Fetch-Dest It is a request header that indicates the request's destination to a server. It is a Structured Header whose value is a token with possible values audio, audioworklet, document, embed, empty, font, image, manifest, object, paintworklet, report, script, serviceworker, sharedworker, style, track, video, worker, xslt, and nested-document. Server-sent events Last-Event-ID ... ...
Meta programming - JavaScript
he prototype parameter must be the same value as Object.getPrototypeOf(target). handler.isExtensible() Object.isExtensible() Reflect.isExtensible() Object.isExtensible(proxy) must return the same value as Object.isExtensible(target). handler.preventExtensions() Object.preventExtensions() Reflect.preventExtensions() Object.preventExtensions(proxy) only returns true if Object.isExtensible(proxy) is false. handler.getOwnPropertyDescriptor() Object.getOwnPropertyDescriptor() Reflect.getOwnPropertyDescriptor() getOwnPropertyDescriptor must return an object or undefined. A property cannot be reported as non-existent if it exists as a non-configurable own property of target. A property cannot be reported as non-existent if ...
...gger any trap Reflection Reflect is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of the proxy handlers. Reflect is not a function object. Reflect helps with forwarding default operations from the handler to the target. With Reflect.has() for example, you get the in operator as a function: Reflect.has(Object, 'assign') // true A better apply function In ES5, you typically use the Function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object). Function.prototype.apply.call(Math.floor, undefined, [1.75]) With Reflect.apply this becomes less verbose and easier to understand: Reflect.apply(Math.floor, undefined, [1.75]) // 1 Reflect.apply(St...
JavaScript modules - JavaScript
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 50Safari Full support 11.1WebView Android Full support 63Chrome Android Full support ...
...To change preferences in Firefox, visit about:config.Opera Android Full support 46Safari iOS Full support 11.3Samsung Internet Android Full support 8.0nodejs Full support 13.2.0Notes Full support ...
ReferenceError: can't access lexical declaration`X' before initialization - JavaScript
Error: 'x' is not defined (Chrome) Error type ReferenceError What went wrong? A lexical variable was accessed before it was initialized. This happens within any block statement, when let or const declarations are accessed before they are defined. ...
... variable "foo" is redeclared in the block statement using let. ...
TypeError: can't redefine non-configurable property "x" - JavaScript
able. ...
...value: "bar"}); Object.defineProperty(obj, "foo", {value: "baz"}); // TypeError: can't redefine non-configurable property "foo" You will need to set the "foo" property to configurable, if you intend to redefine it later in the code. var obj = Object.create({}); Object.defineProperty(obj, "foo", {value: "bar", configurable: true}); Object.defineProperty(obj, "foo", {value: "baz", configurable: true}); ...
ReferenceError: assignment to undeclared variable "x" - JavaScript
xt (function or global). Undeclared variables are configurable (e.g. can be deleted). For more details and examples, see the var reference page. Errors about undeclared variable assignments occur in strict mode code only. ...
...e code only. In non-strict code, they are silently ignored. Examples Invalid cases In this case, the variable "bar" is an undeclared variable. ...
Functions - JavaScript
// function declaration function b() {} if (0) { // function expression function c() {} } } Block-level functions In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode. 'use strict'; function f() { return 1; } { function f() { return 2; } } f() === 1; // true // f() === 2 in non-strict mode Block-level functions in non-strict code In a word: Don't. In non-strict code, function declarations inside blocks behave strangely. 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...
...); } } ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not. In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block. A safer way to define functions conditionally is to assign a function expression to a variable: var zero; if (shouldDefineZero) { zero = function() { console.log("This is zero."); }; } Examples Returning a formatted number The following function returns a string containing the formatted representation of a number padded with leading zeros.
AggregateError - JavaScript
eject. Constructor AggregateError() Creates a new AggregateError object. Instance properties AggregateError.prototype.message Error message, defaults to "". AggregateError.prototype.name Error name, defaults to AggregateError. ...
... ...
Array.prototype.copyWithin() - JavaScript
var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } // Step 18. while (count > 0) { if (from in O) { O[to] = O[from]; } else { delete O[to]; } from += direction; to += direction; count--; } // Step 19. ...
...= 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } // Step 18. while (count > 0) { if (from in O) { O[to] = O[from]; } else { delete O[to]; } from += direction; to += direction; count--; } // Step 19. ...
Array.prototype.find() - JavaScript
If thisArg was supplied, let T be thisArg; else let T be undefined. var thisArg = arguments[1]; // 5. Let k be 0. var k = 0; // 6. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). // b. Let kValue be ? Get(O, Pk). // c. Let testResult be ToBoolean(? Call(predicate, T, << kValue, k, O >>)). // d. ...
...e ? Get(O, Pk). // c. Let testResult be ToBoolean(? Call(predicate, T, << kValue, k, O >>)). // d. If testResult is true, return kValue. var kValue = o[k]; if (predicate.call(thisArg, kValue, k, o)) { return kValue; } // e. Increase k by 1. k++; } // 7. Return undefined. return undefined; }, configurable: true, writable: true }); } If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it is best not to polyfill Array.prototype at all, as you cannot make it non-enumerable. Examples Find an object in an array by one of its properties const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity:...
Array.from() - JavaScript
d this by inserting the following code at the beginning of your scripts, allowing use of Array.from() in implementations that don't natively support it. Polyfill Notes: This algorithm is exactly as specified in ECMA-262 6th Edition (assuming Object and TypeError have their original values and that callback.call() evaluates to the original value of Function.prototype.call()). In addition, since true iterables cannot be polyfilled, this implementation does not support generic iterables as defined in the 6th Edition of ECMA-262. // Production steps of ECMA-262, Edition 6, 22.1.2.1 if (!Array.from) { Array.from = (function () { var symbolIterator; try { symbolIterator = Symbol.iterator ? Symbol.iterator : 'Symbol(Symbol.iterator)...
... // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 2) { T = arguments[2]; } } // 10. Let lenValue be Get(items, "length"). // 11. Let len be ToLength(lenValue). var len = toLength(items.length); // 13. If IsConstructor(C) is true, then // 13. a. Let A be the result of calling the [[Construct]] internal method // of C with an argument list containing the single item len. // 14. a. Else, Let A be ArrayCreate(len). var A = isCallable(C) ? Object(new C(len)) : new Array(len); return getArray( T, A, len, ...
Array.prototype.values() - JavaScript
rr.values() Return value A new Array iterator object. Examples Iteration using for...of loop var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" Array.prototype.values is default implementation of Array.prototype[Symbol.iterator]. ...
...'b', 'c', 'd', 'e']; var iterator = arr.values(); iterator.next(); // Object { value: "a", done: false } iterator.next().value; // "b" iterator.next()["value"]; // "c" iterator.next(); // Object { value: "d", done: false } iterator.next(); // Object { value: "e", done: false } iterator.next(); // Object { value: undefined, done: true } iteraror.next().value; // undefined One-use: the array iterator object is one use or temporary object example: var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e" for (let letter of iterator) { console.log(letter); } // undefined reason: When next().done=true or currentIndex>length the...
ArrayBuffer.isView() - JavaScript
s one of the ArrayBuffer views, such as typed array objects or a DataView. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax ArrayBuffer.isView(value) Parameters value The value to be checked. 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 ...
...ffer views; otherwise, false. Examples Using isView ArrayBuffer.isView(); // false ArrayBuffer.isView([]); // false ArrayBuffer.isView({}); // false ArrayBuffer.isView(null); // false ArrayBuffer.isView(undefined); // false ArrayBuffer.isView(new ArrayBuffer(10)); // false ArrayBuffer.isView(new Uint8Array()); // true ArrayBuffer.isView(new Float32Array()); // true ArrayBuffer.isView(new Int8Array(10).subarray(0, 3)); // true const buffer = new ArrayBuffer(2); const dv = new DataView(buffer); ArrayBuffer.isView(dv); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'ArrayBuffer.isView' in that specification. ...
Atomics.isLockFree() - JavaScript
The static Atomics.isLockFree() method is used to determine whether to use locks or atomic operations. It returns true, if the given size is one of the BYTES_PER_ELEMENT property of integer TypedArray types. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Atomics.isLockFree(size) Parameters size The size in bytes to check. Return value A Boolean indicating whether the operation is lock free. ...
...ple is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Atomics.isLockFree(size) Parameters size The size in bytes to check. Return value A Boolean indicating whether the operation is lock free. Examples Using isLockFree Atomics.isLockFree(1); // true Atomics.isLockFree(2); // true Atomics.isLockFree(3); // false Atomics.isLockFree(4); // true Atomics.isLockFree(5); // false Atomics.isLockFree(6); // false Atomics.isLockFree(7); // false Atomics.isLockFree(8); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'Atomics.isLockFree' in that specification. ...
Generator.prototype.return() - JavaScript
the generator. Syntax gen.return(value) Parameters value The value to return. Return value The value that is given as an argument. Examples Using return() The following example shows a simple generator and the return method. 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. If no argument is provided, the value property of returned object is the same as if .next(). If an argument is provided, it will be set to the value of the value property of the returned object. function* gen() {...
...ded, the value property of returned object is the same as if .next(). If an argument is provided, it will be set to the value of the value property of the returned object. function* gen() { yield 1; yield 2; yield 3; } const g = gen(); g.next(); // { value: 1, done: false } g.next(); // { value: 2, done: false } g.next(); // { value: 3, done: false } g.next(); // { value: undefined, done: true } g.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
The throw() method resumes the execution of a generator by throwing an error into it and returns an object with two properties done and value. Syntax gen.throw(exception) Parameters exception The exception to throw. For debugging purposes, it is useful to make it an instanceof Error. Return value An Object with two properties: done (boolean) Has the value true if the iterator is past the end of the iterated sequence. In this case value optionally specifies the return value of the iterator. Has the value false if the iterator was able to produce the next value in the sequence. This is equivalent of not specifying the done property altogether. value Any JavaScript value returned by the iterator. Can be omitted when done is true. Examples Using throw() The followin...
...he next value in the sequence. This is equivalent of not specifying the done property altogether. value Any JavaScript value returned by the iterator. Can be omitted when done is true. Examples Using throw() The following example shows a simple generator and an error that is thrown using the throw method. An error can be caught by a try...catch block as usual. 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. ...
Intl.Collator() constructor - JavaScript
nt collations for certain locales. Possible values include: "big5han", "dict", "direct", "ducet", "gb2312", "phonebk", "phonetic", "pinyin", "reformed", "searchjl", "stroke", "trad", "unihan". The "standard" and "search" values are ignored; they are replaced by the options property usage (see below). kn Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are "true" and "false". This option can be set through an options property or through a Unicode extension key; if both are provided, the options property takes precedence. kf Whether upper case or lower case should sort first. Possible values are "upper", "lower", or "false" (use the locale's default). This option can be set through an options property or through a Unicode extension key; if both are pr...
...!= b, a = a, a != A. "variant": Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples: a != b, a != a, a != A. The default is "variant" for usage "sort"; it's locale dependent for usage "search". ignorePunctuation Whether punctuation should be ignored. Possible values are true and false; the default is false. numeric Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are true and false; the default is false. This option can be set through an options property or through a Unicode extension key; if both are provided, the options property takes precedence. Implementations are not required to support this property. caseFirst Wheth...
JSON.parse() - JavaScript
ber, boolean, or null value corresponding to the given JSON text. Exceptions Throws a SyntaxError exception if the string to parse is not valid JSON. ...
...n for possible transformation. return (typeof reviver === "function") ? walk({ "": j }, "") : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. 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. Specifically, the computed value and all its properties (beginning with the most nested properties and proceeding to the o...
Number.isFinite() - JavaScript
us a pull request. Syntax Number.isFinite(value) Parameters value The value to be tested for finiteness. Return value A Boolean indicating whether or not the given value is a finite number. Description In comparison to the global isFinite() function, this method doesn't forcibly convert the parameter to a number. This means only values of the type number, that are also finite, return true. ...
... number. This means only values of the type number, that are also finite, return true. Polyfill if (Number.isFinite === undefined) Number.isFinite = function(value) { return typeof value === 'number' && isFinite(value); } Examples Using isFinite Number.isFinite(Infinity); // false Number.isFinite(NaN); // false Number.isFinite(-Infinity); // false Number.isFinite(0); // true Number.isFinite(2e64); // true Number.isFinite('0'); // false, would've been true with // global isFinite('0') Number.isFinite(null); // false, would've been true with // global isFinite(null) Specifications Specification ECMAScript (ECMA-262)The definition of 'Number.isInteger' in that specification. ...
Number - JavaScript
ses. 37 is still a Number, not a BigInt.) Number may also be expressed in literal forms like 0b101, 0o13, 0x0A. Learn more on numeric lexical grammar here. Description When used as a function, Number(value) converts a string or other value to the Number type. If the value can't be converted, it returns NaN. Literal syntax 123 // one-hundred twenty-three 123.0 // same 123 === 123.0 // true Function syntax Number('123') // returns the number 123 Number('123') === 123 // true Number("unicorn") // NaN Number(undefined) // NaN Constructor Number() Creates a new Number value. Static properties Number.EPSILON The smallest interval between two representable numbers. Number.MAX_SAFE_INTEGER The maximum safe integer in JavaScript (253 - 1). Number.MAX_VALUE The larges...
...ng instead. Larger numbers can be represented using the BigInt type. Using Number to convert a Date object The following example converts the Date object to a numerical value using Number as a function: let d = new Date('December 17, 1995 03:24:00') console.log(Number(d)) This logs 819199440000. Convert numeric strings and null to numbers Number('123') // 123 Number('123') === 123 /// true Number('12.3') // 12.3 Number('12.00') // 12 Number('123e-1') // 12.3 Number('') // 0 Number(null) // 0 Number('0x11') // 17 Number('0b11') // 3 Number('0o11') // 9 Number('foo') // NaN Number('100a') // NaN Number('-Infinity') //-Infinity Specifications Specification ECMAScript (ECMA-262)The definition of 'Number' in that specification. ...
Object.getOwnPropertyDescriptors() - JavaScript
operties of an object. A property in JavaScript consists of either a string-valued name or a Symbol and a property descriptor. Further information about property descriptor types and their attributes can be found in Object.defineProperty(). A property descriptor is a record with some of the following attributes: value The value associated with the property (data descriptors only). ...
...y (data descriptors only). writable true if and only if the value associated with the property may be changed (data descriptors only). get A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). set A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). configurable true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. enumerable true if and only if this property shows up during enumeration of the properties on the corresponding object. Examples Creating a shallow clone Whereas the Object.assign() method will only copy enumerable and own properties from a source object to a ...
Promise.resolve() - JavaScript
{ // not called }); Resolving an array var p = Promise.resolve([1,2,3]); p.then(function(v) { console.log(v[0]); // 1 }); Resolving another Promise var original = Promise.resolve(33); var cast = Promise.resolve(original); cast.then(function(value) { console.log('value: ' + value); }); console.log('original === cast ? ' + (original === cast)); // logs, in order: // original === cast ? ...
...); // logs, in order: // original === cast ? ...
handler.deleteProperty() - JavaScript
oxy will throw a TypeError: A property cannot be deleted, if it exists as a non-configurable own property of the target object. Examples Trapping the delete operator The following code traps the delete operator. ...
... the delete operator The following code traps the delete operator. const p = new Proxy({}, { deleteProperty: function(target, prop) { if (prop in target){ delete target[prop] console.log('property removed: ' + prop) 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.ownKeys() - JavaScript
ect.getOwnPropertyNames(). const p = new Proxy({}, { ownKeys: function(target) { console.log('called'); return ['a', 'b', 'c']; } }); console.log(Object.getOwnPropertyNames(p)); // "called" // [ 'a', 'b', 'c' ] The following code violates an invariant. ...
...led'); return ['a', 'b', 'c']; } }); console.log(Object.getOwnPropertyNames(p)); // "called" // [ 'a', 'b', 'c' ] The following code violates an invariant. const obj = {}; Object.defineProperty(obj, 'a', { configurable: false, enumerable: true, value: 10 } ); const p = new Proxy(obj, { ownKeys: function(target) { return [123, 12.5, true, false, undefined, null, {}, []]; } }); console.log(Object.getOwnPropertyNames(p)); // TypeError: proxy [[OwnPropertyKeys]] must return an array // with only string and symbol elements Specifications Specification ECMAScript (ECMA-262)The definition of '[[OwnPropertyKeys]]' in that specification. ...
handler.set() - JavaScript
ndler can also be called indirectly, via the prototype chain or various other ways. For example: Suppose a script does obj.name = "jen", and obj is not a proxy, and has no own property .name, but it has a proxy on its prototype chain. That proxy's set() handler will be called, and obj will be passed as the receiver. Return value The set() method should return a boolean value. Return true to indicate that assignment succeeded. If the set() method returns false, and the assignment happened in strict-mode code, a TypeError will be thrown. Description The handler.set() method is a trap for setting property value. Interceptions This trap can intercept these operations: Property assignment: proxy[foo] = bar and proxy.foo = bar Inherited property assignment: Object.create(prox...
... undefined as its [[Set]] attribute. In strict mode, a false return value from the set() handler will throw a TypeError exception. Examples Trap setting of a property value The following code traps setting a property value. const p = new Proxy({}, { set: function(target, prop, value, receiver) { target[prop] = value; console.log('property set: ' + prop + ' = ' + value); return true; } }) console.log('a' in p); // false p.a = 10; // "property set: a = 10" console.log('a' in p); // true console.log(p.a); // 10 Specifications Specification ECMAScript (ECMA-262)The definition of '[[Set]]' in that specification. ...
ReferenceError() constructor - JavaScript
rameters message Optional Optional. Human-readable description of the error. fileName Optional Optional. The name of the file containing the code that caused the exception. lineNumber Optional Optional. The line number of the code that caused the exception. ...
... "ReferenceError" console.log(e.fileName) // "Scratchpad/1" console.log(e.lineNumber) // 2 console.log(e.columnNumber) // 6 console.log(e.stack) // "@Scratchpad/2:2:7\n" } Creating a ReferenceError try { throw new ReferenceError('Hello', 'someFile.js', 10) } catch (e) { console.log(e instanceof ReferenceError) // true console.log(e.message) // "Hello" console.log(e.name) // "ReferenceError" console.log(e.fileName) // "someFile.js" console.log(e.lineNumber) // 10 console.log(e.columnNumber) // 0 console.log(e.stack) // "@Scratchpad/2:2:9\n" } Specifications Specification ...
ReferenceError - JavaScript
r.prototype.lineNumber Line number in file that raised this error. Inherited from Error. ReferenceError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. ReferenceError.prototype.stack Stack trace. Inherited from Error. ...
... "ReferenceError" console.log(e.fileName) // "Scratchpad/1" console.log(e.lineNumber) // 2 console.log(e.columnNumber) // 6 console.log(e.stack) // "@Scratchpad/2:2:7\n" } Creating a ReferenceError try { throw new ReferenceError('Hello', 'someFile.js', 10) } catch (e) { console.log(e instanceof ReferenceError) // true console.log(e.message) // "Hello" console.log(e.name) // "ReferenceError" console.log(e.fileName) // "someFile.js" console.log(e.lineNumber) // 10 console.log(e.columnNumber) // 0 console.log(e.stack) // "@Scratchpad/2:2:9\n" } Specifications Specification ...
Reflect.getOwnPropertyDescriptor() - JavaScript
t. Description The Reflect.getOwnPropertyDescriptor method returns a property descriptor of the given property if it exists in the target object, undefined otherwise. The only difference to Object.getOwnPropertyDescriptor() is how non-object targets are handled. 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. With Object.getOwnPrope...
...rtyDescriptor() If the target argument to this method is not an object (a primitive), then it will cause a TypeError. With Object.getOwnPropertyDescriptor, a non-object first argument will be coerced to an object at first. Reflect.getOwnPropertyDescriptor('foo', 0) // TypeError: "foo" is not non-null object Object.getOwnPropertyDescriptor('foo', 0) // { value: "f", writable: false, enumerable: true, configurable: false } Specifications Specification ECMAScript (ECMA-262)The definition of 'Reflect.getOwnPropertyDescriptor' in that specification. ...
Reflect.setPrototypeOf() - JavaScript
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...ating whether or not the prototype was successfully set. Exceptions A TypeError, if target is not an Object or if prototype is neither an object nor null. Description The Reflect.setPrototypeOf method changes the prototype (i.e. the value of the internal [[Prototype]] property) of the specified object. Examples Using Reflect.setPrototypeOf() Reflect.setPrototypeOf({}, Object.prototype) // true // It can change an object's [[Prototype]] to null. 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 ...
RegExp.prototype.dotAll - JavaScript
roperty indicates whether or not the "s" flag is used with the regular expression. dotAll is a read-only property of an individual regular expression instance. 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. The "s" flag indicates that the dot special character (".") should additionally match the following line terminator ("newline") characters in a string, which it would not match otherwise: U+000A LINE FEED (LF) ("\n") U+000D CARRIAGE RETURN (CR) ("\r") U+2028 LINE SEPARATOR U+2029 PARAGRAPH SEPARATOR This effectively means the dot will match any ...
...sic Multilingual Plane (BMP). To allow it to match astral characters, the "u" (unicode) flag should be used. Using both flags in conjunction allows the dot to match any Unicode character, without exceptions. You cannot change this property directly. ...
RegExp.prototype.exec() - JavaScript
m the previous match. Using this internally, exec() can be used to iterate over multiple matches in a string of text (with capture groups), as opposed to getting just the matching strings with String.prototype.match(). A newer function has been proposed to simplify matching multiple parts of a string (with capture groups): String.prototype.matchAll(). If you are executing a match simply to find true or false, use RegExp.prototype.test() method or String.prototype.search() instead. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax regexObj.exec(str) Parameters str The string against which to match the reg...
... index The 0-based index of the match in the string. 4 input The original string that was matched against. "The Quick Brown Fox Jumps Over The Lazy Dog" re lastIndex The index at which to start the next match. If g is absent, this will always be 0. 25 ignoreCase Indicates if the i flag was used to ignore case. true global Indicates if the g flag was used for a global match. true multiline Indicates if the m flag was used to search across multiple lines. false source The text of the pattern. "quick\s(brown).+?(jumps)" Examples Finding successive matches If your regular expression uses the "g" flag, you can use the exec() method multiple times to find succ...
RegExp.prototype.global - JavaScript
repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. 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. The "g" flag indicates that the regular expression should be tested against all possible matches in a string. A regular expression defined as both global ("g") and sticky ("y") will ignore the global flag and perform sticky matches. You cannot change this property directly. Examples Using global var regex = new RegExp('foo', 'g'); console.log(regex...
...ag was used; otherwise, false. The "g" flag indicates that the regular expression should be tested against all possible matches in a string. A regular expression defined as both global ("g") and sticky ("y") will ignore the global flag and perform sticky matches. You cannot change this property directly. Examples Using global var regex = new RegExp('foo', 'g'); console.log(regex.global); // true var str = 'fooexamplefoo'; var str1 = str.replace(regex, ''); console.log(str1); // Output: example var regex1 = new RegExp('foo'); var str2 = str.replace(regex1, ''); console.log(str2); // Output: examplefoo Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.prototype.global' in that specification. ...
RegExp.prototype.ignoreCase - JavaScript
ry. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...erable no Configurable yes Description The value of ignoreCase is a Boolean and true if the "i" flag was used; otherwise, false. The "i" flag indicates that case should be ignored while attempting a match in a string. You cannot change this property directly. Examples Using ignoreCase var regex = new RegExp('foo', 'i'); console.log(regex.ignoreCase); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.prototype.ignoreCase' in that specification. ...
RegExp.prototype.multiline - JavaScript
y. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Property attributes of RegExp.prototype.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. The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string. You cannot change this property directly. Examples Using multiline var regex = new RegExp('foo', 'm');...
...e, false. The "m" flag indicates that a multiline input string should be treated as multiple lines. For example, if "m" is used, "^" and "$" change from matching at only the start or end of the entire string to the start or end of any line within the string. You cannot change this property directly. Examples Using multiline var regex = new RegExp('foo', 'm'); console.log(regex.multiline); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.prototype.multiline' in that specification. ...
RegExp.prototype.toString() - JavaScript
...
... ...
RegExp.prototype.unicode - JavaScript
pository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
... value of unicode is a Boolean and true if the "u" flag was used; otherwise false. The "u" flag enables various Unicode-related features. With the "u" flag, any Unicode code point escapes will be interpreted as such, for example. You cannot change this property directly. It is read-only. Examples Using the unicode property var regex = new RegExp('\u{61}', 'u'); console.log(regex.unicode); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.prototype.unicode' in that specification. ...
Planned changes to shared memory - JavaScript
used to get an instance. Unless the two headers mentioned above are set, the various postMessage() APIs will throw for SharedArrayBuffer objects. If they are set, postMessage() on Window objects and dedicated workers will function and allow for memory sharing. ...
... for memory sharing. To avoid having to check whether postMessage() throws, self.crossOriginIsolated is being standardized (a getter that returns a boolean; true if the headers are set), available in window and worker contexts. WebAssembly Shared Memory The WebAssembly Threads proposal allows WebAssembly.Memory objects to be created with a new shared constructor flag. When this flag is set to true, the constructed Memory object can be shared between workers via postMessage(), just like SharedArrayBuffer, and the backing buffer of the Memory object is a SharedArrayBuffer. Therefore, the requirements listed above for sharing a SharedArrayBuffer between workers also apply to sharing a WebAssembly.Memory. The WebAssembly Threads proposal also defines a new set of atomic instructions. Just as ...
String.prototype.indexOf() - JavaScript
// returns -1 'Blue Whale'.indexOf('') // returns 0 'Blue Whale'.indexOf('', 9) // returns 9 'Blue Whale'.indexOf('', 10) // returns 10 'Blue Whale'.indexOf('', 11) // returns 10 The indexOf() method is case sensitive. ...
... // returns 10 The indexOf() method is case sensitive. 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". const str = 'Brave new world' console.log('Index of first w from start is ' + str.indexOf('w')) // logs 8 console.log('Index of "new" from start is ' + str.indexOf('new')) // log...
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. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax str.startsWith(searchString[, position]) Parameters searchString The characters to be searched for at the start of this string. position Optional The position in this string at which to begin searching for searchString. Defaults to 0. Return value true if the given characters are found at the beginning of the string; otherwise, false. Description This method lets you determine whether or not a string begins wi...
...0 ? rawPos|0 : 0; return this.substring(pos, pos + search.length) === search; } }); } A more robust (fully ES2015 specification compliant), but less performant and compact, Polyfill is available on GitHub by Mathias Bynens. 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. ...
String - JavaScript
character access, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See Object.defineProperty() for more information.) Comparing strings In C, the strcmp() function is used for comparing strings. In JavaScript, you just use the less-than and greater-than operators: let a = 'a' let b = 'b' if (a < b) { // true console.log(a + ' is less than ' + b) } else if (a > b) { console.log(a + ' is greater than ' + b) } else { console.log(a + ' and ' + b + ' are equal.') } A similar result can be achieved using the localeCompare() method inherited by String instances. Note that a == b compares the strings in a and b for being equal in the usual case-sensitive way. If you wish to compare without regard to...
...characters, use a function similar to this: function isEqual(str1, str2) { return str1.toUpperCase() === str2.toUpperCase() } // isEqual Upper case is used instead of lower case in this function, due to problems with certain UTF-8 character conversions. String primitives and String objects Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of Boolean and Numbers.) String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (that is, called without using the new keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked...
Symbol.hasInstance - JavaScript
...
... ...
Symbol.unscopables - JavaScript
clone https://github.com/mdn/interactive-examples and send us a pull request. Description The @@unscopables symbol (Symbol.unscopables) can be defined on any object to exclude property names from being exposed as lexical variables in with with environment bindings. Note that if using Strict mode, with statements are not available and will likely also not need this symbol. Setting a property to true in an unscopables object will make it unscopable and therefore it won't appear in lexical scope variables. Setting a property to false will make it scopable and thus it will appear in lexical scope variables. Property attributes of Symbol.unscopables Writable no Enumerable no Configurable no Examples...
...into the with statement. var keys = []; with (Array.prototype) { keys.push('something'); } Object.keys(Array.prototype[Symbol.unscopables]); // ["copyWithin", "entries", "fill", "find", "findIndex", // "includes", "keys", "values"] Unscopables in objects You can also set unscopables for your own objects. var obj = { foo: 1, bar: 2 }; obj[Symbol.unscopables] = { foo: false, bar: true }; with (obj) { console.log(foo); // 1 console.log(bar); // ReferenceError: bar is not defined } Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.unscopables' in that specification. ...
TypeError() constructor - JavaScript
fileName[, lineNumber]]]) Parameters message Optional Optional. Human-readable description of the error fileName Optional Optional. The name of the file containing the code that caused the exception lineNumber Optional Optional. ...
... console.log(e.name) // "TypeError" console.log(e.fileName) // "Scratchpad/1" console.log(e.lineNumber) // 2 console.log(e.columnNumber) // 2 console.log(e.stack) // "@Scratchpad/2:2:3\n" } Creating a TypeError try { throw new TypeError('Hello', "someFile.js", 10) } catch (e) { console.log(e instanceof TypeError) // true console.log(e.message) // "Hello" console.log(e.name) // "TypeError" console.log(e.fileName) // "someFile.js" console.log(e.lineNumber) // 10 console.log(e.columnNumber) // 0 console.log(e.stack) // "@Scratchpad/2:2:9\n" } Specifications Specification ECMAScript (ECMA-262)The definitio...
TypeError - JavaScript
rror. Inherited from Error. TypeError.prototype.lineNumber Line number in file that raised this error. Inherited from Error. TypeError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. TypeError.prototype.stack Stack trace. Inherited from Error. ...
... console.log(e.name) // "TypeError" console.log(e.fileName) // "Scratchpad/1" console.log(e.lineNumber) // 2 console.log(e.columnNumber) // 2 console.log(e.stack) // "@Scratchpad/2:2:3\n" } Creating a TypeError try { throw new TypeError('Hello', "someFile.js", 10) } catch (e) { console.log(e instanceof TypeError) // true console.log(e.message) // "Hello" console.log(e.name) // "TypeError" console.log(e.fileName) // "someFile.js" console.log(e.lineNumber) // 10 console.log(e.columnNumber) // 0 console.log(e.stack) // "@Scratchpad/2:2:9\n" } Specifications Specification ECMAScript (ECMA-262)The definitio...
TypedArray.prototype.some() - JavaScript
y.some(callback[, thisArg]) Parameters callback Function to test for each element, taking three arguments: currentValue The current element being processed in the typed array. index The index of the current element being processed in the typed array. array The typed array some was called upon. thisArg Optional. Value to use as this when executing callback. Return value true if the callback function returns a truthy value for any array element; otherwise, false. Description The some method executes the callback function once for each element present in the typed array until it finds one where callback returns a true value. If such an element is found, some immediately returns true. Otherwise, some returns false. callback is invoked with three arguments: the value ...
...rototype methods at all, as you can't make them non-enumerable. Examples Testing size of all typed array elements The following example tests whether any element in the typed array is bigger than 10. function isBiggerThan10(element, index, array) { 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. ...
URIError() constructor - JavaScript
ber]]]) Parameters message Optional Optional. Human-readable description of the error. fileName Optional Optional. The name of the file containing the code that caused the exception. lineNumber Optional Optional. The line number of the code that caused the exception. ...
...uence" console.log(e.name) // "URIError" console.log(e.fileName) // "Scratchpad/1" console.log(e.lineNumber) // 2 console.log(e.columnNumber) // 2 console.log(e.stack) // "@Scratchpad/2:2:3\n" } Creating an URIError try { throw new URIError('Hello', 'someFile.js', 10) } catch (e) { console.log(e instanceof URIError) // true console.log(e.message) // "Hello" console.log(e.name) // "URIError" console.log(e.fileName) // "someFile.js" console.log(e.lineNumber) // 10 console.log(e.columnNumber) // 0 console.log(e.stack) // "@Scratchpad/2:2:9\n" } Specifications Specification ECMAScript (ECMA-262)The definition of 'N...
URIError - JavaScript
ited from Error. URIError.prototype.lineNumber Line number in file that raised this error. Inherited from Error. URIError.prototype.columnNumber Column number in line that raised this error. Inherited from Error. URIError.prototype.stack Stack trace. Inherited from Error. ...
...uence" console.log(e.name) // "URIError" console.log(e.fileName) // "Scratchpad/1" console.log(e.lineNumber) // 2 console.log(e.columnNumber) // 2 console.log(e.stack) // "@Scratchpad/2:2:3\n" } Creating an URIError try { throw new URIError('Hello', 'someFile.js', 10) } catch (e) { console.log(e instanceof URIError) // true console.log(e.message) // "Hello" console.log(e.name) // "URIError" console.log(e.fileName) // "someFile.js" console.log(e.lineNumber) // 10 console.log(e.columnNumber) // 0 console.log(e.stack) // "@Scratchpad/2:2:9\n" } Specifications Specification ECMAScript (ECMA-262)The definition of 'U...
WeakMap.prototype.clear() - JavaScript
...
... ...
WebAssembly.Memory() constructor - JavaScript
s allowed to grow to, in units of WebAssembly pages. When present, the maximum parameter acts as a hint to the engine to reserve memory up front. However, the engine may ignore or clamp this reservation request. Unshared WebAssembly memories don't need to set a maximum, but shared memories do. shared Optional A boolean value that defines whether the memory is a shared memory or not. If set to true, it is a shared memory. The default is false. Note: A WebAssembly page has a constant size of 65,536 bytes, i.e., 64KiB. Exceptions If memoryDescriptor is not of type object, a TypeError is thrown. If maximum is specified and is smaller than initial, a RangeError is thrown. Examples Creating a new Memory instance There are two ways to get a WebAssembly.Memory object. The first wa...
...alues. WebAssembly.instantiateStreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new Uint32Array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); Creating a shared memory By default, WebAssembly memories are unshared. You can create a shared memory by passing shared: true in the constructor's initialization object: let memory = new WebAssembly.Memory({initial:10, maximum:100, shared:true}); This memory's buffer property will return a SharedArrayBuffer. Specifications Specification WebAssembly JavaScript InterfaceThe definition of 'Memory' in that specification. Browser compatibility The compatibility table on this page is generat...
WebAssembly.validate() - JavaScript
Exceptions If bufferSource is not a typed array or ArrayBuffer, a TypeError is thrown. ...
... Exceptions If bufferSource is not a typed array or ArrayBuffer, a TypeError is thrown. ...
undefined - JavaScript
onsole.log(undefined, typeof undefined); })(); // logs "foo string" (function(undefined) { console.log(undefined, typeof undefined); })('foo'); Examples Strict equality and undefined You can use undefined and the strict equality and inequality operators to determine whether a variable has a value. In the following code, the variable x is not initialized, and the if statement evaluates to true. var x; if (x === undefined) { // these statements execute } else { // these statements do not execute } Note: The strict equality operator (as opposed to the standard equality operator) must be used here, because x == undefined also checks whether x is null, while strict equality doesn't. This is because null is not equivalent to undefined. See comparison operators for details. typeof...
...l is not equivalent to undefined. See comparison operators for details. typeof operator and undefined Alternatively, typeof can be used: var x; if (typeof x === 'undefined') { // these statements execute } One reason to use typeof is that it does not throw an error if the variable has not been declared. // x has not been declared before if (typeof x === 'undefined') { // evaluates to true without errors // these statements execute } if (x === undefined) { // throws a ReferenceError } However, there is another alternative. JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context. The global scope is bound to the global object, so checking the existence of a variable in the global ...
Lexical grammar - JavaScript
atic The following are only reserved when they are found in module code: await Future reserved keywords in older standards The following are reserved as future keywords by older ECMAScript specifications (ECMAScript 1 till 3). 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. Reserved word usage Reserved words actually only apply to Identifiers (vs. IdentifierNames) . As described in es5.github.com/#A.1, these are all IdentifierNames which do not exclude ReservedWords. a.import a['import'] a = { import: 'test' }. On the other hand the following is illegal because it's an Identifier, which is an IdentifierNam...
...IdentifierNames are used for MemberExpression, CallExpression and so on. function import() {} // Illegal. Identifiers with special meanings A few identifiers have a special meaning in some contexts without being keywords of any kind. They include: arguments get set Literals Null literal See also null for more information. null Boolean literal See also Boolean for more information. true false Numeric literals The Number and BigInt types use numeric literals. Decimal 1234567890 42 // Caution when using with a leading zero: 0888 // 888 parsed as decimal 0777 // parsed as octal, 511 in decimal Note that decimal literals can start with a zero (0) followed by another decimal digit, but If all digits after the leading 0 are smaller than 8, the number is interpreted as an octal ...
Unary plus (+) - JavaScript
ithub.com/mdn/interactive-examples and send us a pull request. Syntax Operator: +x Description Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal (0x-prefixed) formats are supported. Negative numbers are supported (though not for hex). Using the operator on BigInt values throws a TypeError. If it cannot parse a particular value, it will evaluate to NaN. Examples Usage with numbers const x = 1; const y = -1; console.log(+x); // 1 console.log(+y); // -1 Usage with non-numbers +...
..., false, and null. Integers in both decimal and hexadecimal (0x-prefixed) formats are supported. Negative numbers are supported (though not for hex). Using the operator on BigInt values throws a TypeError. If it cannot parse a particular value, it will evaluate to NaN. Examples Usage with numbers const x = 1; const y = -1; console.log(+x); // 1 console.log(+y); // -1 Usage with non-numbers +true // 1 +false // 0 +null // 0 +function(val){ return val } // NaN +1n // throws TypeError: Cannot convert BigInt value to number Specifications Specification ECMAScript (ECMA-262)The definition of 'Unary plus operator' in that specification. ...
typeof - JavaScript
(logical NOT) operator are equivalent to Boolean() // Symbols typeof Symbol() === 'symbol' typeof Symbol('foo') === 'symbol' typeof Symbol.iterator === 'symbol' // Undefined typeof undefined === 'unde...
... 'undefined'; // Objects typeof {a: 1} === 'object'; // use Array.isArray or Object.prototype.toString.call // to differentiate regular objects from arrays typeof [1, 2, 4] === 'object'; typeof new Date() === 'object'; typeof /regex/ === 'object'; // See Regular expressions section for historical results // The following are confusing, dangerous, and wasteful. Avoid them. ...
for await...of - JavaScript
ties are to be iterated over. Examples Iterating over async iterables You can also iterate over an object that explicitly implements async iterable protocol: const asyncIterable = { [Symbol.asyncIterator]() { return { i: 0, next() { if (this.i < 3) { return Promise.resolve({ value: this.i++, done: false }); } return Promise.resolve({ done: true }); } }; } }; (async function() { for await (let num of asyncIterable) { console.log(num); } })(); // 0 // 1 // 2 Iterating over async generators Since the return values of async generators conform to the async iterable protocol, they can be looped using for await...of. async function* asyncGenerator() { let i = 0; while (i < 3) { yield i++; } } (async func...
...ole.log(num); } })(); // 0 // 1 // 2 For a more concrete example of iterating over an async generator using for await...of, consider iterating over data from an API. This example first creates an async iterable for a stream of data, then uses it to find the size of the response from the API. async function* streamAsyncIterable(stream) { const reader = stream.getReader(); try { while (true) { const { done, value } = await reader.read(); if (done) { return; } yield value; } } finally { reader.releaseLock(); } } // Fetches data from url and calculates response size using the async generator. async function getResponseSize(url) { const response = await fetch(url); // Will hold the size of the response, in bytes. let responseSize = 0; ...
for...of - JavaScript
s closed. function* foo(){ yield 1; yield 2; yield 3; }; for (const o of foo()) { console.log(o); break; // closes iterator, execution continues outside of the loop } console.log('done'); Iterating over generators You can also iterate over generators, i.e. functions generating an iterable object: function* fibonacci() { // a generator function let [prev, curr] = [0, 1]; while (true) { [prev, curr] = [curr, prev + curr]; yield curr; } } for (const n of fibonacci()) { console.log(n); // truncate the sequence at 1000 if (n >= 1000) { break; } } Do not reuse generators Generators should not be re-used, even if the for...of loop is terminated early, for example via the break keyword. Upon exiting a loop, the generator is closed and trying to iterate ove...
... for (const o of gen) { console.log(o); // Never called. } Iterating over other iterable objects You can also iterate over an object that explicitly implements the iterable protocol: const iterable = { [Symbol.iterator]() { 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. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable properties of an object, in an arbitrary order. The for...of statement iterates...
Statements and declarations - JavaScript
control to the statement following the terminated statement. continue Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. Empty An empty statement is used to provide no statement, although the JavaScript syntax would expect one. if...else Executes a statement if a specified condition is true. If the condition is false, another statement can be executed. switch Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case. throw Throws a user-defined exception. try...catch Marks a block of statements to try, and specifies a response, should an exception be thrown. Declarations var Declares a variable, optionall...
...stom iteration hook with statements to be executed for the value of each distinct property. for await...of Iterates over async iterable objects, array-like objects, iterators and generators, invoking a custom iteration hook with statements to be executed for the value of each distinct property. while Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement. Others debugger Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect. export Used to export functions to make them available for imports in external modules, and other scripts. import Used to import functions exported from an external module, another script. im...
Template literals (Template strings) - JavaScript
st concatenates the parts into a single string. If there is an expression preceding the template literal (tag here), this is called a tagged template. In that case, the tag expression (usually a function) gets called with the template literal, which you can then manipulate before outputting. To escape a backtick in a template literal, put a backslash (\) before the backtick. `\`` === '`' // --> true Multi-line strings Any newline characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings: console.log('string text line 1\n' + 'string text line 2'); // "string text line 1 // string text line 2" Using template literals, you can do the same like this: console.log(`string text line 1...
... 10; console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`); // "Fifteen is 15 and // not 20." Nesting templates In certain cases, nesting a template is the easiest (and perhaps more readable) way to have configurable strings. Within a backticked template, it is simple to allow inner backticks simply by using them inside a placeholder ${ } within the template. For instance, if condition a is true, then return this templated literal. In ES5: let classes = 'header'; classes += (isLargeScreen() ? '' : item.isCollapsed ? ' icon-expander' : ' icon-collapser'); In ES2015 with template literals and without nesting: const classes = `header ${ isLargeScreen() ? '' : (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`; In ES2015 with nested template literals: const classes = `...
<mfrac> - MathML
Web › MathML › Element › mfrac
Otherwise, if set to false (which is the default value), numerator and denominator are on top of each other. This attribute is deprecated and will be removed in the future. Use U+2044 (fraction slash) instead. class, id, style Provided for use with stylesheets. ...
...d also the fraction line color. You can use #rgb, #rrggbb and HTML color names. numalign The alignment of the numerator over the fraction. Possible values are: left, center (default), and right. This attribute is deprecated and will be removed in the future. Use CSS text-align instead. Examples Sample rendering: Your browser rendering: a b c d <math> <mfrac bevelled="true"> <mfrac> <mi> a </mi> <mi> b </mi> </mfrac> <mfrac> <mi> c </mi> <mi> d </mi> </mfrac> </mfrac> </math> Specifications Specification Status Comment MathML 3.0The definition of 'mfrac' in that specification. Recommendation Current specification MathML 2.0The definition of 'mfrac' in that specificat...
<mover> - MathML
Web › MathML › Element › mover
If false (default value) the over-script is a limit over the base expression. align The alignment of the over-script. Possible values are: left, center, and right. This attribute is deprecated and will be removed in the future. Use CSS text-align instead. class, id, style Provided for use with stylesheets. href Used to set a hyperlink to a specified URI. ...
...ext-align instead. class, id, style Provided for use with stylesheets. href Used to set a hyperlink to a specified URI. mathbackground The background color. You can use #rgb, #rrggbb and HTML color names. mathcolor The text color. You can use #rgb, #rrggbb and HTML color names. Examples Sample rendering: Rendering in your browser: x + y + z ? <math> <mover accent="true"> <mrow> <mi> x </mi> <mo> + </mo> <mi> y </mi> <mo> + </mo> <mi> z </mi> </mrow> <mo> &#x23DE; <!--TOP CURLY BRACKET--> </mo> </mover> </math> Specifications Specification Status Comment MathML 3.0The definition of 'mover' in that specification. Recommendation Current specification MathML 2.0The definition of 'mover' in tha...
<mtable> - MathML
Web › MathML › Element › mtable
The MathML <mtable> element allows you to create tables or matrices. Inside a <mtable> only <mtr> and <mtd> elements may appear. These elements are similar to <table> , <tr> and <td> elements of HTML. Note: The <mtable> element resets the displaystyle attribute to false. If you want to use this element as an inline-block, you might want to set <mtable displaystyle="true">...</mtable>. Attributes align Specifies the vertical alignment of the table with respect to its environment. Possible values are: axis (default): The vertical center of the table aligns on the environment's axis (typically the minus sign). baseline: The vertical center of the table aligns on the environment's baseline. bottom: The bottom of the table aligns on the environments baseline. center: See baselin...
...hed. columnspacing Specifies the space between table columns. Unimplemented columnwidth Specifies the width of table columns. 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. The main effect is that larger versions of operators are displayed, when displaystyle is set to true. Unimplemented equalcolumns A Boolean value indicating whether to force all columns to have the same total height. false is default. Unimplemented equalrows A Boolean value indicating whether to force all rows to have the same total height. false is default. frame Specifies borders of the entire table. Possible values are: none (default), solid and dashed. framespacing Specifies additiona...
<munder> - MathML
Web › MathML › Element › munder
If false (default value), the element is a limit under the base expression. align The alignment of the underscript. Possible values are: left, center, and right. This attribute is deprecated and will be removed in the future. Use CSS text-align instead. class, id, style Provided for use with stylesheets. ...
...ign instead. class, id, style Provided for use with stylesheets. href Used to set a hyperlink to a specified URI. mathbackground The background color. You can use #rgb, #rrggbb and HTML color names. mathcolor The text color. You can use #rgb, #rrggbb and HTML color names. Examples Sample rendering: Rendering in your browser: x + y + z ? <math> <munder accentunder="true"> <mrow> <mi> x </mi> <mo> + </mo> <mi> y </mi> <mo> + </mo> <mi> z </mi> </mrow> <mo> &#x23DF; <!--BOTTOM CURLY BRACKET--> </mo> </munder> </math> Specifications Specification Status Comment MathML 3.0The definition of 'munder' in that specification. Recommendation Current specification MathML 2.0The definition of 'munder' ...
Web audio codec guide - Web media technologies
's still an MPEG format file. Factors affecting the encoded audio There are two general categories of factors that affect the encoded audio which is output by an audio codec's encoder: details about the source audio's format and contents, and the codec and its configuration during the encoding process. For each factor that affects the encoded audio, there is a simple rule that is nearly always true: because the fidelity of digital audio is determined by the granularity and precision of the samples taken to convert it into a data stream, the more data used to represent the digital version of the audio, the more closely the sampled sound will match the source material. The effect of source audio format on encoded audio output Because encoded audio inherently uses fewer bits to represent eac...
...it usually is, as long as the audio files are small), the three strongest candidates from a codec perspective are FLAC, Apple Lossless (ALAC), and MPEG-4 ALS. Which we choose will depend on browser support and which media container formats support them. For the purposes of this example, we'll assume that all browsers have the same codec and container support as Firefox (although this is far from true). Consider the breadth of actual support for the codecs when making your decisions. Firefox supports FLAC in FLAC's native containers as well as in Ogg and MPEG-4 (MP4) files. Firefox only supports Apple Lossless through its platform-specific QuickTime support. Firefox doesn't support MP4 ALS. In this case, it appears that FLAC is most likely the best codec to go with; ALAC has little to n...
Web video codec guide - Web media technologies
The documentation included with your encoding sof...
...g VP8). Of note, however, is that Safari supports neither WebM nor VP9, so if you choose to use VP9, be sure to offer a fallback format such as AVC or HEVC for iPhone, iPad, and Mac users. Aside from the lack of Safari support, VP9 is a good choice if you are able to use a WebM container and are able to provide a fallback video in a format such as AVC or HEVC for Safari users. This is especially true if you wish to use an open codec rather than a proprietary one. If you can't provide a fallback and aren't willing to sacrifice Safari compatibility, VP9 in WebM is a good option. Otherwise, you should probably consider a different codec. Supported bit rates Arbitrary; no maximum unless level-based limitations are enforced Supported frame rates Arbitrary Compress...
CSS and JavaScript animation performance - Web Performance
what animation method seems better overall. Enabling FPS tools Before going through the example, please enable FPS tools first to see the current frame rate: In the URL bar, enter about:config; click the I'll be careful, I promise! button to enter the config screen. In the search bar, search for the layers.acceleration.draw-fps preference. Double-click the entry to set the value to true. Now you will be able to see three little purple boxes at the upper left corner of the Firefox window. The first box represents FPS. Running the performance test Initially in the test seen below, a total of 1000 <div> elements are transformed by CSS animation. The animation can be switched to requestAnimationFrame() by clicking the toggle button. Try running them both now, comparing th...
...he CSS transform. If an element is promoted as a layer, animating transform properties can be done in the GPU, meaning better performance/efficiency, especially on mobile. Find out more details in OffMainThreadCompositing. To enable the OMTA (Off Main Thread Animation) in Firefox, you can go to about:config and search for the layers.offmainthreadcomposition.async-animations. Toggle its value to true. After enabling OMTA, try running the above test again. You should see that the FPS of the CSS animations will now be significantly higher. Note: In Nightly/Developer Edition, you should see that OMTA is enabled by default, so you might have to do the tests the other way around (test with it enabled first, then disable to test without OMTA.) Summary Browsers are able to optimize rendering...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
and converts the response to text; then it needs to be converted to a Uint8Array (to support Chrome). To learn more about VAPID keys you can read the Sending VAPID identified WebPush Notifications via Mozilla's Push Service blog post. The app can now use the PushManager to subscribe the new user. ...
...ushManager to subscribe the new user. There are two options passed to the PushManager.subscribe() method -- the first is userVisibleOnly: true, which means all the notifications sent to the user will be visible to them, and the second one is the applicationServerKey, which contains our successfully acquired and converted VAPID key. return registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: convertedVapidKey }); Now let's move to the subscription part -- the app first sends the subscription details as JSON to the server using Fetch. fetch('./register', { method: 'post', headers: { 'Content-type': 'application/json' }, body: JSON.stringify({ subscription: subscription }), }); Then the GlobalEventHandlers.onclick functi...
The building blocks of responsive design - Progressive web apps (PWAs)
80px)"> This says that the whole stylesheet will not be linked to the HTML unless the viewport width is 480px or less. Moving on to the JavaScript, <script> elements don't accept media attributes, so I had to do this a different way. Fortunately there is a JavaScript construct called window.matchMedia(), which can conditionally run JavaScript constructs depending on whether a media query returns true or not. We opened up the brick.js file and wrapped the whole lot in the following: if (window.matchMedia("(max-width: 480px)").matches) { // The whole of brick.js goes here! } This causes nothing inside the brick.js file to be run unless the viewport width is 480px or less. Problem solved. Really wide screens One thing you might notice is that when the viewport gets very wide (such as on a ...
...t One last problem to mention for our example app is concerned with mobile browsers and media queries. If we viewed my example in a mobile browser in its current state, we wouldn't see our nice mobile layout. Instead, we'd see the below image. I'm sure you'll agree that this really isn't what we wanted -- why is this happening? In short, mobile browsers lie. They don't render web pages at their true viewport width. Instead, they render pages at a higher assumed viewport width (something approaching a laptop screen), and then shrink the result down to fit inside the mobile screen. This is a sensible defensive mechanism -- most old school sites that don't have media queries would look terrible when rendered at say, 320px or 480px wide. But this doesn't help us responsible web developers, who h...
requiredExtensions - SVG: Scalable Vector Graphics
None Animatable No <list-of-extensions> The value is a list of references (IRI references in SVG 1, URL References in SVG 2) which identify the required extensions, with the individual values separated by white space. Determines whether all of the named extensions are supported by the user agent. If all of the given extensions are supported, then the attribute evaluates to true; otherwise, the current element and its children are skipped and thus will not be rendered. Note: If a given extension reference contains white space within itself, that white space must be escaped. requiredExtensions is often used in conjunction with the <switch> element. If the attribute is used in other situations, then it represents a simple switch on the given element whether to render th...
...the given element whether to render the element or not. Note: If several extension reference objects are enclosed in a <switch> and none of them matches, this may lead to situations where no content is displayed. It is thus recommended to include a "catch-all" choice at the end of such a <switch> which is acceptable in all cases. If the attribute is not present, then it implicitly evaluates to "true". If a null string or empty string value is given, the attribute evaluates to "false". The IRI names for the extension should include versioning information, such as "http://example.org/SVGExtensionXYZ/1.0", so that script writers can distinguish between different versions of a given extension. Specifications Specification Status Comment Scalable Vector Graphics (SV...
requiredFeatures - SVG: Scalable Vector Graphics
The requiredFeatures attribute takes a list of feature strings, with the individual strings separated by white space. 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. This provides a way to design SVG that gracefully falls back when features aren't available. If the attribute is not present, then its implicit evaluated value is true. If a null string or empty string value is given to attribute requiredFeatures, the attribute is evaluate to false. requiredFeatures is often used in conjunction with the <switch> element. If requiredFeatures i...
...Determines whether all of the named features are supported by the browser. See Feature strings below for a list of allowed values. Feature strings The following are the feature strings for the requiredFeatures attribute. T...
systemLanguage - SVG: Scalable Vector Graphics
hen it represents a simple switch on the given element whether to render the element or not. Note: If several alternative language objects are enclosed in a <switch> and none of them matches, this may lead to situations where no content is displayed. It is thus recommended to include a "catch-all" choice at the end of such a <switch> which is acceptable in all cases. The attribute evaluates to "true" if one of the language tags indicated by user preferences is a case-insensitive match or prefix (followed by a "-") of one of the language tags given in the value of this parameter. Otherwise it evaluates to "false". Note: The prefix matching rule does not imply that if a user understands a language with a certain tag, that the user will also understand all languages with the tag as prefix. If...
... case-insensitive match or prefix (followed by a "-") of one of the language tags given in the value of this parameter. Otherwise it evaluates to "false". Note: The prefix matching rule does not imply that if a user understands a language with a certain tag, that the user will also understand all languages with the tag as prefix. If the attribute is not present, then it implicitly evaluates to "true". If a null string or empty string value is given, the attribute evaluates to "false". The prefix rule simply allows the use of prefix tags if this is the case. Multiple languages may be listed for content that is intended for multiple audiences. For example, content that is presented simultaneously in the original Maori and English versions, would call for: <text systemLanguage="mi, en"><!-- ...
SVG documentation index - SVG: Scalable Vector Graphics
Web › SVG › Index
e repeatDur attribute specifies the total duration for repeating an animation. 177 requiredFeatures SVG, SVG Attribute The requiredFeatures attribute takes a list of feature strings, with the individual strings separated by white space. 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. This provides a way to design SVG that gracefully falls back when features aren't available. 178 restart SVG, SVG Attribute The restart attribute specifies whether or not an animation can restart. 179 result ...
...ost element of SVG documents, but it can also be used to embed an SVG fragment inside an SVG or HTML document. 369 <switch> Element, NeedsExample, SVG, SVG Container The <switch> SVG element evaluates any requiredFeatures, requiredExtensions and systemLanguage attributes on its direct child elements in order, and then renders the first child where these attributes evaluate to true. 370 <symbol> SVG, SVG Container The <symbol> element is used to define graphical template objects which can be instantiated by a <use> element. 371 <text> Element, Reference, SVG, SVG Text Content The SVG <text> element draws a graphics element consisting of text. It's possible to apply a gradient, pattern, clipping path, mask, or filter to <text>, like ...
element-available - XPath
If the expanded-name has a namespace URI equal to the XSLT namespace URI, then it refers to an element defined by XSLT. ...
...If the expanded-name has a namespace URI equal to the XSLT namespace URI, then it refers to an element defined by XSLT. Otherwise, it refers to an extension element. ...
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
o summary! 5 The XSLT/JavaScript Interface in Gecko XSLT No summary! 6 Advanced Example XSLT This advanced example sorts several divs based on their content. The example allows sorting the content multiple times, alternating between ascending and descending order. The JavaScript loads the .xsl file only on the first sort and sets the xslloaded variable to true once it has finished loading the file. Using the XSLTProcessor.getParameter() method, the code can figure whether to sort in ascending or descending order. It defaults to ascending if the parameter is empty (the first time the sorting happens, as there is no value for it in the XSLT file). The sorting value is set using XSLTProcessor.setParameter(). 7 Basic Example XSLT The b...
...ame way. It is often used to iterate through a set of nodes or to change the current node. If one or more <xsl:sort> elements appear as the children of this element, sorting occurs before processing. Otherwise, nodes are processed in document order. 33 <xsl:if> Element, Reference, XSLT, if The <xsl:if> element contains a test attribute and a template. If the test evaluates to true, the template is processed. In this it is similar to an if statement in other languages. To achieve the functionality of an if-then-else statement, however, use the <xsl:choose> element with one <xsl:when> and one <xsl:otherwise> children. 34 <xsl:import> Element, Reference, XSLT, import The <xsl:import> element is a top-level element that serves to import the contents of one...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
Using the XSLTProcessor.getParameter() method, the code can figure whether to sort in ascending or descending order. ...
...div> </div> // JavaScript var xslRef; var xslloaded = false; var xsltProcessor = new XSLTProcessor(); var myDOM; var xmlRef = document.implementation.createDocument("", "", null); function sort() { if (!xslloaded){ p = new XMLHttpRequest(); p.open("GET", "example2.xsl", false); p.send(null); xslRef = p.responseXML; xsltProcessor.importStylesheet(xslRef); xslloaded = true; } // create a new XML document in memory xmlRef = document.implementation.createDocument("", "", null); // we want to move a part of the DOM from an HTML document to an XML document. // importNode is used to clone the nodes we want to process via XSLT - true makes it do a deep clone var myNode = document.getElementById("example"); var clonedNode = xmlRef.importNode(myNode, true);...
Using the WebAssembly JavaScript API - WebAssembly
l variable instances, accessible from both JavaScript and importable/exportable across one or more WebAssembly.Module instances. This is very useful, as it allows dynamic linking of multiple modules. To create a WebAssembly global instance from inside your JavaScript, you use the WebAssembly.Global() constructor, which looks like this: const global = new WebAssembly.Global({value:'i32', mutable:true}, 0); You can see that this takes two parameters: An object that contains two properties describing the global variable: value: its data type, which can be any data type accepted within WebAssembly modules -- i32, i64, f32, or f64. mutable: a boolean defining whether the value is mutable or not. A value containing the variable's actual value. This can be any value, as long as i...
... function assertEq(msg, got, expected) { output.innerHTML += `Testing ${msg}: `; if (got !== expected) output.innerHTML += `FAIL!<br>Got: ${got}<br>Expected: ${expected}<br>`; else output.innerHTML += `SUCCESS! ...
Cross-domain Content Scripts - Archive of obsolete content
-> <html> <head></head> <body> <div id="forecast_summary"></div> </body> </html> The "panel-script.js" uses XMLHttpRequest to fetch the latest forecast: // panel-script.js var url = "http://datapoint.metoffice.gov.uk/public/data/txt/wxfcs/regionalforecast/json/500?key=YOUR-API-KEY"; self.port.on("show", function () { var request = new XMLHttpRequest(); request.open("GET", url, true); request.onload = function () { var jsonResponse = JSON.parse(request.responseText); var summary = getSummary(jsonResponse); var element = document.getElementById("forecast_summary"); element.textContent = summary; }; request.send(); }); function getSummary(forecast) { return forecast.RegionalFcst.FcstPeriods.Period[0].Paragraph[0].$; } Finally, we need to add the "cro...
Reddit Example - Archive of obsolete content
Finally, it registers a listener to the user-...
Modules - Archive of obsolete content
on like this is that malicious scripts can use it to get the loading script to execute arbitrary code, by overriding one of the methods on the built-in constructors. If the loading script has chrome privileges, then so will any methods called by the loading script, even if that method was installed by a malicious script. To avoid problems like this, the object passed to loadSubScript should be a true global object, having its own instances of the built-in constructors. This is exactly what sandboxes are for. A sandbox is a global object that lives in a separate compartment. Compartments are a fairly recent addition to SpiderMonkey, and can be seen as a separate memory space. Objects living in one compartment cannot be accessed directly from another compartment: they need to be accessed throug...
page-mod - Archive of obsolete content
option to define some read-only values for your content scripts. The option consists of an object literal listing name:value pairs for the values you want to provide to the content script. ...
request - Archive of obsolete content
display correctly. To force the response to be interpreted as Latin-1, use overrideMimeType: var Request = require("sdk/request").Request; var quijote = Request({ url: "http://www.latin1files.org/quijote.txt", overrideMimeType: "text/plain; charset=latin1", onComplete: function (response) { console.log(response.text); } }); quijote.get(); anonymous boolean If true, the request will be sent without cookies or authentication headers. This option sets the mozAnon property in the underlying XMLHttpRequest object. Defaults to false. Request The Request object is used to make GET, HEAD, POST, PUT, or DELETE network requests. It is constructed with a URL to which the request is sent. Optionally the user may specify a collection of headers and content to s...
simple-storage - Archive of obsolete content
t that it's only available for add-ons. Usage The simple storage module exports an object called storage that is persistent and scoped to your add-on. It's a normal JavaScript object, and you can treat it as you would any other. To store a value, just assign it to a property on storage: var ss = require("sdk/simple-storage"); ss.storage.myArray = [1, 1, 2, 3, 5, 8, 13]; ss.storage.myBoolean = true; ss.storage.myNull = null; ss.storage.myNumber = 3.1337; ss.storage.myObject = { a: "foo", b: { c: true }, d: null }; ss.storage.myString = "O frabjous day!"; You can store array, boolean, number, object, null, and string values. If you'd like to store other types of values, you'll first have to convert them to strings or another one of these types. Be careful to set properties on the storage o...
widget - Archive of obsolete content
tach event. tooltip string Optional text to show when the user's mouse hovers over the widget. If not given, the label is used. allow object An optional object describing permissions for the content. It should contain a single key named script whose value is a boolean that indicates whether or not to execute script in the content. script defaults to true. contentScriptFile string,array A local file URL or an array of local file URLs of content scripts to load. Content scripts specified by this property are loaded before those specified by the contentScript property. contentScript string,array A string or an array of strings containing the texts of content scripts to load. Content scripts specified b...
/loader - Archive of obsolete content
ch identifies the sandbox in about:memory. Will throw exception if omitted. principal: String URI or nsIPrincipal for the sandbox. If omitted defaults to system principal. prototype: Object that the returned sandbox will inherit from. Defaults to {}. wantXrays: A Boolean value indicating whether code outside the sandbox wants X-ray vision with respect to objects inside the sandbox. Defaults to true. 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. If options.source is provided then its value is evaluated,...
core/promise - Archive of obsolete content
tch. Add-on SDK's promise module provides an API for doing that. defer Module exports defer function, which is where all promises ultimately come from. Lets see the implementation of readAsync that we used in several of the examples above: const { defer } = require('sdk/core/promise'); function readAsync(url) { var deferred = defer(); let xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.onload = function() { deferred.resolve(xhr.responseText); }; xhr.onerror = function(event) { deferred.reject(event); }; xhr.send(); return deferred.promise; } So defer returns an object that contains a promise and two resolve, reject functions that can be used to resolve / reject that promise. Note: A promise can be rejected or resolved only once. All subsequent attemp...
io/byte-streams - Archive of obsolete content
e stream is already closed, an exception is thrown. read(numBytes) Reads a string from the stream. If the stream is closed, an exception is thrown. Parameters numBytes : number The number of bytes to read. If not given, the remainder of the entire stream is read. Returns string : A string containing the bytes read. If the stream is at the end, returns the empty string. Properties closed True if the stream is closed. ByteWriter Methods close() Closes both the stream and its backing stream. If the stream is already closed, an exception is thrown. write(str) Writes a string to the stream. If the stream is closed, an exception is thrown. Parameters str : string The string to write. Properties closed True if the stream is closed. ...
net/url - Archive of obsolete content
Experimental Enables you to read content from a URI. Globals Functions readURI(uri, options) Reads a URI and returns a promise. Parameters uri : string The URL, as a string, to load. options : object Optional options: Name Type sync boolean If this option is set to true, the promise returned will be resolved synchronously. Defaults to false if not provided. charset string The character set to use when read the content of the uri given. Defaults to UTF-8 if not provided. Returns promise : The promise that will be resolved with the content of the URL given. ...
platform/xpcom - Archive of obsolete content
ice supplied. If the factory or service is not registered, this function does nothing. By default, factories and services are unregistered automatically when the add-on that registered them is unloaded. Parameters factory : object The factory or service to unregister. isRegistered(factory) Find out whether a factory or service is registered. Parameters factory : object Returns boolean : True if the factory or service is registered, false otherwise. autoRegister(path) Register a component (.manifest) file or all component files in a directory. See nsIComponentRegistrar.autoRegister() for details. Parameters path : string Path to a component file to be registered or a directory containing component files to be registered. factoryByID(id) Given a class ID, this function returns t...
preferences/service - Archive of obsolete content
a properties file Example: require("sdk/preferences/service").set("general.useragent.locale", "chrome://global/locale/intl.properties"); Example: Setting Global Preferences var { get, set } = require("sdk/preferences/service"); var { when: unload } = require("sdk/system/unload"); var oldValue = get("browser.urlbar.autoFill"); set("browser.urlbar.autoFill", true); // By AMO policy global preferences must be changed back to their original value unload(function() { set("browser.urlbar.autoFill", oldValue); }); ...
remote/parent - Archive of obsolete content
module); frames.port.emit("changeLocation", "foo"); Tab information This shows sending a message when a tab loads; this is similar to how the sdk/tabs module currently works. // remote.js const { frames } = require("sdk/remote/child"); frames.addEventListener("pageshow", function() { // `this` is bound to the frame the event came from let frame = this; frame.port.emit("pageshow"); }, true); // main.js const { frames, remoteRequire } = require("sdk/remote/parent"); remoteRequire("./remote.js", module); // The first argument is the frame the message came from frames.port.on("pageshow", (frame) => { console.log(frame.frameElement.currentURI.host + ": pageshow"); }); Globals Functions remoteRequire(id, module = null) Loads a module in any existing and future child processes. T...
stylesheet/utils - Archive of obsolete content
...
system/environment - Archive of obsolete content
Access, set and clear environment variables. ...
system/runtime - Archive of obsolete content
OS A string identifying the current operating system. For example, . "WINNT", "Darwin", or "Linux". See OS_TARGET for a more complete list of possible values. processType The type of the caller's process, which will be one of these constants: Constant Value Description PROCESS_TYPE_DEFAULT 0 The default (chrome) process. ...
test/assert - Archive of obsolete content
it test framework, and not by unit tests themselves. Parameters logger : object Object used to log the results of assertions. Assert An object used to make assertions about a program's state in order to implement unit tests. The Assert object's interface is defined by the CommonJS Unit Testing specification, version 1.1. Methods ok(guard, message) Tests whether an expression evaluates to true. assert.ok(a == 1, "test that a is equal to one"); This is equivalent to: assert.equal(a == 1, true, "test that a is equal to one"); Parameters guard : expression The expression to evaluate. message : string Optional message to log, providing extra information about the test. equal(actual, expected, message) Tests shallow, coercive equality with ==: assert.equal(1, 1, "test that one is...
util/list - Archive of obsolete content
cept for the length property. Examples: var { List } = require("sdk/util/list"); var MyList = List.compose({ add: function add(item1, item2, /*item3...*/) { Array.slice(arguments).forEach(this._add.bind(this)); }, remove: function remove(item1, item2, /*item3...*/) { Array.slice(arguments).forEach(this._remove.bind(this)); } }); MyList('foo', 'bar', 'baz').length == 3; // true new MyList('new', 'keyword').length == 2; // true MyList.apply(null, [1, 2, 3]).length == 3; // true let list = MyList(); list.length == 0; // true list.add(1, 2, 3) == 3; // true Properties length Number of elements in this list. ...
Implementing the widget - Archive of obsolete content
data. But it seems tidier this way. 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. The widget's icons You can copy the widget's icons from here: Or, if you're feeling creative, you can make your own icons. Either way, save them in your data/widget directory. main.js Now in the lib directory open main.js and add the following code: var widget...
Getting started (cfx) - Archive of obsolete content
lternative development model is to use the Extension Auto-Installer add-on: this listens for new XPI files on a specified port and installs them automatically. That way you can test new changes without needing to restart the browser: make a change to your add-on run cfx xpi post the add-on to the port specified You could even automate this workflow with a simple script. For example: while true ; do cfx xpi ; wget --post-file=codesy.xpi http://localhost:8888/ ; sleep 5 ; done Note that the logging level defined for the console is different when you use this method, compared to the logging level used when an add-on is run using cfx run. This means that if you want to see output from console.log() messages, you'll have to tweak a setting. See the documentation on logging levels for the ...
Bootstrapped extensions - Archive of obsolete content
cument.getElementById(), then manipulate them to inject your UI. For example, you can get access to the menu bar in Firefox with document.getElementById("main-menubar"). Be sure that at shutdown time, you remove any user interface you've added. Creating a bootstrapped extension To mark an extension as bootstrappable, you need to add the following element to its install manifest: <em:bootstrap>true</em:bootstrap> Then you need to add a bootstrap.js file that contains the required functions; this should be alongside the install.rdf file in the extension's package. Backward compatibility Because older versions of Firefox don't know about the bootstrap property or bootstrap.js file, it's not overly difficult to create an XPI that will work on both as a bootstrappable extension and as a trad...
Autocomplete - Archive of obsolete content
Turning autocomplete on for a XUL widget This article is about XUL widgets and not about HTML form inputs. First, declare a panel with the "autocomplete" type, like so: <panel id="popup_autocomplete" type="autocomplete" noautofocus="true" /> Now set the autocompletepopup attribute of your <browser> element to the id of the panel you just declared: <browser id="my_browser" ... autocompletepopup="popup_autocomplete" /> Finally, make sure that the value of the browser.formfill.enable pref is set to true. See also Textbox (Toolkit autocomplete) How to implement custom autocomplete search component ...
Canvas code snippets - Archive of obsolete content
dow.innerWidth - 25; var iframe; iframe = document.createElement('iframe'); iframe.id = 'test-iframe'; iframe.height = '10px'; iframe.width = windowWidth + 'px'; iframe.style.visibility = 'hidden'; iframe.src = this.url; // Here is where the magic happens... ...
Downloading Files - Archive of obsolete content
acy = PrivateBrowsingUtils.privacyContextFromWindow(urlSourceWindow); var hardCodedUserName = "ericjung"; var hardCodedPassword = "foobar"; persist.progressListener = { QueryInterface: XPCOMUtils.generateQI(["nsIAuthPrompt"]), // implements nsIAuthPrompt prompt: function(dialogTitle, text, passwordRealm, savePassword, defaultText, result) { result.value = hardCodedPassword; return true; }, promptPassword: function(dialogTitle, text, passwordRealm, savePassword, pwd) { pwd.value = hardCodedPassword; return true; }, promptUsernameAndPassword: function(dialogTitle, text, passwordRealm, savePassword, user, pwd) { user.value = hardCodedUserName; pwd.value = hardCodedPassword; return true; } }; persist.saveURI(urlToSave, null, null, null, "", nsFileInst...
File I/O - Archive of obsolete content
r drivesEnum = root.directoryEntries, drives = []; while (drivesEnum.hasMoreElements()) { drives.push(drivesEnum.getNext(). QueryInterface(Components.interfaces.nsILocalFile).path); } Creating Folders FileUtils.getDir() can create a folder automatically if it doesn't exist yet: Components.utils.import("resource://gre/modules/FileUtils.jsm"); var dir = FileUtils.getDir("ProfD", ["DIR"], true); The above example creates a folder called "DIR" in the user's profile folder. You can also create a directory explicitly; for more information refer to nsIFile.create(). Creating temporary files To create a temporary file, use nsIFile.createUnique(): Components.utils.import("resource://gre/modules/FileUtils.jsm"); var file = FileUtils.getFile("TmpD", ["suggestedName.tmp"]); file.createUni...
JavaScript Debugger Service - Archive of obsolete content
k; var messageType; if (flags & jsdIErrorHook.REPORT_ERROR) messageType = "Error"; if (flags & jsdIErrorHook.REPORT_WARNING) messageType = "Warning"; if (flags & jsdIErrorHook.REPORT_EXCEPTION) messageType = "Uncaught-Exception"; if (flags & jsdIErrorHook.REPORT_STRICT) messageType += "-Strict"; dump(messageType + "\n"); return false; // trigger debugHook // return true; if you do not wish to trigger debugHook } }; // note that debugHook does not _always_ trigger when jsd.errorHook[onError] returns false // it is not well-known why debugHook sometimes fails to trigger jsd.debugHook = { onExecute: function(frame, type, rv) { stackTrace = ""; for (var f = frame; f; f = f.callingFrame) { stackTrace += f.script.fileName + "@" + f.line + "@" + f.functionN...
Post data to window - Archive of obsolete content
IStringInputStream); if ("data" in stringStream) // Gecko 1.9 or newer stringStream.data = dataString; else // 1.8 or older stringStream.setData(dataString, dataString.length); var postData = Cc["@mozilla.org/network/mime-input-stream;1"]. createInstance(Ci.nsIMIMEInputStream); postData.addHeader("Content-Type", "application/x-www-form-urlencoded"); postData.addContentLength = true; postData.setData(stringStream); // postData is ready to be used as aPostData argument ... POSTing data to the current tab There is a convenience method in global scope (in Firefox, chrome://browser/content/browser.js): loadURI(aURI, aReferrer, aPostData, aAllowThirdPartyFixup); POSTing data to a new window window.openDialog('chrome://browser/content', '_blank', 'all,dialog=no', ...
Sidebar - Archive of obsolete content
th; } or function setSidebarWidth(newwidth) { window.top.document.getElementById("sidebar-box").width=newwidth; } You can also disable the ability to resize it manually, using the mouse, by hiding the sidebar's splitter element. For this snippet to work, you have to declare mainWindow as in the previous code block then write: mainWindow.document.getElementById("sidebar-splitter").hidden = true; Be aware that if you change the splitter's hidden attribute, you need to reset it to a safe value when your sidebar is closed, or replaced by another sidebar. For example, use this in your sidebar's Unload event handler: mainWindow.document.getElementById("sidebar-splitter").hidden = mainWindow.document.getElementById("sidebar-box").hidden; See Also Bootstrap demo addon that creates a ...
xml:base support in old browsers - Archive of obsolete content
null : xmlbase; return xmlbase; } ...
Communication between HTML and your extension - Archive of obsolete content
I found was far too complicated for what I wanted to achieve. Eventually I put the creation of the custom event into the stateChanged function that was handling the receipt of the AJAX request. After the HTML component was update with the result of the AJAX request, I created and dispatched the event like this: var event = document.createEvent("Events"); event.initEvent("my-custom-event", true, true); document.body.dispatchEvent(event); In the code of the extension that catches the loading of a new page I added this code: var doc = aEvent.originalTarget; // doc is document that triggered "onload" event // do something with the loaded page. // doc.location is a Location object (see below for a link). // You can use it to make your code executed on certain pages only. ...
Default Preferences - Archive of obsolete content
on, warning, error, or exception. Think of it more as an .ini file. Comments are perfectly acceptable. Inside your file you set preferences using the pref() function: pref("name", "value") example: pref('extensions.defaultPrefs.example.int', 1); pref('extensions.defaultPrefs.example.float', 0.1); pref('extensions.defaultPrefs.example.string', 'fadf'); pref('extensions.defaultPrefs.example.bool', true); Notice that unlike when you're reading preferences, writing default preferences uses the same function no matter the data type of the preference. You simply pass it directly to the function. Original Document Information Author(s): Tom Aratyn, Security Compass Permission granted to license under the CC:By-SA. ...
Displaying web content in an extension without security issues - Archive of obsolete content
nexpected side-effects. For example, your template document might have this code: <style type="text/css"> #entryTemplate { display: none; } </style> <div id="entryTemplate"> <div class="title"></div> <div class="description"></div> </div> Now to insert a new entry in the document you would do the following: var template = doc.getElementById("entryTemplate"); var entry = template.cloneNode(true); entry.removeAttribute("id"); entry.getElementsByClassName("title")[0].textContent = title; entry.getElementsByClassName("description")[0].textContent = description; template.parentNode.appendChild(entry); The important difference here is that the result will always have the same structure as the template tag. cloneNode() always creates a copy and textContent only manipulates text. So there is ...
Extension Versioning, Update and Compatibility - Archive of obsolete content
hashing algorithm and this hash is signed using the private key. The resultant data is DER encoded then base 64 encoded for inclusion in the update.rdf as an signature entry. Debugging and solving problems The update mechanism logs information to the console, and display various information which can help you to find problem. To enable the log: Set the value of extensions.logging.enabled to true (using URL about:config) Run Firefox from command with option -console If you encounter problems, search the output in console for your extension id, and see if failures were logged. ...
Extension Etiquette - Archive of obsolete content
ith an @, followed by a domain name that the author controls, e.g., "@example.com/foo/bar;1" It is important that the prefix that you use be unlikely to conflict with other code, and that it be indicative of the name of your add-on. Generic prefixes such as myextension-, or short prefixes such as ffx-, are likely to be used elsewhere, and therefore unsuitable to the purpose. Call .noConflict(true) where applicable Many common libraries which create global variables provide a method called noConflict, or similar, which revert any global variables they've declared, and return the object itself. For instance, calling jQuery.noConflict(true) will remove the window.jQuery and window.$ variables, and return the jQuery object itself, for future use by the caller. When available, these metho...
Inline options - Archive of obsolete content
<menuitem value="500" label="small"/> <menuitem value="800" label="medium"/> <menuitem value="1200" label="large"/> </menupopup> </menulist> </setting> <!-- Radio Button example (this example would be stored as a boolean) --> <setting pref="extensions.myaddon.options2" type="radio" title="Options 2"> <radiogroup> <radio value="false" label="disabled"/> <radio value="true" label="enabled"/> </radiogroup> </setting> <!-- Button example - not tied to a preference, but attached to a command --> <setting title="Do Something" type="control"> <button id="myaddon-button" label="Click Me" oncommand="alert('Thank you!');"/> </setting> Setting element changed notifications Most of the setting elements (it might be all I havent really looked), support oninputchanged...
Jetpack Processes - Archive of obsolete content
at compile time. However, the service has been removed entirely as of Firefox 12. These processes are relatively lightweight, do not have access to XPCOM, and can innately do little other than compute. Messaging facilities that allow them to communicate with their parent chrome process are the only means by which they can be endowed with any real power. Note: The above statement is not currently true, as js-ctypes is now provided to Jetpack processes as of bug 588563. A mechanism to optionally disable this feature has been proposed in bug 614351. Privileged APIs When script is evaluated in a Jetpack process via a call to nsIJetpack.evalScript(), the script's global scope is endowed with the following privileged APIs: sendMessage(aMessageName [, v1 [, v2 [, ...]]]) Similar to nsIJetpack.sendM...
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
ode, the nsMsgUtils.h header is being enhanced to fill in some of the gaps caused by the differences between the internal and external APIs. These enhancements make it easier to write code that will transparently compile using either API. The list of enhancements fall in to three categories. Changes to internal APIs to make them compatible with the external API. #define CaseInsensitiveCompare PR_TRUE This allows you to use CaseInsensitiveCompare as the parameter to various string methods that normally accept PR_TRUE under the internal API. #define ToInteger(prv, radix) ToInteger(reinterpret_cast<PRInt32*>(prv), radix) This allows you to pass a pointer to an nsresult to the ToInteger method, when it normally accepts a PRInt32. Note that you must pass the radix (normally 10). Changes to extern...
Offering a context menu for form controls - Archive of obsolete content
ght-clicking on form controls. 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. As a result, all controls in the window will support a context menu when right-clicked, since we've changed the core behavior of context menus to ove...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
typing like Java, making it extremely flexible and giving it qualities that in some senses could be considered similar to Lisp. Firefox 3.5 includes a number of extensions to the specification standardized in ECMAScript 3rd Edition, and can use JavaScript 1.7 and JavaScript 1.8. Listing 3: An example of a class definition in JavaScript function MyClass() { } MyClass.prototype = { property1 : true, property2 : 'string', method : function() { alert('Hello, world!'); } }; var obj = new MyClass(); obj.method(); DOM: An API for manipulating XML documents The Document Object Model (DOM) is a technical standard promulgated by the W3C, and is an API for manipulating the contents of XML documents as objects. In earlier dynamic HTML approaches, the typical method was to use the innerHT...
Adding windows and dialogs - Archive of obsolete content
omeDialog.xul", "xulschoolhello-some-dialog", "chrome,centerscreen", someValue, returnValue); // you can send as many extra parameters as you need. // if (returnValue.accepted) { do stuff } The optional parameters are available in the dialog code through the window.arguments property: let someValue = window.arguments[0]; let returnValue = window.arguments[1]; // returnValue.accepted = true; // returnValue.result = "something"; The parameter named returnValue is an object that the dialog will modify to reflect what the user did in it. This is the simplest way to have the dialog return something to its opener. Note that the opener will wait until the dialog is closed. This means the openDialog function call will not return until the dialog has been closed by the user. Common Dia...
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
first run code is only run once. The best approach in this case is to use a preference, as explained in the Handling Preferences section. 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. You should also change the preference value before you run any other first run code. Keep in mind that the user could have set multiple Firefox windows to open at startup, so there's a race condition on which...
Appendix D: Loading Scripts - Archive of obsolete content
your sandbox script, use content.wrappedJSObject // instead. let context = content; // Create the Sandbox let sandbox = Components.utils.Sandbox(context, { // Make properties of the context object available via the // script's global scope sandboxPrototype: context, // Wrap objects retrieved from the sandbox in XPCNativeWrappers. // This is the default action. ...
Appendix F: Monitoring DOM changes - Archive of obsolete content
ch only a single binding to a given DOM node at once, it is important when using this method to detach your binding from a node once your constructor has run. This is most easily done by adding a :not clause to the CSS selector that attaches your binding. For instance, when using the selector div:not([foo-binding-done]), you can detach your binding by running this.setAttribute("foo-binding-done", true) in your constructor. Monkey patching DOM methods When you are interested in changes to particular nodes, sometimes the best way is to wrap the DOM methods of those elements, as in the monkey patching section above. For instance, if you need to know about attribute changes to a particular node, then you should replace its setAttribute method with a function that calls the original setAttribute ...
JavaScript Object Management - Archive of obsolete content
um delay of 10-15ms (taken from this blog post), so it won't really run instantly. It is more than enough to let the window finish its load. Use window.setTimeout and window.setInterval to control timed code execution. In case you're using JavaScript Code Modules or XPCOM objects, where a window object is not readily available, use an nsITimer instead. This post suggests a way to achieve a true zero ms timeout, as a simple way to achieve parallelism in JS code. Notice the way we send callback functions as parameters, and the use of an alternate reference for this which we always name that. This is all necessary due to a JavaScript feature (quirk would be a better word for it) called Method Binding. The consequence of doing this wrong is to have a this reference that doesn't do what you...
User Notifications and Alerts - Archive of obsolete content
We do this when we need to handle clicks on the alert box. The image can have any size, but it is recommended that you use a medium, fixed size. The main disadvantage of using alerts is that support for the Alerts Service is not guaranteed for all platforms and Fire...
Updating addons broken by private browsing changes - Archive of obsolete content
s of Firefox 20. The supporting per-window private browsing article explains further about the equivalent notifications, which are all backwards compatible through to Firefox 12 (and are sent side-by-side with the global private browsing notifications in older versions). Chrome APIs OpenBrowserWindow: Takes an optional parameter to indicate desired properties of the window. Passing {private: true} will cause a private window to open, otherwise the window will always be non-private. Use {private: PrivateBrowsingUtils.isWindowPrivate(window)} to open a window that matches the current window's privacy status. openLinkIn: Can receive an extra private boolean property in the parameter object. internalSave: Takes a new required Document argument (prior to the optional boolean and string a...
Search Extension Tutorial (Draft) - Archive of obsolete content
first run, or the // new default is the same as the user value. if (firstRun || userPrefs.getCharPref(name) == value) userPrefs.clearUserPref(name); } function startup(data, reason) { firstRun = reason == ADDON_INSTALL; // Change the default engine name. // An engine with this name must already exist. setPref("browser.search.defaultenginename", "Example Engine", true); } function shutdown(data, reason) { // No need to do this if this is app shutdown. if (reason == APP_SHUTDOWN) return; // Reset our changes if the values have not been changed // in the meantime. for (let [name, [origValue, value]] in Iterator(savedPrefs)) { if (defaultPrefs.getCharPref(name) == value) defaultPrefs.setCharPref(name, origValue); ...
Underscores in class and ID Names - Archive of obsolete content
scores. Navigator 4.x honored the restriction against underscores, and so any class or ID name with an underscore will be ignored by Navigator 4.x, so the associated styles will never be applied. It also ignored escaped underscores. Internet Explorer 4.x and 5.x for Windows erroneously allowed underscores, and so were both non-conformant on this point until the errata was published. The same is true of IE4.x and 5.x for Macintosh. Internet Explorer 6 for Windows, published after the errata, permits underscores and escaped underscores. Opera 3.x through 5.x does not recognize underscores or escaped underscores, and so acts the same as Navigator 4.x in this regard. Recommendation Because support is so inconsistent between current browsers as well as older releases, authors are strongly ad...
Creating reusable content with CSS and XBL - Archive of obsolete content
ument.getAnonymousElementByAttribute(this, "anonid", "square") ]]></field> <field name="button"><![CDATA[ document.getAnonymousElementByAttribute(this, "anonid", "button") ]]></field> <method name="doDemo"> <body><![CDATA[ this.square.style.backgroundColor = "#cf4" this.square.style.marginLeft = "20em" this.button.setAttribute("disabled", "true") setTimeout(this.clearDemo, 2000, this) ]]></body> </method> <method name="clearDemo"> <parameter name="me"/> <body><![CDATA[ me.square.style.backgroundColor = "transparent" me.square.style.marginLeft = "0" me.button.removeAttribute("disabled") ]]></body> </method> </implementation> <handlers> <handler event...
MozOrientation - Archive of obsolete content
Notes This event is only dispatched if an accelerometer is available on the current device. Specification Not part of any specification. ...
chargingchange - Archive of obsolete content
Interface Event Bubbles No Cancelable No Target BatteryManager Default Action None Properties The event callback doesn't receive any event objects, but properties can be read from the BatteryManager object received from the navigator.getBattery method. Property Type Description BatteryManager.charging boolean The system's battery charging status. Returns true if the battery is charging, if the state of the system's battery is not determinable, or if no battery is attached to the system. Returns false if the battery is discharging. Read only. Example navigator.getBattery().then(function(battery) { console.log("Battery charging? " + (battery.charging ? "Yes" : "No")); battery.addEventListener('chargingchange', function() { console.log(...
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
age.</p> <br /> <!-- ***** This code dynamically creates the Tabbed Menu if the browser has support to XMLHTTPRequest, since the mechanism used here is XMLHTTPRequest ***** --> <script type="text/javascript" language="javascript"> //// /// Object detection // var xComp=null; var testXMLHTTPRequest=false; try { xComp = new XMLHttpRequest(); if(xComp) testXMLHTTPRequest=true; } catch (e) { try { xComp = new ActiveXObject("Microsoft.XMLHTTP"); if(xComp) testXMLHTTPRequest=true; } catch (e) { } } if(testXMLHTTPRequest&&document.getElementsByTagName) { document.write("<span style=\"margin-left:1em;\"> <a href=\"javascript:\" class=\"tab \" onclick=\"callDevEdge('/viewsource/catalog-new_en.xml',this);return false;\">DevEdge News</a> <a href=\"javascript...
Defining Cross-Browser Tooltips - Archive of obsolete content
d by the lang attribute. In other words, alt text should only be displayed when a user agent cannot display the primary content of the element (e.g., a text-mode browser that cannot display images). In a visual browser, the image should be displayed and the alt text should not. This assumes that the browser can find the image and that it supports the image format used; if either of these is not true, and the image cannot be displayed, then the alt text should be displayed in place of the missing image. On the other hand, the HTML 4.01 definition of the title attribute states: title = text CS This attribute offers advisory information about the element for which it is set. Unlike the TITLE element, which provides information about an entire document and may only appear once, the title a...
Images, Tables, and Mysterious Gaps - Archive of obsolete content
cked on top of one another instead of being shown side-by-side. One potential solution is to add a class to any image that needs to be block-level and then write the rule to match. td img.decoration {display: block;} <td><img src="reddot.gif" class="decoration"></td> Depending on the design, though, that could lead to a lot of classes added for this one simple effect. This would be especially true if there are many single-pixel cells intended to create cool stacked lines, or something like that. If you have markup that lends itself well to this approach, you could class the table rows instead of the images. Thus you might have: tr.decoration img {display: block;} ...along with the following change in the markup: <tr class="decoration"><td style="background: red;"> <img src="smallred.gif...
Same-origin policy for file: URIs - Archive of obsolete content
...
Visualizing an audio spectrum - Archive of obsolete content
zAudioAvailable event does an FFT of the samples and displays them in a canvas. NOTE: You can use the AudioNode called AnalyserNode to perform real-time FFT analysis on an audio stream, rather than the code shown below. ...
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
control on operating systems such as Windows NT, 2000 & XP. Usage Insert some HTML like this into your content: <OBJECT classid="CLSID:DBB2DE32-61F1-4F7F-BEB8-A37F5BC24EE2" width="500" height="300"> <PARAM name="type" value="video/quicktime"/> <PARAM name="src" value="http://www.foobar.com/some_movie.mov"/> <!-- Custom arguments --> <PARAM name="loop" value="true"/> </OBJECT> The CLASSID attribute tells IE to create an instance of the plug-in hosting control, the WIDTH and HEIGHT specify the dimensions in pixels. You may optionally specify a CODEBASE attribute if you have packaged the control into a CAB file and wish for it to be installed automatically. The following <EMBED> attributes have <PARAM> tag equivalents: <PARAM name="type" ...> is equiv...
Automated testing tips and tricks - Archive of obsolete content
firefox-bin -P testprofile -chrome chrome://tests/content/quit.xul<code> the above process may exit before the profile is completely created. ...
Structure of an installable bundle - Archive of obsolete content
Note that other files and directories (e.g. chrome.manifest, components, defaults) in bootstrapped extensions are not processed by a supporting application. (>=2.0) /chrome.manifest Chrome Registration Manifest (>=1.8) /components/* XPCOM components (*.js, *.dll), and interface files from *.xpt (>=1.7) /defaults/prefe...
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <RDF:Seq about="urn:mozilla:package:root"> <RDF:li resource="urn:mozilla:package:tinderstatus"/> </RDF:Seq> <RDF:Description about="urn:mozilla:package:tinderstatus" chrome:displayName="Mozilla Tinderstatus Extension" chrome:author="Myk Melez" chrome:name="tinderstatus" chrome:extension="true" chrome:description="Displays tinderbox status for the Mozilla codebase."> </RDF:Description> <RDF:Seq about="urn:mozilla:overlays"> <RDF:li resource="chrome://navigator/content/navigator.xul"/> </RDF:Seq> <RDF:Seq about="chrome://navigator/content/navigator.xul"> <RDF:li>chrome://tinderstatus/content/tinderstatusOverlay.xul</RDF:li> </RDF:Seq> </RDF:RDF> install.js, on the other h...
In-Depth - Archive of obsolete content
in one of its 4 different states (Normal, Hover, Mouse Down, and Disabled). To cut the pieces out you need to define rectangles in the css file like this: #button-send { -moz-image-region: rect(294px 23px 315px 0px); } #button-send:hover { -moz-image-region: rect(294px 46px 315px 23px); } #button-send:hover:active { -moz-image-region: rect(294px 69px 315px 46px); } #button-send[disabled="true"] { -moz-image-region: rect(294px 92px 315px 69px) !important; } The properties for Rect are listed in a clockwise fashion - Top, Right, Bottom, Left. Adding an image to the right of a toolbar This tutorial is done with Mozilla 1.2 in mind. The layout of files can and probably will change over time, but the basics should remain the same. By default, Mozilla 1.2 doesn't support images on the r...
Dehydra Function Reference - Archive of obsolete content
rsion similar to version() in JS 1.7. strict boolean: Controls JS strict mode werror boolean: Turns JS warnings into errors gczeal int: This is a write-only parameter to set turn on frequent garbage collection. It is a mainly useful for debugging Dehydra for rooting bugs. gczeal is only enabled when SpiderMonkey and Dehydra are compiled with DEBUG macro defined. require() Example require({strict:true, gczeal:2}) if (require().werror) print("werror is set") warning([code,] msg [, loc]) Print a warning message using the GCC warning mechanism. If -Werror is specified this will cause compilation to fail. Optional: code is an integer parameter that allows warnings to be enabled(-Wfoo) and disabled(-Wno-) on the GCC commandline. This parameter is used when the first argument to warning() is an in...
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
to your classpath. This library provides the interfaces necessary to bootstrap Mozilla and call XPCOM methods. To start embedding, we use the methods provided by the Mozilla singleton class. ...
Error Console - Archive of obsolete content
Use the Web Console instead, for web content, or the Browser Console for chrome content. The Error Console is a tool available in most Mozilla-based applications that is used for reporting errors in the application chrome and in web pages user opens. It reports JavaScript-related errors and warnings, CSS errors and arbitrary messages from chrome code. In Firefox, the Error Console can be opened from the tools menu or by Ctrl-Shift-J. ...
Exception logging in JavaScript - Archive of obsolete content
pt frames logged (in the call chain above that would be when an exception is unhandled in frame 4). Note that the following will have no effect on the NS_NOINTERFACE exceptions outlined in rules 3 and 4 above - those exceptions will not be reported in any case. There are two ways you can accomplish this. First, you can set the boolean preference dom.report_all_js_exceptions. If this preference is true, all exceptions from inner frames will be logged. Alternatively, you can set the environment variable MOZ_REPORT_ALL_JS_EXCEPTIONS. It doesn't matter what value you set this to (it can even be 0). If the variable exists, all exceptions from inner frames will be reported. See also Error Console bug 415498 ...
Block and Line Layout Cheat Sheet - Archive of obsolete content
ncapsulates the transient reflow state for a nsLineBox that contains a block frame. mNextRCFrame During an incremental reflow, this member holds current frame in the reflow chain. nsLineLayout Encapsulates the transient reflow state for a nsLineBox that contains inline frames. A new nsLineLayout object is created for each inline linebox that is flowed. mFlags LL_ENDSINWHITESPACE Set to true by default when starting line layout. LL_UNDERSTANDSNWHITESPACE LL_TEXTSTARTSWITHNBSP LL_FIRSTLETTERSTYLEOK LL_ISTOPOFPAGE LL_UPDATEDBAND LL_IMPACTEDBYFLOATERS LL_LASTFLOATERWASLETTERFRAME LL_CANPLACEFLOATER LL_KNOWSTRICTMODE LL_INSTRICTMODE LL_LINEENDSINBR PerFrameData (Why isn't this just stored in the frame?) mFlags PFD_RELATIVEPOS PFD_ISTEXTFRAME PFD_ISNONEMPT...
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
cks whether the channel has "Content-Disposition: attachment" set. If so, it skips trying to find an internal viewer and goes right over to looking for a stream converter. Otherwise, DispatchContent goes through a three-step process to try to find the correct listener. The basic idea is that DispatchContent calls nsDocumentOpenInfo::TryContentListener on various content listeners; if that returns true, we have found the right listener and we are done. TryContentListener makes use of the IsPreferred and CanHandleContent functions on nsIURIContentListener and calls DoContent() on the listener if it claims to handle the data, as well as hooking up a stream converter if the listener asks for one. If any of those steps fails, the function returns false so that another content listener will be looke...
Documentation for BiDi Mozilla - Archive of obsolete content
rnational Components for Unicode (ICU), which was chosen after comparing and testing the available open-source implementations. As far as we could discover, ICU is the only one which is 100% compatible with UBA, including support for explicit directional controls (LRO, RLO, etc, and their HTML equivalents). Bidi processing for a given HTML document will only take place if one of the following is true: The page includes a Hebrew or Arabic character or a Hindi digit. This is determined in nsTextFragment::SetTo The page includes a element with the attribute dir=rtl, either explicitly (nsGenericHTMLElement::MapCommonAttributesInto), or as a consequence of a style rule (MapDeclarationTextInto in nsCSSStyleRule.cpp) All these cases use nsDocument::EnableBidi to set the flag mBidiEnabled. In a Bid...
Syncing custom preferences - Archive of obsolete content
nc is enabled, Firefox Sync will synchronize preferences between the same application based on a whitelist. That means preferences between Firefox and Fennec, for instance, are never synced. To sync preferences between Firefoxes, Fennecs, Thunderbirds, etc., ensure the prefs are whitelisted. The whitelist is determined as follows: for each services.sync.prefs.sync.<pref> preference that is set to true, Firefox Sync will sync the <pref> preference. For example, if your add-on had a pref called extension.frobnaz.foobar, to have it synced, create a bool preference called services.sync.prefs.sync.extension.frobnaz.foobar and set it to true. The most convenient place for this would be your add-on's default preferences, though if you want to give the user a choice to opt-in, you can also do it progr...
Hidden prefs - Archive of obsolete content
When that mail gets sent, Approved: test@test.com will be in the message in the headers. This is a useful trick for newsgroup moderators who want moderate from mozilla. 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. There is UI for the "mail.collect_email_address_outgoing" pref. See "Edit | Preferences.. | Mail & Newsgroups | Addressing" ...
Settings - Archive of obsolete content
With the above manifest the following stored properties are available in the jetpack's code: * jetpack.storage.settings.twitt...
Jetpack Snippets - Archive of obsolete content
','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'); document.body.appendChild(firebug); (function(){if(window.firebug.version){firebug.init();}else{setTimeout(arguments.callee);}})();void(firebug); ]]></script> </body></html>, width: 800, //wide enough to use firebug onSelect: function(slide) { slide.slide(800, true); }}); Calling into a slidebar from the global jetpack scope jetpack.slideBar.append({ onReady: function (slide) { // call out to a global function, passing the slidebar object exInitSlidebar(slide); }, ...});function exInitSlidebar(aSlidebar) { // This variable will now be global slider = aSlidebar;} // then, accessing the slidebar HTMLvar tl = slider.contentDocument.getElem...
Settings - Archive of obsolete content
With the above manifest the following stored properties are available in the jetpack's code: jetpack.storage.settings.twitte...
Simple Storage - Archive of obsolete content
notes;// Updates the Jetpack menu with the current notes. We'll add a Notes menu with// a submenu, which lists all the notes. If there are no notes, we'll show a// disabled "(Empty)" menuitem.function updateJetpackMenu() { jetpack.menu.set({ label: "Notes", menu: new jetpack.Menu(notes.length > 0 ? notes : [{ label: "(Empty)", disabled: true }]) });}// Modify the page's context menu by sneaking in before it's shown. If there's// a selection, add a Note menuitem that makes a new note. Otherwise, don't// modify the menu at all. We'll limit the number of notes to 20. Old notes// will be forgotten. :(jetpack.menu.context.page.beforeShow = function (menu) { menu.reset(); if (jetpack.selection.text) menu.add({ label: "Note",...
Simple Storage - Archive of obsolete content
Updates the Jetpack menu with the current notes. We'll add a Notes menu with // a submenu, which lists all the notes. If there are no notes, we'll show a // disabled "(Empty)" menuitem. function updateJetpackMenu() { jetpack.menu.set({ label: "Notes", menu: new jetpack.Menu(notes.length > 0 ? notes : [{ label: "(Empty)", disabled: true }]) }); } // Modify the page's context menu by sneaking in before it's shown. If there's // a selection, add a Note menuitem that makes a new note. Otherwise, don't // modify the menu at all. We'll limit the number of notes to 20. Old notes // will be forgotten. :( jetpack.menu.context.page.beforeShow = function (menu) { menu.reset(); if (jetpack.selection.text) menu.add({ la...
Makefile.mozextension.2 - Archive of obsolete content
Either remove (clean it), or choose individual targets to buil...
Monitoring downloads - Archive of obsolete content
tooltip is included that displays the full source URL of the file. Download the full sample. Setting up When the extension loads, it will do some housekeeping chores. In particular, it needs to get an instance of the Download Manager's nsIDownloadManager interface and create the database into which its data will be stored. ...
LIR - Archive of obsolete content
use Call 32 not in use 33 callv void call subroutine that returns void 34 calli integer call subroutine that returns an int 35 callq quad 64 bit call subroutine that returns a quad 36 calld double call subroutine that returns a double Branch 37 j void jump always 38 jt void jump if true 39 jf void jump if false 40 jtbl void jump to address in table 41 label void a jump target (no machine code is emitted for this) 42 not in use Guards 43 x void exit always 44 xt void exit if true 45 xf void exit if false 46 xtbl void exit via indirect jump 47 xbarrier void...
Nanojit - Archive of obsolete content
Guards are required in a cross platform dynamic language like JavaScript. Certain assumptions are made when a particular JIT code is generated. For example, in an instruction INR x, a guard would check that x doesn't overflow the range for a 32 bit integer. The JIT code would have a guard checking this condition(an xt guard), and would return to the interpreter if the condition turns out to be true. The interpreter is then equipped to handle the overflow. Hence, guards are needed to prevent certain erroneous behaviour that might result from the assumptions that are generally made while JIT is generated. TODO: Explain guards, guard records, VMSideExit, Fragmento, VerboseWriter::formatGuard... ...
New Security Model for Web Services - Archive of obsolete content
la.org, etc. will be granted access. Implementation nsIWebScriptsAccessService This interface provides a way to check whether the running script has access to the server that the script wishes to communicate. boolean canAccess(in nsIURI aTransportURI, in AString aType); aTransportURI - The service URI aType - Type requested by the script ( ex. soapv, soap, load, etc. ) return PR_TRUE if access granted else PR_FALSE void invalidateCache(in string aTransportURI); Invalidate cached entry for the given transport uri. Empty the cache by passing in a empty string nsWebScriptsAccess(Implements nsIWebScriptsAccessService) Maintains access information, for servers, in an access-info-cache ( hashtable ). If an entry was not found in the cache creates one by loadi...
Plugin Architecture - Archive of obsolete content
ts, this document concentrates on plugins. Sequence of events In content A content node for a plugin DOM element gets created In BindToTree (usually) or another function, it calls LoadObject LoadObject either notices directly that it is dealing with a plugin, or it starts a network request and notices this in OnStartRequest When it realizes that, it tries to create a frame, if aNotify is true and no frame exists yet If a frame exists now, it is asked to instantiate the plugin That was the normal case. If a frame comes into existance independent of that, it tells the content node that it exists now (nsIObjectLoadingContent::hasNewFrame). That function will post an event and when that fires, asks the frame to instantiate the plugin. (The event is necessary because by the time HasNewFr...
HostWindow - Archive of obsolete content
are considering whether to support a sidebar in future versions of Prism and welcome input on this subject. Status - Area of the statusbar that displays the loading status message and a "percent complete" progress bar, as well as the "gear" menu that provides access to Prism commands such as displaying the error console. To display the status bar, the statusbar option in webapp.ini must be set to true. Command Menu - A popup menu showing several Prism-specific commands. ...
New Skin Notes - Archive of obsolete content
d links different color. 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). Your statement that "It looks odd when someone who uses Devmo on regular basis sees some violet links just because he already worked with this site yesterday" holds true for every single place on the web, yet visited links use different styling on most sites. --Nickolay 01:34, 31 Aug 2005 (PDT) Ok, so I'm asking just to change this color. --Gandalf 04:55, 31 Aug 2005 (PDT) Fine, changed. --dria The default link color is to bright. It's less readable than the old one. I'd suggest to use the color from Cavedish. -- gandalf That was my first thought, too. -...
RDF Datasource How-To - Archive of obsolete content
call the component manager's RegisterComponent() method: extern "C" PR_IMPLEMENT(nsresult) NSRegisterSelf(nsISupports* aServiceManager, const char* aPath) { nsresult rv; ... // Assume compMgr refers to the component manager rv = compMgr->RegisterComponent(kMyDataSourceCID, "My Data Source", NS_RDF_DATASOURCE_PROGID_PREFIX "my-datasource", aPath, PR_TRUE, PR_TRUE); ... } Replace kMyDataSourceCID with your datasource's CLSID. Replace "My Data Source" with a descriptive string that should appear in the registry. Finally, replace "my-datasource" with a value appropriate for your datasource. This value, when prefixed with "rdf:", is a datasource identifier, and may be used with nsIRDFService::GetDataSource() to retrieve your datasource from the R...
Remote XUL - Archive of obsolete content
However, there is a whitelist that lets you specify sites that can still use remote XUL. ...
Remotely debugging Firefox for Metro - Archive of obsolete content
ndows 8 (Metro-style) Firefox running in the touch-friendly "Metro" mode on a Windows 8 computer. Firefox running in classic "desktop" mode on Windows, Mac OS X, or Linux, either on a separate computer or in a separate profile on the same computer. ...
Frequently Asked Questions - Archive of obsolete content
ople view the SVG files on their website. The native SVG support must be turned off before Mozilla will look to see if there's an SVG plugin installed. This is done by toggling a hidden user configuration preference (pref). To access the pref type about:config into the URL bar, then type svg.enabled into the Filter field. When you double click on the pref you will see its value change to and from true/false, turning the native support on/off. How does Mozilla's SVG implementation compare to Adobe's? Mozilla's native implementation is less complete than Adobe SVG Viewer's in general. There are major features such as filters and SMIL based animation that have still to be implemented in Mozilla. However, Mozilla's implementation already supports some things that Adobe's lacks, particularly part...
Safely loading URIs - Archive of obsolete content
what data you have, prefer checkLoadURIWithPrincipal to checkLoadURI and prefer checkLoadURI to checkLoadURIStr. Note that checkLoadURIWithPrincipal is not scriptable in Gecko 1.8, so extensions are not able to use it. Changes in Gecko 1.9 A key security change in Gecko 1.9 is the addition of the new security.fileuri.strict_origin_policy preference. 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. See Same-origin policy for file: URIs for details. ...
The life of an HTML HTTP request - Archive of obsolete content
w is done by the nsHTMLContentSink::StartLayout(), StartLayout() calls PresShell::InitialReflow(). StartLayout is called quite early in the parsing process, for HTML it's called in nsHTMLContentSink::OpenBody() (among other places). TODO: How are nsIFrames reflowed after a change when they already exist? (8) Each nsIFrame knows how how to draw itself on the screen. When the PresShell [Note: not true, who really does the call?] has layouted (reflowed) the frames it calls nsIFrame::Paint() method of all frames. These get passed references to the presentation context and a rendering context to do the drawing on. The rendering context implementation is a native class (nsGtkRenderingContext on unix) that knows how to draw in a window. TODO: Views, ViewManager, EventStateManager? Diagram created...
Tuning Pageload - Archive of obsolete content
During this delay, the page that's coming in is not painted, unless it ends up fully loaded before the delay expires. The idea here is twofold.This reduces ugly visual jitter as the new page comes in by not starting painting till after we have a bunch of the data.This makes overall page load time shorter by not doing extra repaints very early on. content.interrupt.parsing This preference, when true, means that the content sink can tell the parser to stop for now and return to the event loop, which allows layout and painting to happen. If the parser gets a large chunk of data, it will try to parse it all, building the corresponding content model. Since layout and painting happen asynchronously, while the parser is working there is no layout or painting. So this preference is used to increas...
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
On WIN-16, the thread's attempt to address the <tt>SharedData</tt> through the pointer shared will provide interesting (though always incorrect) results. It's difficult to tell exaclty where the updated...
Binding Implementations - Archive of obsolete content
are used to specify a getter or setter, then the element form is ignored. A getter contains script whose return value is handed back when the property is requested. A setter contains a script that is invoked when a new value is assigned to the property. In script, the word val is used to represent the new value. Properties can be designated as constant using the readonly attribute. When set to true, the property's value cannot be altered. If a property is readonly and a setter is defined, then the setter is ignored. Properties also support a shorthand syntax for defining getters and setters that forward requests or assignments to an anonymous content element. The element attribute specifies the ID of anonymous content underneath the bound element that should be used when obtained the prope...
DOM Interfaces - Archive of obsolete content
hecks to see if any anonymous child of "element" is itself an element. 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; ...
XML in Mozilla - Archive of obsolete content
is also a proprietary API from scripts to the XPointer processor. There is a testcase for XPointers that you can also study. Lastly, there is a pref you might want to try (especially useful with FIXptr) that will select the link target when you traverse it. There is no UI for setting this pref yet, so you will need to manually edit the preferences file. Add this line: pref("layout.selectanchor", true); DOM Load and Save Methods document.load() is a part of an old version of the W3C DOM Level 3 Load & Save module. Mozilla currently implements only the load() method and the document.async property. Outside Supported XML W3C Recommendations Specification or Technology Documentation Mozilla Project XSLT W3C Recommendation XSLT ...
File.macAlias - Archive of obsolete content
File.macAlias In this example, a mac alias is created for software (AppleCD Audio Player) that is installed locally. ...
File.windowsShortcut - Archive of obsolete content
ch the program itself is installed, for example, C:\Program Files\Netscape\Netscape 6\" on Windows) to Windows software (misc.exe) that is installed in the "Windows" directory. ...
confirm - Archive of obsolete content
tom title for button 0. aButton1Title Custom title for button 1. aButton2Title Custom title for button 2. aCheckMsg A string to display as a checkbox label. aCheckState An object with a boolean value property representing the state of the checkbox: When the dialog box is shown, its checkbox will be checked when this object's value is true. After the user presses a button (or closes the window), the value property is updated according to the checkbox. var check = { value: false }; var button = confirm("Are you sure you want to install FooBar 0.1?", "Confirm", STD_YES_NO_BUTTONS, null, null, null, "Install F...
writeString - Archive of obsolete content
Summary Changes a value in a .ini file. Method of WinProfile object Syntax Boolean writeString ( String section, String key, String value); Parameters The method has the following parameters: section Section in the file, such as "boot" or "drivers". key The key in that section whose value to change. value The new value. Returns True if successfully scheduled, otherwise, false. Description The writeString method is similar to the Windows API function WritePrivateProfileString. To delete an existing value, supply null as the value parameter. Unlike the WritePrivateProfileString function, this method does not support using a null key to delete an entire section. Values are not actually written until performInstall is called. Example To s...
keyExists - Archive of obsolete content
d 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 } } ...
highlightnonmatches - Archive of obsolete content
...
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
...
searchbutton - Archive of obsolete content
Otherwise, the command event is fired whenever the user modifies the value. ...
treelines - Archive of obsolete content
This is false by default. ...
accelerated - Archive of obsolete content
...
afterselected - Archive of obsolete content
This is automatically set when needed and you shouldn't adjust it manually. ...
allownegativeassertions - Archive of obsolete content
...
alternatingbackground - Archive of obsolete content
You can use the :-moz-tree-row CSS style to do this instead. ...
alwaysopenpopup - Archive of obsolete content
If false, the default value, the popup will be hidden. ...
autocheck - Archive of obsolete content
<< XUL Reference home autocheck Type: boolean If this attribute is true or left out, the checked state of the button will be switched each time the button is pressed. If this attribute is false, the checked state must be adjusted manually. When autocheck is true, the button type should be "checkbox" or "radio". ...
autoFillAfterMatch - Archive of obsolete content
<< XUL Reference home autoFillAfterMatch Obsolete since Gecko 1.9.1 Type: boolean If set to true, the entire text of the best match will be displayed at the end of the input. If false, only the text that hasn't been entered yet will be filled in. The textbox.autoFill attribute must be set to true to use this feature. As of Gecko 1.9.1, this attribute is superseded by the completedefaultindex attribute. ...
autocompleteenabled - Archive of obsolete content
...
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. If this attribute is set to true or omitted, autoscroll will be enabled or depending on the user preference general.autoScroll. ...
beforeselected - Archive of obsolete content
This is set automatically set when needed and you shouldn't adjust it manually. ...
buttondisabledaccept - Archive of obsolete content
...
clicktoscroll - Archive of obsolete content
<< XUL Reference home clicktoscroll Type: boolean clicktoscroll, if true, the arrows must be clicked to scroll the scrollbox content. If false, the mouse must be hovered over the arrows to scroll automatically. ...
close - Archive of obsolete content
Pressing the close button will close the panel. ...
closebutton - Archive of obsolete content
This feature is used by the tabbrowser to provide the facilities for adding and closing tabs. ...
coalesceduplicatearcs - Archive of obsolete content
...
collapsed - Archive of obsolete content
<< XUL Reference home collapsed Type: boolean If true, then the element is collapsed and does not appear. It is equivalent to setting the CSS visibility property to collapse. ...
commandupdater - Archive of obsolete content
Typically, this is used to update menu commands such as Undo and Cut based on when an event occurs. ...
completedefaultindex - Archive of obsolete content
If set to false or omitted, the value must be selected from the list. ...
completeselectedindex - Archive of obsolete content
...
panel.consumeoutsideclicks - Archive of obsolete content
If set to false, the rollup event is not consumed. This attribute should be used instead of setConsumeRollupEvent. ...
container - Archive of obsolete content
This would be used for folders. ...
current - Archive of obsolete content
This is typically used by a theme to customize the focus ring. ...
customizable - Archive of obsolete content
This causes the set of buttons to be persisted across sessions. ...
cycler - Archive of obsolete content
In the case, clicking on a cell in the column will alternate its state between on and off. This is used, for example, in a mail window, for a column that indicates that the message is read or unread with a small mark in the cell. ...
default - Archive of obsolete content
...
disableautocomplete - Archive of obsolete content
You might use a script to change this attribute. If false, the default, autocomplete is enabled. ...
disableKeyNavigation - Archive of obsolete content
...
disableautoselect - Archive of obsolete content
If the text does not match any of the items in the list, the menu selection is cleared. ...
disablechrome - Archive of obsolete content
This is used to hide chrome when showing in-browser UI such as the about:addons page, and causes the toolbars to be hidden, with only the tab strip (and, if currently displayed, the add-on bar) left showing. ...
disableclose - Archive of obsolete content
...
disabled - Archive of obsolete content
home disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
disablefastfind - Archive of obsolete content
<< XUL Reference homedisablefastfindType: booleanPut disablefastfind="true" on the root element of a XUL document, which is intended to be loaded in a tab, to disable the find bar for the tab with this document. This is used to prevent the find bar from being displayed when it's not supported by the content (such as in the Add-ons manager tab). ...
disablesecurity - Archive of obsolete content
Omit this attribute off to enable it. ...
dragging - Archive of obsolete content
<< XUL Reference home dragging Type: boolean This attribute will be set to true if the column is being dragged. This attribute is set automatically; you shouldn't adjust it yourself. ...
drawintitlebar - Archive of obsolete content
This allows the window to draw in the title bar. ...
empty - Archive of obsolete content
<< XUL Reference home empty Type: boolean Set to true if the element is a container that contains no children. This will be set by the template builder as needed. ...
enableColumnDrag - Archive of obsolete content
...
enablehistory - Archive of obsolete content
<< XUL Reference home Note: For SeaMonkey 2.0 and all versions of Thunderbird prior to 3.0 you also need to provide the disablehistory attribute. enablehistory New in Thunderbird 1Requires SeaMonkey 2.0 Type: boolean If true, an arrow button will appear on the end of the textbox which, when pressed, will open a dropdown menu of all available results. ...
fadein - Archive of obsolete content
<< XUL Reference home fadein Type: boolean This attribute is set to true if the tab is fading in or out. This typically means that the tab is in the process of appearing or disappearing. ...
first-tab - Archive of obsolete content
<< XUL Reference home first-tab Type: boolean This attribute will be set to true for the first tab. This attribute should not be set manually, but is useful in a theme if the first tab should be styled differently. ...
firstpage - Archive of obsolete content
...
fixed - Archive of obsolete content
Any splitter to either side will resize those columns while keeping the fixed column at a constant size. ...
focused - Archive of obsolete content
...
forcecomplete - Archive of obsolete content
If false, it will only be filled in when the user selects an item. ...
fullscreenbutton - Archive of obsolete content
Supported on Mac OS X 10.7 Lion and later and on Windows. ...
grippyhidden - Archive of obsolete content
<< XUL Reference home grippyhidden SeaMonkey only Type: boolean When set to true, the grippy will be hidden. When set to false, the default, the grippy will be shown. ...
handleCtrlTab - Archive of obsolete content
If the Shift key is also held down, the previous tab will be displayed. ...
hidden - Archive of obsolete content
<< XUL Reference home hidden Type: boolean If set to true, the element is not displayed. This is similar to setting the CSS display property to 'none'. ...
hidechrome - Archive of obsolete content
...
hidecolumnpicker - Archive of obsolete content
The default value is false. ...
hideheader - Archive of obsolete content
<< XUL Reference home hideheader Type: boolean Set this to true to indicate that the tree column header should be displayed without any column header styling. If you don't set a label for that column either, the header is not displayed at all. ...
hidespinbuttons - Archive of obsolete content
<< XUL Reference home hidespinbuttons Type: boolean If true, the number box does not have arrow buttons next to it to allow the user to adjust the value. The value may still be adjusted with the keyboard. The default value is false. ...
ignoreblurwhilesearching - Archive of obsolete content
...
ignorecase - Archive of obsolete content
<< XUL Reference home ignorecase Type: boolean Set to true to indicate that the case does not matter when making comparisons. Otherwise, the default value is false, to indicate that the value should match with the same case. ...
ignoreincolumnpicker - Archive of obsolete content
...
ignorekeys - Archive of obsolete content
...
instantApply - Archive of obsolete content
...
inverted - Archive of obsolete content
<< XUL Reference home inverted Type: boolean For boolean preferences, if this attribute is set to true, it indicates that the value of the preference is the reverse of the user interface element attached to it. For instance, checking the checkbox disables the preference instead of enabling it. ...
iscontainer - Archive of obsolete content
<< XUL Reference home iscontainer Type: boolean Indicates whether rules match based on containment. If not specified, the rule may match regardless of whether a node is a container or not. true: The rule will only match nodes that are marked as containers. This would apply to nodes that represent folders. false: The rule will only match nodes that are not marked as containers. ...
isempty - Archive of obsolete content
<< XUL Reference home isempty Type: boolean Indicates whether rules match based on emptyness. If not specified, the rule may match regardless of whether a node has children or not. true: The rule will only match nodes that contain no child elements. false: The rule will only match nodes that contain one or more child elements. ...
last-tab - Archive of obsolete content
<< XUL Reference home last-tab Type: boolean This attribute will be set to true for the last tab. This attribute should not be set manually, but is useful in a theme if the last tab should be styled differently. ...
lastpage - Archive of obsolete content
...
lightweightthemes - Archive of obsolete content
...
menuitem.name - Archive of obsolete content
name Radio menuitems with the same name as put into a group. Only one menuitem in each radio group can be checked at a time. ...
multiline - Archive of obsolete content
If the user presses Enter, a new line is started. ...
multiple - Archive of obsolete content
Any of the values may match. ...
negate - Archive of obsolete content
<< XUL Reference home negate Type: boolean Set to true to indicate that the comparison should be reversed. The where clause matches if the condition is false, and does not match if the condition is true. ...
noautofocus - Archive of obsolete content
...
noautohide - Archive of obsolete content
...
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. If true, the element will not receive initial focus. This lets you prevent things like descriptions and labels from inadvertently receiving initial focus. ...
nomatch - Archive of obsolete content
...
oncommand - Archive of obsolete content
en a user selects a menu item or presses a keyboard shortcut attached to the command. Example 1: in-line code <button label="Click me" oncommand="alert('Hi')"/> Example 2: function with source argument <button label="Click me" oncommand="doSomeProcessing(event.target)"/> And here is the definition of the function: function doSomeProcessing(source) { alert("source: " + source); return true; } See also command element ...
open - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › open
The open attribute is not present if the menu is closed. ...
panel.ignorekeys - Archive of obsolete content
...
panel.noautohide - Archive of obsolete content
...
pending - Archive of obsolete content
<< XUL Reference home pending Type: boolean This attribute is set to true if the tab is currently in the process of being restored by the session store service. Once the tab is restored, this attribute is removed. You can determine if a tab is being restored by checking to see if hasAttribute("pending") is true. If the user has turned on the "Don't load tabs until selected" preference, the pending attribute is set on tabs until they get loaded. ...
pinned - Archive of obsolete content
<< XUL Reference home pinned Type: boolean This attribute is set to true if the tab has been pinned (that is, if it's an app tab). The tabbrowser element's pinTab and unpinTab methods handle pinning and unpinning tabs. ...
preference-editable - Archive of obsolete content
The preference attribute may be used to connect to a preference element. This is useful for custom elements implemented in XBL. The element should fire change, command, or input event when the value is changed so that the preference will update accordingly. ...
preference.type - Archive of obsolete content
Usually a checkbox would be connected to these preferences. int An integer string A string unichar A Unicode string wstring A localized string. ...
prefpane.selected - Archive of obsolete content
<< XUL Reference home selected Type: boolean This attribute will be set to true for the currently selected prefpane. To change the selected pane, use the prefwindow's showPane method. See also selected ...
primary - Archive of obsolete content
<< XUL Reference home primary Type: boolean If set to true, the treecol will have indentation and twisties drawn to the left of it to indicate the hierarchy level of the rows. If no column has the primary attribute set to true, the tree may still contain nested rows, although no indication will be given to the user. The attribute also controls whether the column picker allows the user to deselect this column. ...
readonly - Archive of obsolete content
<< XUL Reference home readonly Type: boolean If set to true, then the user cannot change the value of the element. However, the value may still be modified by a script. ...
setfocus - Archive of obsolete content
If this attribute is false, the focus does not change during navigation. ...
showcommentcolumn - Archive of obsolete content
<< XUL Reference home showcommentcolumn New in Thunderbird 3Requires SeaMonkey 2.0 Type: boolean If true, a comment column appears in the popup. For the URL history, the comment column will contain the page titles associated with each URL. If this attribute is not specified, the comment column doesn't appear. ...
showcaret - Archive of obsolete content
<< XUL Reference home showcaret Type: boolean Whether or not to cause a typing caret to be visible in the content area. Default is false. Examples <iframe id="content-body" src="http://www.mozilla.org/" showcaret="true"/> <browser src="http://www.mozilla.org" flex="1" showcaret="true"/> ...
showimagecolumn - Archive of obsolete content
There is no default styling of this image, but the class name returned by the results appears in the property list for the column. ...
showpopup - Archive of obsolete content
<< XUL Reference home showpopup Type: boolean Note: Applies to: Thunderbird, SeaMonkeyIf true, the popup will be shown. 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. The default value is true. ...
smoothscroll - Archive of obsolete content
<< XUL Reference home smoothscroll Type: boolean true initially enables smooth scrolling for the corresponding arrowscrollbox, false disables it. Currently, smooth scrolling supports horizontal arrowscrollboxes only. ...
sortActive - Archive of obsolete content
...
spellcheck - Archive of obsolete content
<< XUL Reference home spellcheck Type: boolean If true, spell checking is enabled by default for the text box; if false, spell checking is disabled by default. If not specified, this defaults to false The HTML The spellcheck attribute uses values of true or false (you cannot simply add the spellcheck attribute to a given element): <!-- spellcheck everything! --> <input type="text" spellcheck="true" /><br /> <textarea spellcheck="true"></textarea> <div contenteditable="true" spellcheck="true">I am some content</div> <!-- spellcheck nothing! --> <input type="text" spellcheck="false" /><br /> <textarea spellcheck="false"></textarea> <div contenteditable="true" spellcheck="false">I am some content</div> You can use spellcheck on INPUT, TEXTAREA, and contenteditable elements. ...
suppressonselect - Archive of obsolete content
...
tab.selected - Archive of obsolete content
See also selected ...
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
<< XUL Reference home autoFill Obsolete since Gecko 1.9.1 Type: boolean Note: Applies to: Thunderbird and SeaMonkeyIf set to true, the best match will be filled into the textbox as the user types. If false, the default, the value will not be filled in until the user selects an item. As of Gecko 1.9.1, this attribute is now always specified in lower case. ...
textbox.disableAutocomplete - Archive of obsolete content
You might use a script to change this attribute. ...
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. The default value is true, hiding the dropdown button. This attribute only works correctly in SeaMonkey 1.x; for Thunderbird and SeaMonkey 2.0 you should also set the enablehistory attribute; as of Gecko 2.0 this attribute is completely superseded by it. ...
textbox.forceComplete - Archive of obsolete content
<< XUL Reference home forceComplete Obsolete since Gecko 1.9.1 Type: boolean If true, the textbox will be filled in with the best match when it loses the focus. If false, it will only be filled in when the user selects an item. As of Gecko 1.9.1, this attribute is now always specified in lower case. ...
textbox.ignoreBlurWhileSearching - Archive of obsolete content
As of Gecko 1.9.1, this attribute is now always specified in lower case. ...
textbox.showCommentColumn - Archive of obsolete content
For the URL history, the comment column will contain the page titles associated with each URL. ...
textbox.tabScrolling - Archive of obsolete content
<< XUL Reference home tabScrolling Obsolete since Gecko 1.9.1 Type: boolean If true, the user may cycle through the results list by pressing the Tab key. 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. ...
textbox.type - Archive of obsolete content
to be configured, including decimalplaces, min, max, increment, wraparound, hidespinbuttons, and textbox.value. password A textbox that hides what is typed, used for entering passwords. search A textbox intended for searching. The command event will fire as the user modifies the value. A listener for the command event should update search results. If the searchbutton attribute is set to true, the command event is only fired if the user presses the search button or presses the Enter key. You may specify grey text to appear when the search box is empty using the emptytext attribute, and a timeout may be set for the command event using the timeout attribute (defaults to 500). timed This textbox will fire a command event after the user types characters and a certain time has passed...
timepicker.increment - Archive of obsolete content
...
titlebar - Archive of obsolete content
...
treecol.src - Archive of obsolete content
label. You cannot have both an image and a label displayed in the header. Set this to the URL of an image to appear on the tree column header. If this attribute is left out, no image appears and the label is used instead. The class treecol-image must be used on the treecol element for the image to appear. You should still specify a label for use in the column picker if ignoreincolumnpicker is not true and hidecolumnpicker is not true on the tree. See also src ...
unread - Archive of obsolete content
<< XUL Reference home unread Type: boolean This attribute is set to true if the tab is unread; that is, either it has not yet been selected during the current session, or has changed since the last time it was selected. This attribute is not present if the tab is not unread. See also selected ...
wait-cursor - Archive of obsolete content
Usually, you would only use this on the window element or other top-level elements. In order to revert to the normal cursor state call the method removeAttribute("wait-cursor") when the process effectively has ended otherwise the wait cursor might never disappear. ...
wraparound - Archive of obsolete content
<< XUL Reference home wraparound Type: boolean If true, the value of the number box will wrap around when the maximum or minimum value is exceeded. The minimum and maximum values must both not be infinity. ...
command - Archive of obsolete content
Archive › Mozilla › XUL › Events › command
view Read only WindowProxy document.defaultView (window of the document) detail Read only long (float) Unused; always zero. sourceEvent Read only Event The activation event that caused this command event to be generated. Currently only set when a command event is redirected though use of the command attribute. ctrlKey Read only boolean true if the control key was down when the event was fired. false otherwise. shiftKey Read only boolean true if the shift key was down when the event was fired. false otherwise. altKey Read only boolean true if the alt key was down when the event was fired. false otherwise. metaKey Read only boolean true if the meta key was down when the event was fired. ...
Accessing Files - Archive of obsolete content
a valid file reference even if the file 'sample.txt' does not yet exist. You can check if the file exists by using nsIFile.exists(). var file = IO.getFile("Profile", "sample.txt"); if (file.exists()) alert("The file is there!"); else alert("File not found!"); Here, the same file is retrieved and a further check is performed to see whether the file is present or not. The exists method returns true if the file is present and false if it is not. If the file does not exist, you may wish to create it. The File object has a nsIFile.create() method which may be used to create an empty file, or you can open a writing stream and write to the file. nsIScriptableIO.getFile() may only be used to retrieve files that are directly within one of the starting directories. To retrieve other files, you will...
Working With Directories - Archive of obsolete content
). See Creating Directories below for information about this. Note that nsIFile.append() modifies the file object, rather than returning a new one. Both files and directories are represented using the same kind of object so most of the functions available for nsIFile will work for both. You can check if the object refers to a directory or a file by using nsIFile.isDirectory(). This method returns true if a file object returned by nsIScriptableIO.getFile() refers to a directory, and false otherwise. There is also a corresponding nsIFile.isFile() method to check if an object refers to a file. In both cases, the method fails if the file or directory does not exist, so you should check first using nsIFile.exists(). var dir = IO.getFile("Desktop", "myfiles"); dir.append("pictures"); if (dir.exists(...
Getting File Information - Archive of obsolete content
; In this example, a Date object is created using the modification time of a file. You can change the modification time of a file by setting the lastModifiedTime (nsIFile.Attributes) attribute, or you can just write to the file, in which case the value will be adjusted automatically. File Permissions Several methods may be used to check for file permissions. The following four methods return true or false: nsIFile.isReadable() - returns true if the file can be read from. nsIFile.isWritable() - returns true if the file can be written to. nsIFile.isExecutable() - returns true if the file can be executed. nsIFile.isHidden() - returns true if the file is hidden. In this example, an exeception will occur if the file cannot be written to. if (!file.isWritable()) throw "File cannot be...
Reading from Files - Archive of obsolete content
rs below 256, if you expect to use the data as text. while(stream.available()) output += stream.readString(20); Although this can be a suitable means of reading binary data, usually you will want to retrieve the data with some additional methods that are more useful. 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. read8 will read a single byte and return it. The 8 in the method name indicates that 8 bits of data are being read. read16 will read two bytes from the stream and interpret them as an integer. This method will return the value as a number. read32 will read four bytes and return this as a single 32-bit integer. readFloat will read four bytes and interpret them as ...
Writing to Files - Archive of obsolete content
(). var stream = IO.newOutputStream(file, "binary"); This line will create and open a binary stream for a file. Once opened, you can write to the file using various writing methods. The following methods are available, all of which take one argument, which is the value to write: writeBoolean will write a boolean value to a stream. If the argument is false, 0 is written, and if the argument is true, 1 is written. Non-boolean values will be converted into booleans automatically. write8 will write a single byte. The 8 in the method name indicates that 8 bits of data are being written. If the supplied value is larger than 8 bits, only the lowest significant 8 bits are written. write16 will write two bytes to the stream. write32 will write four bytes. writeFloat will write a floating po...
Moving, Copying and Deleting Files - Archive of obsolete content
the same directory: file.moveTo(null, "hello.txt"); If the destination file already exists, nsIFile.moveTo() replaces the existing file. For this reason, you may wish to check if the file exists using nsIFile.exists() before moving the file. Deleting a File To delete a file, use nsIFile.remove(). This method takes one boolean argument which indicates whether to delete recursively or not. If true and the file object refers to a directory, the directory will be removed as well all files and subdirectories within it. If false, a directory will only be removed if it is empty. If the directory is not empty, an error will occur. For files, the argument is simply ignored. var file = IO.newFile("Home", "photo.jpg"); file.remove(false); This example removes the file called 'photo.jpg'. ...
How to implement a custom XUL query processor component - Archive of obsolete content
from the beginning of the name var name = aVar.toString().slice(1); return this._data[name]; }, // return an object instead of a string for convenient compari...
How to Quit a XUL Application - Archive of obsolete content
ta. eForceQuit will quit no matter what. ...
Introduction to XUL - Archive of obsolete content
unctions may be added in a fashion similar to HTML. There is no <head> section of a XUL file, so script is just mixed in with the other content, delimited by a script element in the HTML namespace. <html:script type="application/javascript"> // dialog initialization code function InitWindow() { var checkbox = document.getElementById("remember"); if (checkbox) checkbox.checked = true; } </html:script> JavaScript can be referenced as in HTML documents: as onClick handlers and the like. See individual widget documentation referenced at the index for a list of attributes accepting JavaScript values. JavaScript is most safely kept in a separate file and included in the XUL file <html:script language="javascript" src="our.js"/> or relegated to the contents of a CDATA secti...
List of commands - Archive of obsolete content
Also obtained from http://www.mozilla.org/unix/customizing.html ...
toggleHighlight - Archive of obsolete content
...
advance - Archive of obsolete content
Archive › Mozilla › XUL › Method › advance
<< XUL Reference home advance( pageID ) Return type: no return value Call this method to go to the next page. This is equivalent to pressing the Next button. The canAdvance property must be set to true for the page to be changed. The code in the onwizardnext attribute is called before the page is changed. The pageID argument allows you to specify the index of the page to which to jump. Supply null as the argument to go to the next page in the sequence. ...
advanceSelectedTab - Archive of obsolete content
...
checkAdjacentElement - Archive of obsolete content
If it is false, the previous radio button is selected. ...
contains - Archive of obsolete content
...
hasUserValue - Archive of obsolete content
...
insertItem - Archive of obsolete content
<< XUL Reference home insertItem( id, beforeNode, wrapper, beforePermanent ) Not in SeaMonkey 1.x Return type: element Add an item with the given id to the toolbar. The new item is added just before the item given by the second argument. If the second argument is null, but the beforePermanent argument is true, the item is added to the beginning of the toolbar before the first permanent item. Otherwise, if the beforePermanent argument is false, the new item is added to the end of the toolbar. The third argument can be used to wrap the new item in another element. Usually, the last argument will be null as it is mainly for the use of the customize dialog. The id should match an element in the toolbar's toolbarpalette. Some special ids may also be used to create special spacing it...
loadOneTab - Archive of obsolete content
turn type: tab element Opens a new tab that loads a page with the specified URL. The rest of the parameters are optional. This method works the same as addTab except for the loadInBackground parameter which allows you to choose whether to open the new tab in foreground or background. There's also no owner parameter as the owner tab is specified automatically. Parameters inBackground if true the tab will be loaded in the background, if false the tab will be the newly selected tab. And if null or not specified, this parameter will default to the browser.tabs.loadInBackground preference. Firefox 3.6 note The second form of this method was added in Firefox 3.6; it adds the relatedToCurrent parameter, and allows the parameters to be specified by name, in any order. ...
loadTabs - Archive of obsolete content
<< XUL Reference home loadTabs( uris, loadInBackground, replace ) loadTabs( uris, params ) Return type: no return value Loads a set of URIs, specified by the array uris, into tabs. If loadInBackground is true, the tabs are loaded in the background, and if replace is true, the currently displayed tabs are replaced with the specified URIs instead of adding new tabs. The properties of params are following: boolean inBackground boolean replace boolean allowThirdPartyFixup tab targetTab number newIndex object postDatas number userContextId ...
moveByOffset - Archive of obsolete content
<< XUL Reference home moveByOffset( offset , isSelecting, isSelectingRange) Return type: no return value If offset is positive, adjusts the focused item forward by that many items. If offset is negative, adjusts the focused item backward by that many items. If isSelecting is true, then the selection is also adjusted. If isSelectingRange is also true, then the new item is selected in addition to any currently selected items. If isSelectingRange is false, any existing selection is cleared. Items that are hidden are skipped. ...
openPopup - Archive of obsolete content
popup, the x and y arguments may be used to offset the popup from its anchored position by some number, measured in CSS pixels. An unanchored popup appears at the position specified by x and y, relative to the viewport of the document containing the popup node. In this case, the position and attributesOverride arguments are ignored. isContextMenu The isContextMenu argument should be true for context menus and false for all other types of popups. It affects menu item highlighting; that is, while a context menu is open, menus opened earlier do not highlight or execute their items. attributesOverride If the attributesOverride argument is true, the position attribute on the popup node overrides the position value argument. If attributesOverride is false, the attribute i...
removeAllNotifications - Archive of obsolete content
<< XUL Reference home removeAllNotifications( immediate ) Return type: no return value Remove all notifications. If immediate is true, the messages are removed immediately. If immediate is false, the notifications are removed using a slide transition. ...
removeTab - Archive of obsolete content
<< XUL Reference home removeTab( tabElement ) Return type: no return value Removes a specific tabbed page corresponding to the given tab element. If only one tab is displayed, this method does nothing (unless the preference browser.tabs.closeWindowWithLastTab is true, in which case the window containing the tab is closed). If browser.tabs.autoHide is true, the row of tabs will collapse if only one tab remains. ...
rewind - Archive of obsolete content
Archive › Mozilla › XUL › Method › rewind
<< XUL Reference home rewind() Return type: no return value Call this method to go back a page. It is equivalent to pressing the Back button. The canRewind property must be set to true for the page to be changed. The code in the onwizardback attribute is called before the page is changed. ...
stopEditing - Archive of obsolete content
<< XUL Reference home stopEditing( shouldaccept ) Return type: no return value Stops editing the cell currently being edited. If the shouldAccept parameter is true, the cell's label is changed to the edited value (the tree view's nsITreeView.setCellText() method is called to change the cell contents). Otherwise the cell label is reverted to the value it had prior to editing. ...
MenuButtons - Archive of obsolete content
the operation. We might want to extend this example to insert a list of the unsaved documents to the Save button menu so that each could be saved individually. You might want to set the first item in the example above as the default button, so it indicates to the user that the command is carried out when the main button is pressed. This can be done by setting the default attribute on the item to true. <menuitem label="Save This Document" default="true"/> See Indicating_the_Default_Item for more information about the default attribute. As with the 'menu' type, the 'menu-button' type may be applied to either the button or the toolbarbutton element. ...
MenuModification - Archive of obsolete content
ar newmenu = document.createElement("menu"); popup.appendChild(newmenu); newmenu.label = "New"; newmenu.appendItem("Document", "doc"); newmenu.appendItem("Image", "image"); } </script> The hasChildNodes method may be used to check if a node has any children. The first time the function is called, the hasChildNodes method will return false, however the second time, the method will return true as the items have already been added to the menu. Removing Items from a Menu To remove an item from the menu, use the removeItemAt method. It takes a single argument, the index of the item to remove. In this example, an item is appended to a menu, and then immediately removed again. menu.appendItem("Open", ""); menu.removeItemAt(menu.itemCount - 1); The itemCount property holds the number of...
hasUserValue - Archive of obsolete content
...
canGoBack - Archive of obsolete content
...
canGoForward - Archive of obsolete content
...
canRewind - Archive of obsolete content
<< XUL Reference canRewind Type: boolean This property is set to true if the user can press the Back button to go to the previous page. If this property is false, the user cannot navigate to the previous page. Set this property to true to indicate that the user can go back a page. Set to false to disallow moving to the previous page. This has the effect of enabling or disabling the Back button. ...
clickSelectsAll - Archive of obsolete content
...
colorpicker.open - Archive of obsolete content
<< XUL Reference open Type: boolean Returns true if the popup for a button-type colorpicker is open. Set this property to true to open the popup or false to close the popup. ...
disabled - Archive of obsolete content
<< XUL Reference disabled Type: boolean Gets and sets the value of the disabled attribute. <!-- Checkbox enables/disables the button --> <checkbox label="Enable button" oncommand="document.getElementById('buttRemove').disabled = ! this.checked"/> <button id="buttRemove" label="Remove All" disabled="true"/> ...
editable - Archive of obsolete content
<< XUL Reference editable Type: boolean Returns true if the element is editable. Autocomplete fields are editable so this property always returns true for those. ...
enableColumnDrag - Archive of obsolete content
...
instantApply - Archive of obsolete content
...
isPM - Archive of obsolete content
Archive › Mozilla › XUL › Property › isPM
...
isSearching - Archive of obsolete content
...
isWaiting - Archive of obsolete content
...
locked - Archive of obsolete content
This property is read-only. ...
menu.open - Archive of obsolete content
<< XUL Reference open Type: boolean This property will be set to true when the menu is open. The menu may be opened by setting the open property to true and closed by setting it to false. ...
noMatch - Archive of obsolete content
...
onFirstPage - Archive of obsolete content
...
onLastPage - Archive of obsolete content
...
readOnly - Archive of obsolete content
...
selected - Archive of obsolete content
This property is read only. ...
Providing Command-Line Options - Archive of obsolete content
mmandLineHandler */ handle : function clh_handle(cmdLine) { try { // CHANGEME: change "viewapp" to your command line flag that takes an argument var uristr = cmdLine.handleFlagWithParam("viewapp", false); if (uristr) { // convert uristr to an nsIURI var uri = cmdLine.resolveURI(uristr); openWindow(CHROME_URI, uri); cmdLine.preventDefault = true; } } catch (e) { Components.utils.reportError("incorrect parameter passed to -viewapp on the command line."); } // CHANGEME: change "myapp" to your command line flag (no argument) if (cmdLine.handleFlag("myapp", false)) { openWindow(CHROME_URI, null); cmdLine.preventDefault = true; } }, // CHANGEME: change the help info as appropriate, but /...
Building Trees - Archive of obsolete content
and value. The label attribute is used to set the label for a cell. The mode is used for progress meter columns. It may be set to either "normal" for a normal progress meter or "undetermined" for an undetermined progress meter. The value attribute is used to set the current progress value for normal progress meters. The value attribute may also be used for checkbox columns by setting it to either true or false. Whether a cell is a normal labeled value, a progress meter or a checkbox is determined by the type attribute on the column the cell is in. For cells in normal columns, you can use the value attribute to store some other value and you can use the view's getCellValue() method to retrieve it. Naturally, this will retrieve the value after any variables have been substituted. Besides the att...
RDF Modifications - Archive of obsolete content
anging the value. However, only one notification is made. For instance, an Assert call looks like the following: var source = RDF.GetResource("http://www.xulplanet.com/ndeakin/images/t/obelisk.jpg"); var predicate = RDF.GetResource("http://purl.org/dc/elements/1.1/description"); var target = RDF.GetLiteral("One of the thirty or so Egyptian obelisks"); datasource.Assert(source, predicate, target, true); The Assert call adds a new triple to the RDF datasource. When this happens, any templates observing the datasource will be notified via the RDF observer's onAssert method. The second situation when notifications are made is when a datasource is being loaded or reloaded. Actually, internally, this isn't any different than the other notifications, but it is worth discussing separately. When the ...
RDF Query Syntax - Archive of obsolete content
lplanet.com/rdf/B) (?start = http://www.xulplanet.com/rdf/A, ?relateditem = http://www.xulplanet.com/rdf/C) (?start = http://www.xulplanet.com/rdf/A, ?relateditem = http://www.xulplanet.com/rdf/D) You may note that the ?start variable is repeated for each result. This is because the builder copies the existing data for each new potential result and adds the new data. Internally, this isn't quite true; the builder actually maintains only one copy of the similar data but uses data structures in such a way which make it appear as if it were duplicated. You may find this a bit confusing, but this should become clearer later with more specific and practical examples. Since the triple was the last statement, the builder moves on to the content generation phase, creating matches out of the three pot...
Rule Compilation - Archive of obsolete content
different results. Once the template builder has compiled the rules, query processing and content generation can begin. The template builder generates content lazily, that is, it processes as little as needed, and only continues when necessary. For instance, consider the example below: <vbox datasources="http://www.xulplanet.com/ds/sample.rdf" ref="http://www.xulplanet.com/rdf/A" hidden="true"> <template> ... </template> </vbox> The <vbox> is hidden as indicated by the 'hidden' attribute. Since any content that would be generated wouldn't be displayed anyway, the template builder doesn't do anything, putting off work until later. If you show the vbox by setting the hidden state to false, the template builder will be invoked and the content will be generated. Does this mean th...
Sorting Results - Archive of obsolete content
d when the user changes the sort. The sortDirection attribute may be used to specify the initial sort direction for a column. Only one column should have this attribute set, as a tree may only be sorted by one column at a time. The value should be either 'ascending', 'descending' or 'natural'. This last value is the default if the attribute is not specified. The sortActive attribute may be set to true or false and specifies which column the tree is sorted by. Only one column should have the sortActive attribute set to true at a time. The tree will change both attributes as necessary automatically when the column headers are clicked or the tree is sorted by other means. If you don't want to allow sorting by a certain column, you can leave out the sort attribute. Only specify this attribute on c...
Static Content - Archive of obsolete content
Example Let's look at another example, involving radio buttons. Actually, this example is similar, it just uses a radiogroup instead of a menulist to display the list of countries. ...
Adding HTML Elements - Archive of obsolete content
ase. "Quotes" must be placed around all attribute values. XML requires a trailing slash at the end of tags that have no content. This may be clearer from the examples below. Using HTML elements You can use any HTML tag although some such as head and body are not really useful. Some examples of using HTML elements are shown below. <html:img src="banner.jpg"/> <html:input type="checkbox" value="true"/> <html:table> <html:tr> <html:td> A simple table </html:td> </html:tr> </html:table> These examples will create an image from the file banner.jpg, a checkbox and a single-cell table. You should always use XUL features if they are available and you probably should not use tables for layout in XUL. (There are XUL elements for doing layout). Notice that the prefix html: was add...
Adding Properties to XBL-defined Elements - Archive of obsolete content
ed, they are stripped off. If there are no digits, the value is not changed. This is done in the code inside the setter element. The real value of the property is stored in the number attribute. You can use either syntax for creating get and set handlers. Readonly Attribute You can make a field or property read-only by adding a readonly attribute to the field tag or property tag and setting it to true. Attempting to set the value of a read-only property will fail. Note: The readonly attribute did not work correctly on fields until Gecko 2.0. The next section shows how to add methods to XBL-defined elements. << PreviousNext >> ...
Adding Style Sheets - Archive of obsolete content
<spacer class="titlespace"/> <hbox> <progressmeter id="progmeter" value="50%" style="display:none;"/> The new xml-stylesheet line is used to import the style sheet. It will contain the styles instead of having them directly in the XUL file. You can include any number of style...
Advanced Rules - Archive of obsolete content
ble assigned in the child attribute of the member element. Complete Tree Example The following example shows a complete tree with conditions and an action. ...
Creating a Window - Archive of obsolete content
le-click the file in your file manager, assuming that XUL files are associated with Mozilla. The XUL window will appear in the browser window as opposed to a new window, but this is often sufficient during the early stages of development. Note: The local XUL document can be opened in the browser as mentioned above only if |dom.allow_XUL_XBL_for_file| preference in "about:config" has been set to |true| . If it does not exist, then it needs to be created and set to |true|. The correct way, of course, is to open the window using JavaScript. No new syntax is necessary as you can use the window.open() function as one can do for HTML documents. However, one additional flag, called 'chrome' is necessary to indicate to the browser that this is a chrome document to open. This will open the window wit...
More Event Handlers - Archive of obsolete content
Propagation method, as in the following example. Example 2 : Source View <hbox id="outerbox"> <button id="okbutton" label="OK"/> </hbox> <script> function buttonPressed(event){ alert('Button was pressed!'); } function boxPressed(event){ alert('Box was pressed!'); event.stopPropagation(); } var button = document.getElementById("okbutton"); button.addEventListener('command',buttonPressed,true); var outerbox = document.getElementById("outerbox"); outerbox.addEventListener('command',boxPressed,true); </script> Here, an event listener has been added to the button and another event listener has been added to the box. The stopPropagation method has been called in the box's listener, so the button's listener never gets called. If this call was removed, both listeners would be called and b...
Popup Menus - Archive of obsolete content
"/> Our find files example Let's add a simple popup menu to the find files dialog. For simplicity, we'll just replicate the contents of the Edit menu. Let's have the popup appear when clicking over the first tab panel: <popupset> <menupopup id="editpopup"> <menuitem label="Cut" accesskey="t"/> <menuitem label="Copy" accesskey="c"/> <menuitem label="Paste" accesskey="p" disabled="true"/> </menupopup> </popupset> <vbox flex="1"> . . . <tabpanel id="searchpanel" orient="vertical" context="editpopup"> Here a simple popup that is similar to the edit menu has been added to the first tabpanel. If you right-click (Control-click on the Macintosh) anywhere on the first panel, the popup will appear. However, the popup will not appear if you click anywhere else. Note that the textb...
Progress Meters - Archive of obsolete content
ing or how long the search will take. However, we'll add a normal one for now as an animating one can be distracting during development. The progress meter would normally only appear while the search is taking place. We'll add a script later to turn it on and off. <textbox id="find-text"/> <html:progress value="50" max="100" style="margin: 4px;"/> <button id="find-button" label="Find" default="true"/> The value has been set to 50% so that we can see the meter on the window. A margin has been set to 4 pixels so that it is separated from the edge of the window. As was stated earlier, we only want the progress bar to be displayed while the search was occurring. A script will show and hide it as necessary. To make this work you will first have to define the namespace html. Do this by adding ...
RDF Datasources - Archive of obsolete content
hat are hierarchical. Using RDF file Example The following is an example of how an RDF file can be used as a datasource. ...
Tabboxes - Archive of obsolete content
e user clicks on the Mail tab, the contents of the first tab page will be displayed below the tabs. In this case, the page with the check box labeled 'Automatically check for mail' will appear. When the second tab is clicked, the page containing the button labeled 'Clear News Buffer' will appear instead. The currently selected tab element is given an additional selected attribute which is set to true. This alters the appearance of the currently selected tab to make it look selected. Only one tab will have a true value for this attribute at a time. Position of the tabs Finally, you can change the position of the tabs so that they appear on any side of the tab pages. There is no special syntax to do this. You simply set the orient and dir attributes as necessary. Remember that the tab element...
Trees - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Trees
y make the columns flexible. You can also supply widths with the width attribute. You should include the same number of treecol elements as there are columns in the tree. Otherwise strange things might happen. The header row is created automatically. The button in the upper right corner can be used to hide and show the columns. You can place a hidecolumnpicker attribute on the tree and set it to true if you would like to hide this button. If this button is hidden, the user will not be able to hide columns. Make sure that you set an id attribute on each column or the hiding and showing of columns will not work in all versions of Mozilla. The treechildren element surrounds all of the rows. Inside the body are individual rows, which may in turn contain other rows. For a simpler tree, each row ...
XPCOM Examples - Archive of obsolete content
menu. This is done because getCookies() is called every time the menu is opened and we don't want to leave the old items there each time. Next, the cookie manager is retrieved. The cookie manager has an enumerator method which returns an object which implements nsISimpleEnumerator. This can be used to iterate over all of the cookies. An enumerator has a hasMoreElements() method which will return true until we get to the last cookie. The getNext() method gets a cookie and moves the enumerator index to the next cookie. Since an enumerator just returns a generic object, we need to QueryInterface() it to an nsICookie before we can use it. In this case, we just use the instanceof operator to accomplish this. Finally, an item is added to the menu for the cookie. The host, name and value properties ...
XUL Structure - Archive of obsolete content
ainder of the application session. This improves performance. However, because of this, the XUL will be not be reloaded even when the source files are changed. To disable this mechanism, it is necessary to change the preference nglayout.debug.disable_xul_cache. In Firefox, this preference may be added to the user preferences by typing "about:config" in the address field, and setting this value to true. Or, just manually edit your user.js preferences file and add the following line: pref("nglayout.debug.disable_xul_cache", true); There are usually three different parts to a chrome package, although they are all optional. Each part is stored in a different directory. These three sets are the content, the skin, and the locale, which are all described below. A particular package might provide o...
Using Remote XUL - Archive of obsolete content
However, there is a whitelist that lets you specify sites that can still use remote XUL. ...
Using spell checking in XUL - Archive of obsolete content
ll checking capabilities to your Firefox extension. See Controlling spell checking in HTML forms for details on adding spell check support to HTML forms for your website. Checking the spelling of a word To check the spelling of a word, you must first create an interface to the mozISpellCheckingEngine component and then call the check() method on the string you wish to test. This method returns true if the word is correctly spelled, or false if it's not. You may also want to check to see if the word is in the user's personal dictionary, since sometimes a word might be correctly spelled but in the dictionary. // Different versions of Firefox have different contract IDs var spellclass = "@mozilla.org/spellchecker/myspell;1"; if ("@mozilla.org/spellchecker/hunspell;1" in Components.classes) ...
XULBrowserWindow - Archive of obsolete content
ns and any other pages in the in content whitelist. You can augment the functionality of this method using chaining in order to hide chrome for other locations. See Hiding browser chrome for details and an example. boolean hideChromeForLocation( in String aLocation ); Parameters aLocation The URL to check to see if chrome should be hidden while that location is displayed. Return value true if chrome should be hidden while displaying the specified location; otherwise false. ...
The Implementation of the Application Object Model - Archive of obsolete content
rable solution for buttons that observe preferences (like the HOME button) Denoting persistence of local annotations to the AOM: The PERSISTENT attribute A content tree in XUL that wishes to allow persistent local annotations to be made to all the nodes in the subtree (including the node itself) must specify this capability using the persistent attribute. The persistent attribute has values of true and false, with true specifying that local annotations that are persistent are desired. The default assumption if this attribute is not present is that local annotations are not allowed. One subtree nested inside another subtree can specify a different value for the persistent attribute, thus allowing the XUL writer to specify a default for the whole window, but to still selectively override it f...
XUL Coding Style Guidelines - Archive of obsolete content
moved out of XUL. DTD declaration. predefined Entities. Other guidelines mentioned in XHTML 1.1 Recommendation. See details here. Making XUL localizable -- mandatory In the past, UI (display) related resource descriptions are stored in *.rc (for Windows client) or *.ad (for UNIX client) so that they can be localized for a specific language or culture. In the new world, Mozilla 5.0, this is not true any more. Most of the windows and dialogs in Mozilla will be described using XUL. To make XUL stream/file localizable, several guidelines are to be adopted to make the translation work easier and less error-prone. The issues are discussed in details here: What is localizable? Widget resources Content data Style info Layout geometry How to make them localizable? Localization Notes Localization...
XUL Event Propagation - Archive of obsolete content
enuitem itself is not displayed, since the root window element has used event capture to handle the event itself. In another example, an onload event handler for a XUL window can register a box element to capture all the click events that are raised from its child elements: var bbox = document.getElementById("bigbox"); if (bbox) bbox.addEventListener("click", function() { alert('captured'); }, true); ... <box id="bigbox"> <menu value="File"> <menupopup> <menuitem value="New" onclick="alert('not captured')" /> ... <menupopup> </menu> </box> Adding an Event Listener In order to take advantage of event capturing (or event bubbling with elements that do not already have event listeners), you must add an event listener to the element that wants to capture events ta...
autohide - Archive of obsolete content
When set to false, the default, the toolbar is visible. ...
clicktoscroll - Archive of obsolete content
<< XUL Reference home clicktoscroll Type: boolean If true, the up or down arrow(s) must be clicked to scroll the content. If false, the content will scroll automatically when the cursor hovers over either arrow. ...
commandset - Archive of obsolete content
he command updater is to update cut, copy, and paste menu items. More information is available in the XUL tutorial. Attributes commandupdater, events, oncommandupdate, targets Example <commandset> <command id="cmd_open" oncommand="alert('Open!');"/> <command id="cmd_help" oncommand="alert('Help!');"/> </commandset> Attributes commandupdater Type: boolean If true, the commandset is used for updating commands. Typically, this is used to update menu commands such as Undo and Cut based on when an event occurs. For example, since the Cut command is only valid when something is selected, a command updater might be used when the select event occurs. events Type: comma-separated list A comma-separated list of event names that the comman...
description - Archive of obsolete content
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
grid - Archive of obsolete content
Archive › Mozilla › XUL › grid
<groupbox> <caption label="Details"/> <grid> <columns> <column flex="1"/> <column flex="2"/> </columns> <rows> <row> <label value="User name"/> <textbox id="user"/> </row> <row> <label value="Group"/> <menulist> <menupopup> <menuitem label="Accounts"/> <menuitem label="Sales" selected="true"/> <menuitem label="Support"/> </menupopup> </menulist> </row> </rows> </grid> </groupbox> Attributes Inherited from XUL element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertb...
key - Archive of obsolete content
Archive › Mozilla › XUL › key
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
keyset - Archive of obsolete content
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
label - Archive of obsolete content
Archive › Mozilla › XUL › label
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
listcell - Archive of obsolete content
disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
listhead - Archive of obsolete content
s disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
listheader - Archive of obsolete content
s disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user actions, it cannot be focused, and the command event will not fire. In the case of form elements, it will not be submitted. 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 disabled attribute is allowed only for form controls. Using it with an anchor tag (an <a> link) will have no effect. The element will, however, still respond to mouse events. To enable the element, leave this attribute out entirely. Visible controls have a disabled property which, except...
menubar - Archive of obsolete content
on Windows), the menubar element needs to be placed inside a toolbox element. More information is available in the XUL tutorial. Attributes grippyhidden, statusbar Properties accessibleType, statusbar Examples <menubar id="sample-menubar"> <menu id="action-menu" label="Action"> <menupopup id="action-popup"> <menuitem label="New"/> <menuitem label="Save" disabled="true"/> <menuitem label="Close"/> <menuseparator/> <menuitem label="Quit"/> </menupopup> </menu> <menu id="edit-menu" label="Edit"> <menupopup id="edit-popup"> <menuitem label="Undo"/> <menuitem label="Redo"/> </menupopup> </menu> </menubar> Attributes grippyhidden SeaMonkey only Type: boolean When set to true, the grippy will be hidden. When ...
progressmeter - Archive of obsolete content
eforehand. More information is available in the XUL tutorial. 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) ? 'undetermined' : 'determined'; } Attributes max Type: integer The maximum value that progressmeter may have. The default value if not specified is 100 such that the value may be used as a percentage. mode Type: one of the ...
resizer - Archive of obsolete content
agging it. The resizer will send a command event after the resize is complete. Note: Starting in Gecko 2.0, you can also specify a target element using the element attribute, to use the resizer to resize the specified element instead of the window. ...
splitter - Archive of obsolete content
be used instead of changing the style of the element directly since they will fit more naturally with the user's selected theme. tree-splitter This splitter is intended to be used in tree columns (in-between treecol elements). The splitter will be drawn with no width so that it isn't visible, however, the columns may still be resized. ...
tabbox - Archive of obsolete content
Keyboard navigation is captured at the parent of the tabbox. window Keyboard navigation is captured at the window level. Tab navigation will occur as long as any element in the window is focused. document Keyboard navigation is captured at the document level. Tab navigation will occur as long as any element in the document is focused. handleCtrlTab Type: boolean If set to true or omitted, the tabbox will switch to the next tab when the Control and Tab keys are pressed. If the Shift key is also held down, the previous tab will be displayed. If this attribute is set to false, these keys do not navigate between tabs. Properties accessibleType Type: integer A value indicating the type of accessibility object for the element. eventNode Typ...
titlebar - Archive of obsolete content
r of normal windows; instead, it's used to create custom titlebars for chromeless windows. If the titlebar is in a panel element, dragging it will move the panel. Elements inside the titlebar usually don't receive any mouse events, so e.g. buttons inside it can't be clicked and textboxes can't be focused with the mouse. If you don't want this behavior, you can override it by setting allowevents="true" on the titlebar element. The titlebar will send a command event after the move is complete. Examples This XUL file will create a HUD-style window that can be moved with the mouse. It will close if the mouse button is released. <?xml version="1.0"?> <window title="Movable HUD Window" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" width="300" height="200"...
toolbaritem - Archive of obsolete content
element. The element is used, for example, to hold the location bar's textbox in Firefox. It is also used to group buttons together so they can be added and removed all at once like Firefox's unified-back-forward-button. ...
toolbox - Archive of obsolete content
w" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" title="toolbox example" width="300"> <toolbox> <toolbar> <toolbarbutton label="Back"/> <toolbarbutton label="Forward"/> <toolbarbutton label="Home"/> </toolbar> <toolbar> <toolbarbutton label="Stop"/> <toolbarbutton label="Reload"/> </toolbar> </toolbox> <textbox multiline="true" value="We have two toolbars inside of one toolbox above." width="20"/> </window> Attributes Inherited from XUL element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, ...
treechildren - Archive of obsolete content
| Properties | Methods | Related ] This element is the body of the tree. For content trees, the content will be placed inside this element. This element is also used to define container rows in the tree. More information is available in the XUL tutorial. Attributes alternatingbackground Attributes alternatingbackground Obsolete since Gecko 2.0 Type: boolean If true, the background of the tree's rows will alternate between two colors. You can use the :-moz-tree-row CSS style to do this instead. Inherited from XUL element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, m...
Building XULRunner with Python - Archive of obsolete content
jects/mozilla make -f client.mk which will also checkout client.mk itself For build only, without checkouts, use make -f client.mk build and see client.mk for other options. The built XULRunner can then be found asc:\projects\obj-xulrunner\dist\bin\xulrunner.exe. Using Python in XUL applications Add the following to yourprefs.js during development pref("browser.dom.window.dump.enabled", true); pref("javascript.options.showInConsole", true); pref("javascript.options.strict", true); pref("nglayout.debug.disable_xul_cache", true); pref("nglayout.debug.disable_xul_fastload", true); HTML <script> tags specify that Python is used withtype="application/x-python" attribute. DOM scripting is pretty much as with Java Script. For example def onLoad(): btnTest = document.getElementById("b...
Dialogs in XULRunner - Archive of obsolete content
tekeeper/there.is.only.xul" onload="window.sizeToContent();" buttons="accept,cancel" buttonlabelaccept="Set Favorite" buttonaccesskeyaccept="S" ondialogaccept="return doSave();" buttonlabelcancel="Cancel" buttonaccesskeycancel="n" ondialogcancel="return doCancel();"> <script> function doSave(){ //doSomething() return true; } function doCancel(){ return true; } </script> <dialogheader title="My dialog" description="Example dialog"/> <groupbox flex="1"> <caption label="Select favorite fruit"/> <radiogroup> <radio id="1" label="Oranges because they are fruity"/> <radio id="2" selected="true" label="Strawberries because of color"/> <radio id="3" label="Bananna becaus...
Using Crash Reporting in a XULRunner Application - Archive of obsolete content
XULRunner application authors who wish to use crash reporting must run a crash reporting server. Please see the Socorro project for more information. To enable crash reporting on the client, set the following items in application.ini: [Crash Reporter] Enabled=True ServerURL=https://your.server.url/submit Note: because crash reports can contain private data including passwords, in production environments they should only be sent via https. ...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
Client.CharSet + "\"", < beforeSend: function(req) { < req.setRequestHeader("Method", "POST"); < req.setRequestHeader("Content-Length", SOAPClient.ContentLength); < req.setRequestHeader("SOAPServer", SOAPClient.SOAPServer); < req.setRequestHeader("SOAPAction", soapReq.Action); < } < }); --- > var xhr = new XMLHttpRequest(); > xhr.mozBackgroundRequest = true; > xhr.open('POST', SOAPClient.Proxy, true); > xhr.onreadystatechange = function() { > if (4 != xhr.readyState) { return; } > getResponse(xhr); > }; > var headers = { > 'Method': 'POST', > 'Content-Type': SOAPClient.ContentType + '; charset="' + > SOAPClient.CharSet + '"', > 'Content-Length': SOAPClient.ContentLength, > 'SOAPServer': SOAPClient.SOAPServer,...
xulauncher - Archive of obsolete content
me.manifest file ############################################################################## echo " content $XULNAME file:$XULNAME/ ">$XULMANIFEST # create prefs.js file ############################################################################## echo " pref(\"toolkit.defaultChromeURI\", \"chrome://$XULNAME/content/$XULFILE\"); /* debugging prefs */ pref(\"browser.dom.window.dump.enabled\", true); pref(\"javascript.options.showInConsole\", true); pref(\"javascript.options.strict\", true); pref(\"nglayout.debug.disable_xul_cache\", true); pref(\"nglayout.debug.disable_xul_fastload\", true); ">$XULPREFS # copy xul file to right location and run it ############################################################################## cp $XULFILE $XULDIR xulrunner $XULAPPINI $@ ...
Mozprofile - Archive of obsolete content
Setting Permissions mozprofile also takes care of adding permissions to the profile. See https://github.com/mozilla/mozbase/b...permissions.py Resources Other Mozilla programs offer additional and overlapping functionality for profiles. There is also substantive documentation on profiles and their management. ProfileManager : XULRunner application for managing profiles. Has ...
nsIContentPolicy - Archive of obsolete content
Note: Before you can recieve notifications, you must register your plugin with nsICategoryManager. See example below. char* previous = nsnull; nsCOMPtr<nsICategoryManager> catman; servman->GetServiceByContractID(NS_CATEGORYMANAGER_CONTRACTID, NS_GET_IID(nsICategoryManager), getter_AddRefs(catman)); rv = catman->AddCategoryEntry("content-policy", COMPONENT_CLASSNAME, COMPONENT_CONTRACTID, PR_TRUE, PR_TRUE, &previous); JavaScript developers can also implement an XPCOM component that extends nsIContentPolicy. ...
NPN_Enumerate - Archive of obsolete content
ng parameters: npp The NPP indicating which plugin instance is making the request. npobj The object of which the properties and methods are to be retrieved. identifiers A pointer to receive a pointer to the start of an array of string identifiers of the names of the properties and methods of npobj. identifierCount A pointer to receive the number of identifiers in identifiers. Returns true if the names of the properties and methods were successfully retrieved, otherwise false. Note: The caller must call NPN_MemFree() on the pointer received through the identifiers parameter of a successful call to NPN_Enumerate to release the array of string identifiers when it is no longer needed. The callee allocates this array via NPN_MemAlloc(). ...
NPN_Evaluate - Archive of obsolete content
ct *npobj, NPString *script, NPVariant *result); Parameters The function has the following parameters: npp The NPP indicating which plugin instance's window to evaluate the script in. npobj The scope object. script The script to evaluate. result On return, contains the value returned by the script. Can't be NULL. Returns true if the script was evaluated successfully, otherwise false. Description The script is evaluated in the context of the window that the calling plugin instance (the <tt>npp</tt> argument) is loaded in. Note: The caller must call NPN_ReleaseVariantValue() to release the returned value when it's no longer needed. ...
NPN_GetProperty - Archive of obsolete content
esult); Parameters The function has the following parameters: <tt>npp</tt> The NPP indicating which plugin instance's is making the request. <tt>npobj</tt> The object from which a value is to be retrieved. <tt>propertyName</tt> A string identifier indicating the name of the property whose value is to be retrieved. <tt>result</tt> On return, contains the value of the specified property. Returns true if the value was retrieved successfully, otherwise false. Note: The caller must call NPN_ReleaseVariantValue() to release the returned value when it's no longer needed. ...
NPN_GetValue - Archive of obsolete content
nt Display NPNVxtAppContext: Unix only: Returns the application's XtAppContext NPNVnetscapeWindow: MS Windows and Unix/X11 only: MS Windows: Gets the native window on which plug-in drawing occurs; returns HWND Unix/X11: Gets the browser toplevel window in which the plug-in is displayed; returns Window NPNVjavascriptEnabledBool: Tells whether JavaScript 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 Get...
NPN_HasMethod - Archive of obsolete content
ied NPObject has a particular method. Syntax #include <npruntime.h> bool NPN_HasMethod(NPP npp, NPObject *npobj, NPIdentifier methodName); Parameters The function has the following parameters: npp The NPP indicating which plugin instance is making the request. npobj The object on which to look for the method. methodName A string identifier indicating the name of the method to look for. Returns true if the method exists on the specified object, otherwise false. ...
NPN_HasProperty - Archive of obsolete content
...
NPN_IdentifierIsString - Archive of obsolete content
...
NPN_PostURLNotify - Archive of obsolete content
g-in instance, specified by the plug-in. url URL of the POST request, specified by the plug-in. target Target window, specified by the plug-in. For values, see NPN_GetURL. len Length of the buffer buf. buf Path to local temporary file or data buffer that contains the data to post. file Whether to post a file. Values: true: Post the local file whose path is specified in buf, then delete the file. false: Post the raw data in buf. notifydata Plug-in-private value for associating the request with the subsequent NPP_URLNotify call, which returns this value (see Description below). Returns If successful, the function returns NPERR_NO_ERROR. If unsuccessful, the plug-in is not loaded and...
NPN_ReloadPlugins - Archive of obsolete content
Description NPN_ReloadPlugins() reads the Plugins directory for the current platform and reinstalls all of the plug-ins it finds there. ...
NPN_RemoveProperty - Archive of obsolete content
ect. Syntax #include <npruntime.h> bool NPN_RemoveProperty(NPP npp, NPObject *npobj, NPIdentifier propertyName); Parameters The function has the following parameters: npp The NPP indicating which plugin instance is making the request. npobj The object on which a property is to be deleted. propertyName A string identifier indicating the name of the property to remove. Returns true if the property was removed successfully, otherwise false. ...
NPN_SetProperty - Archive of obsolete content
...
NPP_HandleEvent - Archive of obsolete content
e Pointer to the current plug-in instance. event Platform-specific value representing the event handled by the function. Values: MS Windows: Pointer to NPEvent structure Mac OS: Pointer to a standard Mac OS EventRecord Unix/X11: Pointer to a standard Xlib XEvent For a list of possible events, see NPEvent. Returns If the plug-in handles the event, the function should return true. If the plug-in ignores the event, the function returns false. Description The browser calls NPP_HandleEvent to tell the plug-in when events take place in the plug-in's window or drawable area. The plug-in either handles or ignores the event, depending on the value given in the event parameter of this function. For a list of event types the application is responsible for delivering to the plu...
NPP_NewStream - Archive of obsolete content
NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype); Parameters The function has the following parameters: instance Pointer to current plug-in instance. type Pointer to MIME type of the stream. stream Pointer to new stream. seekable Boolean indicating whether the stream is seekable: true: Seekable. Stream supports random access through calls to NPN_RequestRead (for example, local files or HTTP servers that support byte-range requests). false: Not seekable. The browser must copy data in the stream to the local cache to satisfy random access requests made through NPN_RequestRead. stype Out parameter. The plugin should set this value to request a mode for the stream. For ...
Adobe Flash - Archive of obsolete content
function myFlash_DoFSCommand(command, args) { // handle any callback logic that you may have designed into your Flash plugin // the Flash animation will supply you with the values for command and args // This is a function that handles...
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
Every add-on must have a unique id. This can be in a guid form but the simpler email form is preferred now. You should aim to use a domain-name that you own and then your own unique short-name for the plugin before the @. The plugin must have a name to identify the plugin to the user in the list of add-ons. T...
Introduction to Public-Key Cryptography - Archive of obsolete content
sumes that the client has a valid certificate that can be used to identify the client to the server. Certficate-based authentication is generally considered preferable to password-based authentication because it is based on what the user has (the private key) as well as what the user knows (the password that protects the private key). However, it's important to note that these two assumptions are true only if unauthorized personnel have not gained access to the user's machine or password, the password for the client software's private key database has been set, and the software is set up to request the password at reasonable frequent intervals. Neither password-based authentication nor certificate-based authentication address security issues related to physical access to individual machines o...
Theme changes in Firefox 3.5 - Archive of obsolete content
This attribute can be used to style different parts of the browser window inside the Private Browsing mode. See this blog post for an example. Supporting 3.5 Features Video/Audio player: controlBar has to be styled (chrome://global/skin/media/videocontrols.css) Shadow effect for disabled text using text-shadow. Greying menus of inactive windows: active windows get attribute 'active="true"'. To do this only for 3.5 use a CSS selector that is only supported in 3.5, like so: window:not([active="true"]) menubar>menu:nth-child(1n) { color:threedshadow } Private browsing: show private browsing state by coloring the URL bar, or by adding an icon to the toolbox/tabbrowserbar. See Private browsing for theme designers for details. Native hyperlink color: use -moz-nativehyperlinktext, to...
Settings - Archive of obsolete content
this option adds a "Filter variables" search box to the variables pane, so that you can filter the displayed list of variables. Show Original Sources Enabling this option will make the debugger use source maps, if they are available, to display the original source for code which has been combined, minified, or even compiled to JavaScript from a language like CoffeeScript. Defaults to true. Automatically Black Box Minified Sources New in Firefox 33. Automatically black box sources whose URL ends with ".min.js". Defaults to true. ...
Using workers in extensions - Archive of obsolete content
It starts by setting up an interval handler (in lines...
Introduction - Archive of obsolete content
for JavaScript programmers to manipulate an XML document, without going through the DOM interfaces. However, many of the same functions that you would use in the DOM can be used in E4X. The most basic is appendChild var element1 = <foo/>; var element2 = <bar/>; element1.appendChild(element2); which produces exactly the XML document you'd expect <foo> <bar/> </foo> Javascript Variables The true power of E4X only begins to come to light, however, when the XML document can interact closely with other JavaScript. With special syntax, we can assign the value of a JavaScript variable to be the value of an E4X element. This is done with brace ({}) notation. var a = 2; var b = <foo>{a}</foo>; creates an XML document that reads <foo>2</foo>. You can also use brace notation on attributes of e...
Iterator - Archive of obsolete content
name, value] in Iterator(a)) { console.log(name, value); // x 10 // y 20 } Iterating with for-of var a = { x: 10, y: 20, }; for (var [name, value] of Iterator(a)) { // @@iterator is used console.log(name, value); // x 10 // y 20 } Iterates over property name var a = { x: 10, y: 20, }; for (var name in Iterator(a, true)) { console.log(name); // x // y } Passing Generator instance function* f() { yield 'a'; yield 'b'; } var g = f(); console.log(g == Iterator(g)); // true for (var v in Iterator(g)) { console.log(v); // a // b } Passing Iterator instance var a = { x: 10, y: 20, }; var i = Iterator(a); console.log(i == Iterator(i)); // true Spec...
Expression closures - Archive of obsolete content
JavaScript 1.7 and older: function(x) { return x * x; } JavaScript 1.8: function(x) x * x This syntax allows you to leave off the braces and 'return' statement - making them implicit. There is no added benefit to writing code in this manner, other than having it be syntactically shorter. Examples A shorthand for binding event listeners: document.addEventListener('click', function() false, true); Using this notation with some of the array functions from JavaScript 1.6: elems.some(function(elem) elem.type == 'text'); ...
Function.prototype.isGenerator() - Archive of obsolete content
...
ActiveXObject - Archive of obsolete content
orksheet). Once an object is created, you refer to it in code using the object variable you defined. In the following example, you access properties and methods of the new object using the object variable ExcelSheet and other Excel objects, including the application object and the ActiveSheet.Cells collection. // Make Excel visible through the Application object. ExcelSheet.Application.Visible = true; // Place some text in the first cell of the sheet. ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1"; // Save the sheet. ExcelSheet.SaveAs("C:\\TEST.XLS"); // Close Excel with the Quit method on the Application object. ExcelSheet.Application.Quit(); Requirements Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, I...
Debug.msTraceAsyncCallbackStarting - Archive of obsolete content
g.MS_ASYNC_OP_STATUS_SUCCESS); Debug.msTraceAsyncCallbackStarting(opID); // Process result of async operation. }, function (error) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATUS_ERROR); Debug.msTraceAsyncCallbackStarting(opID); }); Debug.msTraceAsyncCallbackCompleted(); } function doSomethingAsync() { return WinJS.Promise.as(true); } asyncWrapperFunction(); Requirements Supported in the Internet Explorer 11 standards document mode. Also supported in Store apps (Windows 8.1 and Windows Phone 8.1). Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards. Not supported...
Debug.msTraceAsyncCallbackCompleted - Archive of obsolete content
g.MS_ASYNC_OP_STATUS_SUCCESS); Debug.msTraceAsyncCallbackStarting(opID); // Process result of async operation. }, function (error) { Debug.msTraceAsyncOperationCompleted(opID, Debug.MS_ASYNC_OP_STATUS_ERROR); Debug.msTraceAsyncCallbackStarting(opID); }); Debug.msTraceAsyncCallbackCompleted(); } function doSomethingAsync() { return WinJS.Promise.as(true); } asyncWrapperFunction(); Requirements Supported in the Internet Explorer 11 standards document mode. Also supported in Store apps (Windows 8.1 and Windows Phone 8.1). Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards. Not supported...
Enumerator.atEnd - Archive of obsolete content
Non-standard. Do not use! This object is a Microsoft extension and is only supported in Internet Explorer. The Enumerator.atEnd method returns a Boolean value indicating if the enumerator is at the end of the collection. Syntax myEnum.atEnd() Remarks The required myEnum reference is any Enumerator object. The atEnd method returns true if the current item is the last one in the collection, the collection is empty, or the current item is undefined. Otherwise, it returns false. Example In following code, the atEnd method is used to determine if the end of a list of drives has been reached: function ShowDrives() { var s = ""; var bytesPerGB = 1024 * 1024 * 1024; var fso = new ActiveXObject("Scripting.FileSystemObject"); var e = new Enumerator(fso.Drives); e.moveFi...
@if - Archive of obsolete content
Windows 8.x Store apps. Conditional compilation is supported in Internet Explorer 10 Standards mode and in all earlier versions. The @if statement conditionally executes a group of statements, depending on the value of an expression. Syntax @if ( condition1 ) text1 [@elif ( condition2 ) text2] [@else text3] @end Parameters text1 Optional Text to be parsed if condition1 is true. text2 Optional Text to be parsed if condition1 is false and condition2 is true. text3 Optional Text to be parsed if both condition1 and condition2 are false. Remarks When you write an @if statement, you do not have to place each clause on a separate line. You can use multiple @elif clauses. However, all @elif clauses must come before an @elseclause. The @if statement is typically used to...
New in JavaScript 1.8.5 - Archive of obsolete content
that, when called, itself calls this function in the context provided (with a given sequence of arguments). bug 429507 New ECMAScript5 features get and set operators now allows the identifier to be numeric or a string. bug 520696 Function.apply() can accept any array-like object as the arguments list, instead of only true arrays. strict mode support Array.toString() now works even on non-arrays by either returning the result of calling its join() method if one is available or by calling its toString() method. Other standardization work Various non-standard syntaxes for defining getters and setters have been removed; ECMAScript 5 defined syntax has not been ...
Number.toInteger() - Archive of obsolete content
Syntax Number.toInteger(number) Parameters number The value to be converted to an integer. ...
Object.prototype.unwatch() - Archive of obsolete content
You can usually use setters and getters or proxies instead. The unwatch() method removes a watchpoint set with the watch() method. ...
Object.prototype.watch() - Archive of obsolete content
You can usually use setters and getters or proxies instead. The watch() method watches for a property to be assigned a value and runs a function when that occurs. ...
JavaObject - Archive of obsolete content
java.lang.String("Hello, world"); Example: Accessing methods of a Java object Because the JavaObject theString is an instance of java.lang.String, it inherits all the public methods of java.lang.String. The following example uses the startsWith method to check whether theString begins with "Hello". var theString = new java.lang.String("Hello, world"); theString.startsWith("Hello"); // returns true Example: Accessing inherited methods Because getClass is a method of Object, and java.lang.String extends Object, the String class inherits the getClass method. Consequently, getClass is also a method of the JavaObject which instantiates String in JavaScript. var theString = new java.lang.String("Hello, world"); theString.getClass(); // returns java.lang.String See also JavaArray, JavaClas...
Packages - Archive of obsolete content
n: Any class in the Java package sun.*. Examples Example: JavaScript function to create a Java dialog box The following JavaScript function creates a Java dialog box: function createWindow() { var theOwner = new Packages.java.awt.Frame(); var theWindow = new Packages.java.awt.Dialog(theOwner); theWindow.setSize(350, 200); theWindow.setTitle("Hello, World"); theWindow.setVisible(true); } In the previous example, the function instantiates theWindow as a new Packages object. The setSize, setTitle, and setVisible methods are all available to JavaScript as public methods of java.awt.Dialog. ...
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
h Cam page while giving it a nice new CSS-driven look. I hope that our little cruise through this aspect of the redesign has gotten you hooked on the idea of using simple markup and CSS to create interesting effects, if you weren't already. With just the few elements I had available in this example, there were any number of possibilities for design effects, and I think you'll find the same to be true for your own designs if you just give this sort of approach a try. - FIN. - Related Links The Amazing Netscape Fish Cam Page Original Document Information Author(s): Eric Meyer, Standards Evangelist, Netscape Communications Last Updated Date: Published 25 Apr 2003 Copyright Information: Copyright (C) 2001-2003 Netscape. All rights reserved. Note: This reprinted article was originall...
XForms Range Element - Archive of obsolete content
...
XForms Secret Element - Archive of obsolete content
se64Binary, xsd:hexBinray or any data type derived from these. Representations The XForms secret element is represented by a password field. The password field is a text field, the value of which is hidden by asterisks (xhtml/xul). Characteristics analogous widgets are <xhtml:input type="password"/> and <xul:textbox type="password"/> if the incremental attribute is present and has the value true, then the bound instance node is updated on every user input. Please keep in mind that the instance data will hold exactly what the user gave as input. Any other XForm control bound to that data will show that data 'as is'. ...
XForms Select1 Element - Archive of obsolete content
cesskey - used to specify the keyboard shortcut for focusing this control. Single-Node Binding Special selection - this attribute, when set to 'open', allows the user to provide free entry to the list. Possible values are open and closed, default is closed (see #Representations section to refer if the attribute is supported for every representation). incremental - supported, default value is true Properties selection - see corresponding attribute incremental - see corresponding attribute Type restrictions The select1 element can be bound to a node containing simple content. The data binding restriction to simple content may be relaxed when an itemset element is used, which allows the available choices to be obtained from an XForms Model. The relaxation happens when the itemset el...
XForms Textarea Element - Archive of obsolete content
ing Special inputmode - isn't supported. incremental - supported. The default value is false. Type restrictions The textarea element can be bound to a node of type xsd:string or any type derived from it. Representations The XForms textarea element is represented by a multiline text field (xhtml/xul). Characteristics analogous widgets are <xhtml:textarea/> and <xul:textbox multiline="true"/> if the incremental attribute has the value true, then the bound instance node is updated on every user input. ...
Displaying a graphic with audio samples - Archive of obsolete content
The following example shows how to take samples from an audio stream and display them behind an image (in this case, the Mozilla logo), giving the impression that the image is built from the samples. ...
Parsing microformats in JavaScript - Archive of obsolete content
a string in which all occurrences of a in the HTML are replaced with b. string = html.match(a); Performs the specified matching operation on the HTML and returns the result. iso8601FromDate Converts a JavaScript date object into an ISO 8601 formatted date. isoDate = Microformats.parser.iso8601FromDate(date, punctuation) Parameters date The JavaScript Date object to convert. punctuation true if the date should have "-" and "/" in it. Return value A string containing the ISO 8601 formatted date. textGetter() Retrieves all the text from a particular DOM node, including all tags. This calls defaultGetter() internally. text = Microformats.parser.textGetter(propnode, parentnode); Parameters propnode The DOM node to check. parentnode The property's parent ...
The Business Benefits of Web Standards - Archive of obsolete content
forms - for example mobile telephones. Feed content such as RSS and Atom simply will not work without being implemented by following the requisite standard. Assumptions about the user and their platform based on erroneous thinking about the anticipated user community are inevitably always wrong. It does not follow for example that successful business users have wide monitors. The opposite may be true. Power users and business travellers are downsizing their notebooks. Increasingly one person may need to acccess the same site using different platforms at home, in the office and when travelling. They expect a consistent experience. Web Standards gives us tools, and methodologies for dealing with this paradox and making the wider contribution of making our content universally accessible to peop...
Building up a basic demo with A-Frame - Game development
f you have the necesary VR hardware set up and ready. Specifying a camera A camera entity can be created by adding an <a-camera> element to the scene. We can set the position of the camera explicitly and move it back a little bit from the center of the scene, so we'll be able to see the shapes. Add this just before the closing </a-scene> element: <a-camera position="0 1 4" cursor-visible="true" cursor-scale="2" cursor-color="#0095DD" cursor-opacity="0.5"> </a-camera> We've also defined a cursor for the given camera, using the cursor-* attributes (by default it is invisible.) -- we've set its scale so it will more easily visible, its color, and some opacity so it won't completely covering the objects behind it. Adding lights The basic light types in A-Frame are directional and...
Building up a basic demo with Three.js - Game development
Canvas, SVG, CSS, and DOM. They differ in how everything is rendered, so the WebGL implementation will implement differently than the CSS one. Despite the variety of ways they achieve the goal, the experience will look the same for the user. Thanks to this approach, a fallback can be used, if a desired technology is not supported by the browser. var renderer = new THREE.WebGLRenderer({antialias:true}); renderer.setSize(WIDTH, HEIGHT); renderer.setClearColor(0xDDDDDD, 1); document.body.appendChild(renderer.domElement); We are creating a new WebGL renderer, setting its size to fit the whole available space on the screen, and appending the DOM structure to the page. You might have noticed the antialias parameter in the first line -- this renders the edges of shapes more smoothly. The setClear...
GLSL Shaders - Game development
sition = projectionMatrix * modelViewMatrix * vec4(position.x+10.0, position.y, position.z+5.0, 1.0); } </script> <script id="fragmentShader" type="x-shader/x-fragment"> void main() { gl_FragColor = vec4(0.0, 0.58, 0.86, 1.0); } </script> JavaScript var WIDTH = window.innerWidth; var HEIGHT = window.innerHeight; var renderer = new THREE.WebGLRenderer({antialias:true}); renderer.setSize(WIDTH, HEIGHT); renderer.setClearColor(0xDDDDDD, 1); document.body.appendChild(renderer.domElement); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(70, WIDTH/HEIGHT); camera.position.z = 50; scene.add(camera); var boxGeometry = new THREE.BoxGeometry(10, 10, 10); var shaderMaterial = new THREE.ShaderMaterial( { ...
Mobile touch controls - Game development
rform more complicated actions, but in this game touching the right side of the screen will simply fire the bullets to the right -- this is all we need in this case. Moving the player could be managed by creating the four directional buttons, but we can take the advantage of touch screens and drag the player's ship around: var player = this.game.add.sprite(30, 30, 'ship'); player.inputEnabled = true; player.input.enableDrag(); player.events.onDragStart.add(onDragStart, this); player.events.onDragStop.add(onDragStop, this); function onDragStart(sprite, pointer) { // do something when dragging } We can pull the ship around and do something in the meantime, and react when the drag is stopped. Hauling in Phaser, if enabled, will work out of the box -- you don't have to set the position of ...
Bounce off the walls - Game development
e Canvas (remember that we count the y values from the top left, so the top edge starts at 0 and the bottom edge is at 320 pixels, the Canvas' height), then bounce it off the bottom edge by reversing the y axis movement as before. We could merge those two statements into one to save on code verbosity: if(y + dy > canvas.height || y + dy < 0) { dy = -dy; } If either of the two statements is true, reverse the movement of the ball. Bouncing off the left and right We have the top and bottom edge covered, so let's think about the left and right ones. It is very similar actually, all you have to do is to repeat the statements for x instead of y: if(x + dx > canvas.width || x + dx < 0) { dx = -dx; } if(y + dy > canvas.height || y + dy < 0) { dy = -dy; } At this point you should in...
Collision detection - Game development
ionDetection() { for(var c=0; c<brickColumnCount; c++) { for(var r=0; r<brickRowCount; r++) { var b = bricks[c][r]; // calculations } } } If the center of the ball is inside the coordinates of one of our bricks, we'll change the direction of the ball. For the center of the ball to be inside the brick, all four of the following statements need to be true: The x position of the ball is greater than the x position of the brick. The x position of the ball is less than the x position of the brick plus its width. The y position of the ball is greater than the y position of the brick. The y position of the ball is less than the y position of the brick plus its height. Let's write that down in code: function collisionDetection() { for(var c...
Create the Canvas and draw on it - Game development
ctx.closePath(); As you can see we're using the beginPath() and closePath() methods again. Between them, the most important part of the code above is the arc() method. 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. The fillStyle property looks different than before. This is because, just as with CSS, color can be specified as a hexadecimal value, a color keyword, the rgba() function, or any of the other available color methods. Instead of using fill() and filling the shapes with colors, we can use stroke() to only colour the outer stroke. Try adding t...
Animations and tweens - Game development
ype of easing to use for the tween. We will also add the optional onComplete event handler, which defines a function to be executed when the tween finishes. The last thing do to is to start the tween right away using start(). That's the expanded version of the tween definition, but we can also use the shorthand syntax: game.add.tween(brick.scale).to({x:2,y:2}, 500, Phaser.Easing.Elastic.Out, true, 100); This tween will double the brick's scale in half a second using Elastic easing, will start automatically, and have a delay of 100 miliseconds. Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: Next steps Animations and tweens look very nice, but we can add even more to our game -- in the nex...
Bounce off the walls - Game development
off the world boundaries The easiest way to get our ball bouncing off the walls is to tell the framework that we want to treat the boundaries of the <canvas> element as walls and not let the ball move past them. In Phaser this can be easily accomplished using the collideWorldsBound property. Add this line right after the existing game.physics.enable() method call: ball.body.collideWorldBounds = true; Now the ball will stop at the edge of the screen instead of disappearing, but it doesn't bounce. To make this occur we have to set its bounciness. Add the following line below the previous one: ball.body.bounce.set(1); Try reloading index.html again -- now you should see the ball bouncing off all the walls and moving inside the canvas area. Compare your code You can check the finished cod...
Buttons - Game development
execution context The frames that will be used for the over, out and down events. Note: The over event is the same as hover, out is when the pointer moves out of the button and down is when the button is pressed. Now we need to define the startGame() function referenced in the code above: function startGame() { startButton.destroy(); ball.body.velocity.set(150, -150); playing = true; } When the button is pressed, we remove the button, sets the ball's initial velocity and set the playing variable to true. Finally for this section, go back into your create() function, find the ball.body.velocity.set(150, -150); line, and remove it. You only want the ball to move when the button is pressed, not before! Keeping the paddle still before the game starts It works as expected, b...
Extra lives - Game development
ndler (shown above) and replace it with the following line: ball.events.onOutOfBounds.add(ballLeaveScreen, this); We want to decrease the number of lives every time the ball leaves the canvas. ...
Game over - Game development
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. We need a way to detect this and act accordingly. Add the following lines just below the previous new one: ball.checkWorldBounds = true; ball.events.onOutOfBounds.add(function(){ alert('Game over!'); location.reload(); }, this); Adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onOutOfBounds event. When you click on the resulting alert, the page will be reloaded so you can play again. Compare your code You can check the finished code for this lesson...
Player paddle and controls - Game development
paddle. This works, but not quite as we expected it to -- when the ball hits the paddle, the paddle falls off the screen! All we want is the ball bouncing off the paddle and the paddle staying in the same place. We can set the body of the paddle to be immovable, so it won't move when the ball hits it. To do this, add the below line at the bottom of the create() function: paddle.body.immovable = true; Now it works as expected. Controlling the paddle The next problem is that we can't move the paddle. To do that we can use the system's default input (mouse or touch, depending on platform) and set the paddle position to where the input position is. Add the following new line to the update() function, as shown: function update() { game.physics.arcade.collide(ball, paddle); paddle.x =...
Scaling - Game development
on any screen size automatically during the preload stage, so we don't have to worry about it later. The Phaser scale object There's a special scale object available in Phaser with a few handy methods and properties available. Update your existing preload() function as follows: function preload() { game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; game.scale.pageAlignHorizontally = true; game.scale.pageAlignVertically = true; } scaleMode has a few different options available for how the Canvas can be scaled: NO_SCALE -- nothing is scaled. EXACT_FIT -- scale the canvas to fill all the available space both vertically and horizontally, without preserving the aspect ratio. SHOW_ALL -- scales the canvas, but keeps the aspect ratio untouched, so images won't be skewed like ...
Win the game - Game development
ting winning in our game is quite easy: if you happen to destroy all the bricks, then you win. How to win? Add the following new code into your ballHitBrick() function: function ballHitBrick(ball, brick) { brick.kill(); score += 10; scoreText.setText('Points: '+score); var count_alive = 0; for (i = 0; i < bricks.children.length; i++) { if (bricks.children[i].alive == true) { count_alive++; } } if (count_alive == 0) { alert('You won the game, congratulations!'); location.reload(); } } We loop through the bricks in the group using bricks.children, checking for the aliveness of each with each brick's .alive() method. If there are no more bricks left alive, then we show a winning message, restarting the game once the alert is di...
Block (scripting) - MDN Web Docs Glossary: Definitions of Web-related terms
In JavaScript, a block is a collection of related statements enclosed in braces ("{}"). 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. Learn more Learn about it JavaScript block statement ...
Block - MDN Web Docs Glossary: Definitions of Web-related terms
...
CORS - MDN Web Docs Glossary: Definitions of Web-related terms
nto allowing cross-origin access to their resources. Learn more General knowledge Cross-Origin Resource Sharing (CORS) on MDN Cross-origin resource sharing on Wikipedia CORS headers Access-Control-Allow-Origin Indicates whether the response can be shared. Access-Control-Allow-Credentials Indicates whether or not the response to the request can be exposed when the credentials flag is true. Access-Control-Allow-Headers Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request. Access-Control-Allow-Methods Specifies the method or methods allowed when accessing the resource in response to a preflight request. Access-Control-Expose-Headers Indicates which headers can be exposed as part of the response by listing their names...
Global object - MDN Web Docs Glossary: Definitions of Web-related terms
in a Worker has a WorkerGlobalScope object as its global object. Scripts running under Node.js have an object called global as their global object. window object in the Browser The window object is the Global Object in the Browser. Any Global Variables or Functions can be accessed as properties of the window object. Access Global Variables var foo = "foobar"; foo === window.foo; // Returns: true After defining a Global Variable foo, we can access its value directly from the window object, by using the variable name foo as a property name of the Global Object window.foo. Explanation: The global variable foo was stored in the window object, like this: foo: "foobar" Access Global Functions function greeting() { console.log("Hi!"); } window.greeting(); // It is the same as the nor...
Null - MDN Web Docs Glossary: Definitions of Web-related terms
invalid object or address. The meaning of a null reference varies among language implementations. In JavaScript, null is marked as one of the primitive values, because its behaviour is seemingly primitive. But in certain cases, null is not as "primitive" as it first seems! Every Object is derived from null value, and therefore typeof operator returns object for it: typeof null === 'object' // true ...
Operator - MDN Web Docs Glossary: Definitions of Web-related terms
Reserved syntax consisting of punctuation or alphanumeric characters that carries out built-in functionality. For example, in JavaScript the addition operator ("+") adds numbers together and concatenates strings, whereas the "not" operator ("!") negates an expression -- for example making a true statement return false. Learn more General knowledge Operator (computer programming) on Wikipedia Technical reference JavaScript operators ...
SQL Injection - MDN Web Docs Glossary: Definitions of Web-related terms
name: admin Password: anything 'or'1'='1 After clicking on the login button, the SQL query will work as follows: "SELECT Count(*) FROM Users WHERE Username=' admin ' AND Password=' anything 'or'1'='1 ' "; Just take a closer look at the above query's password section. Password=' anything 'or'1'='1 ' The password is not 'anything', hence password=anything results in FALSE, but '1'='1' is a TRUE statement and hence returns a TRUE value. Finally, due to the OR operator, the value ( FALSE OR TRUE ) is TRUE, so authentication bypasses successfully. Just due to a simple string (Magical String) the entire database is compromised. How To Prevent Before executing the queries for the user credentials, make some changes like the following: $id = $_GET['id'] (1) $id = Stripslashes($id) (2)...
State machine - MDN Web Docs Glossary: Definitions of Web-related terms
gram, circles represent each possible state and arrows represent transitions between states. Looking at the final state, you can discern something about the series of inputs leading to that state. There are two types of basic state machines: deterministic finite state machine This kind allows only one possible transition for any allowed input. This is like the "if" statement in that if x == true then doThis else doThat is not possible. The computer must perform one of the two options. non-deterministic finite state machine Given some state, an input can lead to more than one different state. . Figure 1: Deterministic Finite State Machine In Figure 1, the state begins in State 1; the state changes to State 2 given input 'X', or to State 3 given input 'Y'. Figure 2: Non-Determinis...
Truthy - MDN Web Docs Glossary: Definitions of Web-related terms
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, -0, 0n, "", null, undefined, and NaN). JavaScript uses type coercion in Boolean contexts. 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. ...
Type - MDN Web Docs Glossary: Definitions of Web-related terms
A value's data type also affects the operations that are valid on that value. For example, a value of type number can be multiplied by another number, but not by a string - even if that string contains only a number, such as the string "2". ...
Loop - MDN Web Docs Glossary: Definitions of Web-related terms
p when condition is met (i = 10) For the above example, the syntax is as follows: Statement 1 sets the variable for the loop (var i = 0). Statement 2 sets the loop condition (i < 10). Statement 3 increases the value of i (i++) each time the code block is run. While loop Syntax: while (condition){ execute code block } The code block will continue to loop as long as the condition is true. 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. ...
Accessible multimedia - Learn web development
xtContent = 'Play'; } }; These are very simple, just adding or subtracting 3 seconds to the currentTime each time they are clicked. In a real video player, you'd probably want a more elaborate seeking bar, or similar. Note that we also check to see if the currentTime is more than the total media duration, or if the media is not playing, when the Fwd button is pressed. If either conditions are true, we simply stop the video, to avoid the user interface going wrong if they attempt to fast forward when the video is not playing, or fast forward past the end of the video. Last of all, add the following to the end of the code, to control the time elapsed display: player.ontimeupdate = function() { let minutes = Math.floor(player.currentTime / 60); let seconds = Math.floor(player.currentTim...
What is accessibility? - Learn web development
most common for young people. In the U.S., "intellectual disabilities" is the new term for "mental retardation." In the U.K., "intellectual disabilities" is commonly "learning disabilities" or "learning difficulties". Implementing accessibility into your project A common accessibility myth is that accessibility is an expensive "added extra" to implement on a project. This myth actually can be true if either: You are trying to "retrofit" accessibility onto an existing website that has significant accessibility issues. You have only started to consider accessibility and uncovered related issues in the late stages of a project. If however, you consider accessibility from the start of a project, the cost of making most content accessible should be fairly minimal. When planning your proj...
Advanced styling effects - Learn web development
; } This gives us the following results: You can see here that the multiply mix blend has blended together not only the two background images, but also the color from the <div> below it too. Note: Don't worry if you don't understand some of the layout properties above, like position, top, bottom, z-index, etc. We will cover these in detail in our CSS Layout module. CSS shapes While it is true that everything in CSS is a rectangular box, and images are a physical rectangular box, we can make it look as if our content flows around non-rectangular things by using CSS Shapes. The CSS Shapes specification enables the wrapping of text around a non-rectangular shape. It's especially useful when working with an image which has some white-space you might want to float text around. In the ima...
Beginner's guide to media queries - Learn web development
n: landscape) { body { color: blue; } } Open this example in the browser, or view the source. "or" logic in media queries If you have a set of queries, any of which could match, then you can comma separate these queries. In the below example the text will be blue if the viewport is at least 600 pixels wide OR the device is in landscape orientation. If either of these things are true the query matches. @media screen and (min-width: 600px), screen and (orientation: landscape) { body { color: blue; } } Open this example in the browser, or view the source. "not" logic in media queries You can negate an entire media query by using the not operator. This reverses the meaning of the entire media query. Therefore in this next example the text will only be blue if...
Positioning - Learn web development
e; padding: 10px; margin: 10px; } span { background: red; border: 1px solid black; } .positioned { position: absolute; background: yellow; top: 30px; left: 30px; } First of all, note that the gap where the positioned element should be in the document flow is no longer there -- the first and third elements have closed together like it no longer exists! Well, in a way, this is true. An absolutely positioned element no longer exists in the normal document layout flow. Instead, it sits on its own layer separate from everything else. This is very useful: it means that we can create isolated UI features that don't interfere with the layout of other elements on the page. For example, popup information boxes and control menus; rollover panels; UI features that can be dragged and...
Responsive design - Learn web development
han a certain width, or a certain resolution) and apply CSS selectively to style the page appropriately for the user's needs. For example, the following media query tests to see if the current web page is being displayed as screen media (therefore not a printed document) and the viewport is at least 800 pixels wide. The CSS for the .container selector will only be applied if these two things are true. @media screen and (min-width: 800px) { .container { margin: 1em 2em; } } You can add multiple media queries within a stylesheet, tweaking your whole layout or parts of it to best suit the various screen sizes. The points at which a media query is introduced, and the layout changed, are known as breakpoints. A common approach when using Media Queries is to create a simple single-colu...
How can we design for all types of users? - Learn web development
xels. Also, check your website's statistics: you may receive visits from older browsers. We would advise the following: Describe fonts in rem units, most browsers will be very happy with them; Let older browsers display fonts with their own internal engine. Browser's engines will ignore any property or value in the CSS if they can't cope with them, so that your website is still usable if not true to your designer's vision. Older browsers are on the way out anyway. Note: Your mileage may vary. If you have to cater to older browsers, you'll have to use ems and do a bit more math. Line width There is a longstanding debate about line length on the web, but here's the story. Back when we had newspapers, printers realized that the reader's eyes would have trouble going from one line to th...
How do I start to design my website? - Learn web development
to reach my goals? All of this is called project ideation and is a necessary first step to reach your goal, whether you are a beginner or an experienced developer. Active Learning There is no active learning available yet. Deeper dive A project never starts with the technical side. Musicians will never make any music unless they first have an idea of what they want to play--and the same is true for painters, writers, and web developers. Technique comes second. Technique is obviously critical. Musicians must master their instrument. But good musicians can never produce good music without an idea. Therefore, before jumping into the technical side--for example, code and tools--you must first step back and decide in detail what you want to do. An hour's discussion with friends is a good s...
Advanced form styling - Learn web development
ears containing the options when you click on the <select> box to open it. You'll notice that the options don't inherit the font set on the parent. You also can't consistently set things like spacing and colors. For example, Firefox will apply color and background-color when set on the <option> elements, Chrome won't. Neither of them will apply any kind of spacing (e.g. padding). The same is also true of the autocomplete list that appears for the datalist. If you really need full control over the option styling, you'll have to either use some kind of library to generate a custom control, or build your own custom control, or in the case of select use the multiple attribute, which makes all the options appear on the page, sidestepping this particular problem: <select id="select" name="select" ...
Basic native form controls - Learn web development
browser (for example if you specify type="color" and the browser doesn't support native color pickers). Note: You can find examples of all the single line text field types on GitHub at single-line-text-fields.html (see it live also). Here is a basic single line text field example: <input type="text" id="comment" name="comment" value="I'm a text field"> Single line text fields have only one true constraint: if you type text with line breaks, the browser removes those line breaks before sending the data to the server. The following screenshot shows default, focused and disabled text input types in Firefox 71 and Safari on macOS and in Chrome 79 and Edge 18 on Windows 10. Note: HTML5 enhanced the basic original single line text field by adding special values for the type attribute tha...
The HTML5 input types - Learn web development
ws intranet email addresses by default. To implement different validation behavior, you can use the pattern attribute, and you can also custom the error messages; we'll talk how to use these features in the Client-side form validation article later on. Note: If the data entered is not an email address, the :invalid pseudo-class will match, and the validityState.typeMismatch property will return true. Search field Search fields are intended to be used to create search boxes on pages and apps. This type of field is set by using the value search for the type attribute: <input type="search" id="search" name="search"> The main difference between a text field and a search field is how the browser styles its appearance. Often, search fields are rendered with rounded corners; they also sometime...
UI pseudo-classes - Learn web development
to reset their choices. Also mentioned above radios/checkboxes will be matched by the :indeterminate pseudo-class when they are in a state where they are neither checked nor unchecked. But what does this mean? Elements that are indeterminate include: <input/radio> inputs, when all radio buttons in a same-named group are unchecked <input/checkbox> inputs whose indeterminate property is set to true via JavaScript <progress> elements that have no value. This isn't something you'll likely use very often. One use case could be an indicator to tell users that they really need to select a radio button before they move on. Let's look at a couple of modified versions of the previous example that remind the user what the default option was, and style the radio buttons when indeterminate. Both o...
Tips for authoring fast-loading HTML pages - Learn web development
To mark an image for lazy loading, specify its loading attribute with a value of lazy. With this set, the image will only be loaded when it's needed. <img href="./images/footerlogo.jpg" loading="lazy"> Note that lazily-loaded images may not be available when the load event is fired. You can determine if a given image is loaded by checking to see if the value of its Boolean complete property is true. Choose your user-agent requirements wisely To achieve the greatest improvements in page design, make sure that reasonable user-agent requirements are specified for projects. Do not require your content to appear pixel-perfect in all browsers, especially not in down-version browsers. Ideally, your basic minimum requirements should be based on the consideration of modern browsers that support t...
Creating hyperlinks - Learn web development
client with no destination address. This is often useful as "Share" links that users can click to send an email to an address of their choosing. Specifying details In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term. Here's an example that includes a cc, bcc, subject and body: <a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&subject=The%20subject%20of%20the%20email&body=The%20body%20of%20the%20email"> Send mail with cc, bcc, subjec...
Introduction to events - Learn web development
is system that included both, which is the one modern browsers implemented. Note: As mentioned above, by default all event handlers are registered in the bubbling phase, and this makes more sense most of the time. If you really want to register an event in the capturing phase instead, you can do so by registering your handler using addEventListener(), and setting the optional third property to true. Event delegation Bubbling also allows us to take advantage of event delegation -- this concept relies on the fact that if you want some code to run when you select any one of a large number of child elements, you can set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually. Rem...
Function return values - Learn web development
a new value is entered into the text input, and submitted (e.g., enter a value, then unfocus the input by pressing Tab or Return). When this anonymous function runs, the value in the input is stored in the num constant. Next, we do a conditional test. If the entered value is not a number, an error message is printed to the paragraph. The test looks at whether the expression isNaN(num) returns true. The isNaN() function to test whether the num value is not a number -- if so, it returns true, and if not, it returns false. If the test returns false, the num value is a number. Therefore, a sentence is printed out inside the paragraph element that states the square, cube, and factorial values of the number. The sentence calls the squared(), cubed(), and factorial() functions to calculate the...
Test your skills: Loops - Learn web development
vious task. Download the starting point for this task to work in your own editor or in an online editor. Loops 3 In this final task, you are provided with the following: i -- starts off with a value of 500; intended to be used as an iterator. para -- contains a reference to a paragraph, which will be used to report the results. isPrime() -- a function that, when passed a number, returns true if the number is a prime number, and false if not. You need to use a loop to go through the numbers 2 to 500 backwards (1 is not counted as a prime number), and run the provided isPrime() function on them. For each number that isn't a prime number, continue on to the next loop iteration. For each one that is a prime number, add it to the paragraph's textContent along with some kind of separator...
Third-party APIs - Learn web development
h. Adding a custom marker Adding a marker (icon) at a certain point on the map is easy -- you just use the L.marker() method (which seems to be documented in the related Leaflet.js docs). Add the following code to your example, again inside window.onload: L.marker([53.480759, -2.242631], { icon: L.mapquest.icons.marker({ primaryColor: '#22407F', secondaryColor: '#3B5998', shadow: true, size: 'md', symbol: 'A' }) }) .bindPopup('This is Manchester!') .addTo(map); As you can see, this at its simplest takes two parameters, an array containing the coordinates at which to display the marker, and an options object containing an icon property that defines the icon to display at that point. The icon is defined using an mapquest.icons.marker() method, which as you can see co...
Storing the information you need — Variables - Learn web development
other programming languages. When you give a variable a number value, you don't include quotes: let myAge = 17; Strings Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks; otherwise, JavaScript tries to interpret it as another variable name. let dolphinGoodbye = 'So long and thanks for all the fish'; Booleans Booleans are true/false values -- they can have two values, true or false. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be: let iAmAlive = true; Whereas in reality it would be used more like this: let test = 6 < 3; This is using the "less than" operator (<) to test whether 6 is less than 3. As you might expect, it returns false, becau...
Solve common problems in your JavaScript code - Learn web development
while loops? How do you iterate over the elements in an array? How do you iterate over the elements in a multidimension...
JavaScript object basics - Learn web development
ent('div'); const myVideo = document.querySelector('video'); You were using methods available on an instance of the Document class. For each webpage loaded, an instance of Document is created, called document, which represents the entire page's structure, content, and other features such as its URL. Again, this means that it has several common methods and properties available on it. The same is true of pretty much any other built-in object or API you've been using -- Array, Math, and so on. Note that built in objects and APIs don't always create object instances automatically. As an example, the Notifications API -- which allows modern browsers to fire system notifications -- requires you to instantiate a new object instance using the constructor for each notification you want to fire. Try ...
Inheritance in JavaScript - Learn web development
in a browser, and entering Teacher.prototype.constructor into the console to verify. This can become a problem, so we need to set this right. You can do so by going back to your source code and adding the following line at the bottom: Object.defineProperty(Teacher.prototype, 'constructor', { value: Teacher, enumerable: false, // so that it does not appear in 'for in' loop writable: true }); Now if you save and refresh, entering Teacher.prototype.constructor should return Teacher(), as desired, plus we are now inheriting from Person()! Giving Teacher() a new greeting() function To finish off our code, we need to define a new greeting() function on the Teacher() constructor. The easiest way to do this is to define it on Teacher()'s prototype -- add the following at the bott...
Working with JSON - Learn web development
very much resembles JavaScript object literal format. You can include the same basic data types inside JSON as you can in a standard JavaScript object -- strings, numbers, arrays, booleans, and other object literals. ...
Aprender y obtener ayuda - Learn web development
ecommend taking a 15 minutes break every hour to 90 minutes. Eat, exercise, and sleep. Eat healthily, get regular exercise, and make sure you get enough sleep. This sounds obvious, but it is easy to forget when you get really into coding. Factor these essential ingredients into your schedule, and make sure you are not doing your learning time instead of these things. Give yourself rewards. It's true that all work and no play makes Jack a dull boy. You should try to schedule fun things to do after each learning session, which you'll only have when the learning is over and complete. If you are really into gaming, for example, there is something quite motivating about saying "no gaming tonight unless I get through my 5 hours of learning". Now all you need is willpower. Good luck! Co-learning a...
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
small issue to contend with. The "todos left" indicator always says "x todos left", even when there is only one todo left, which is bad grammar! To fix this, we need to update this part of the template to include some conditional rendering. ...
Introduction to client-side frameworks - Learn web development
DSLs Angular IE9+ TypeScript HTML-based; TypeScript React Modern (IE9+ with Polyfills) JSX JSX; TypeScript Vue IE9+ HTML-based HTML-based, JSX, Pug Ember Modern (IE9+ in Ember version 2.18) Handlebars Handlebars, TypeScript Note: DSLs we've described as "HTML-based" do not have official names. They are not really true DSLs, but they are non-standard HTML, so we believe they are worth highlighting. Citations for this table: React browser support: official docs Ember browser support: Ember 3.0 release announcement Ember templating language (official docs) Does the framework have a strong community? This is perhaps the hardest metric to measure, because community size does not correlate directly to easy...
Getting started with React - Learn web development
raries to render to certain environments. For instance, React Native can be used to build mobile applications; React 360 can be used to build virtual reality applications; and there are other possibilities besides. To build for the web, developers use React in tandem with ReactDOM. React and ReactDOM are often discussed in the same spaces as -- and utilized to solve the same problems as -- other true web development frameworks. When we refer to React as a "framework", we're working with that colloquial understanding. React's primary goal is to minimize the bugs that occur when developers are building UIs. It does this through the use of components -- self-contained, logical pieces of code that describe a portion of the user interface. These components can be composed together to create a ful...
React interactivity: Events and state - Learn web development
box" defaultChecked={props.completed} onChange={() => props.toggleTaskCompleted(props.id)} /> Save everything and return to your browser and notice that our first task, Eat, is checked. Open your JavaScript console, then click on the checkbox next to Eat. It unchecks, as we expect. Your JavaScript console, however, will log something like this: Object { id: "task-0", name: "Eat", completed: true } The checkbox unchecks in the browser, but our console tells us that Eat is still completed. We will fix that next! Synchronizing the browser with our data Let's revisit our toggleTaskCompleted() function in App.js. We want it to change the completed property of only the task that was toggled, and leave all the others alone. To do this, we'll map() over the task list and just change the one w...
Deployment and next steps - Learn web development
g the -w argument, which tells rollup to watch files and rebuild on changes. ...
Getting started with Svelte - Learn web development
It extends HTML by allowing JavaScript expressions in markup and providing directives to use conditions and loops, in a fashion similar to handlebars. It extends CSS by adding a scoping mechanism, allowing each component to define their own styles without the risk of clashing with other component's styles. It extends JavaScript by reinterpreting specific directives of the language to achieve true reactivity and ease component state management. The compiler only intervenes in very specific situations and only in the context of Svelte components. Extensions to the JavaScript language are minimal and carefully picked in order to not break JavaScript syntax nor alienate developers. In fact, you will be mostly working with vanilla JavaScript. First steps with Svelte Being a compiler, you c...
Handling common HTML and CSS problems - Learn web development
n really old browsers, and acts as a fallback if the modern shiny features don't work. What happens is a browser visiting this page first applies the first background-color value; when it gets to the second background-color declaration, it will override the initial value with this value if it supports RGBA colors. If not, it will just ignore the entire declaration and move on. Note: The same is true for other CSS features like media queries, @font-face and @supports blocks -- if they are not supported, the browser just ignores them. IE conditional comments IE conditional comments are a modified proprietary HTML comment syntax, which can be used to selectively apply HTML code to different versions of IE. This has proven to be a very effective mechanism for fixing cross browser bugs. The sy...
Handling common JavaScript problems - Learn web development
tup in your JavaScript. You need some kind of a feature detection test that detects whether the browser supports the feature we are trying to use: if (browserSupportsAllFeatures()) { main(); } else { loadScript('polyfills.js', main); } function main(err) { // actual app code goes in here } So first we run a conditional that checks whether the function browserSupportsAllFeatures() returns true. If it does, we run the main() function, which will contain all our app's code. browserSupportsAllFeatures() looks like this: function browserSupportsAllFeatures() { return window.Promise && window.fetch; } Here we are testing whether the Promise object and fetch() function exist in the browser. If both do, the function returns true. If the function returns false, then we run the code inside ...
Command line crash course - Learn web development
This can be installed directly from the Windows store for free. You can find all the documentation you need in the Windows Subsystem for Linux Documentation. In terms of what option to choose on Windows, we'd strongly recommend trying to install the WSL. You could stick with the default command prompt (cmd), and many tools will...
Chrome Worker Modules
yclic calls to require(). However, if you have cyclic requirements, some of the modules involved in the cyclic requirements may become visible by the other modules before they are fully evaluated. No attempt is made to fully isolate modules from each other. In particular, globals (String, Math, Object, self) and the worker global scope itself (this) are shared between workers. In other words, the true isolation unit is the worker itself, not the module. ...
Accessibility Features in Firefox
all your bookmarks, and is easy to move around from computer to computer. View selection source (techies only): when you select some text and right click or press Shift+F10, you can "view selection source". This will show the HTML source for only the selected text, which is useful for understanding accessibility problems in some web sites. Customize Your Experience! Many users are finding the true greatness of Firefox lies in support for third party extensions. Extensions are small add-ons which can change your browser experience as you see fit. Extensions can easily be installed or removed with the extension manager in the Tools menu. Here are some examples of accessible extensions, although there are hundreds more to try (thank you to the GW Micro knowledge base for some of this informa...
CSUN Firefox Materials
structure. Caret browsing allows you to move through web content one letter a time. You can even select web content and copy it to the clipboard. -- all with the keyboard Moving back and forward by web page (Alt+Left and Alt+Right) occurs near-instantaneously The download manager provides keyboard access to all of your recent downloads Customize Your Experience! Many users are finding the true greatness of Firefox lies in support for third party extensions. Extensions are small add-ons which can change your browser experience as you see fit. Extensions can easily be installed or removed with the extension manager in the Tools menu. Here are some examples of accessible extensions, although there are hundreds more to try (thank you to the GW Micro knowledge base for some of this informat...
Multiprocess on Windows
M Apartments, Part II For the purposes of this document, "COM" will refer to Microsoft COM (as opposed to XPCOM). Gecko and apartments Most code that runs on Gecko's main thread is not thread safe. Since Gecko's main thread uses COM, and COM requires threads to declare their threading model, the main thread must initialize itself to live inside its own single threaded apartment (STA). This is true for both chrome and content processes. As you should already know from the prerequisite reading, single threaded apartments receive remote procedure calls (RPCs) from COM, via the Windows message queue. From a performance standpoint, this is less than ideal. The Windows message queue carries a lot of baggage for the purposes of maintaining backward compatibility. On the other hand, COM's multith...
Accessible Toolkit Checklist
ich can vary from platform to platform. Expose your UI - a way for assistive technologies such as screen readers, screen magnifiers and voice dictation software to understand your software. Provide theme compatibility with the operating system, at least as an option. Some low vision users will be running your software with high contrast or large font themes. Go beyond section 508. Implement true usability for everyone, and make your toolkit follow the guidelines for each platform. The Approaches There are two basic kinds of toolkits, which each provide different challenges when implementing accessibility: Native widget toolkits , like Eclipse and wxWidgets, already have some accessibility built-in. These toolkits wrap the widgets implemented by the OS with a consisten...
Testopia
tallation before attempting to install or upgrade. Testopia 2.3 This version supports Bugzilla 3.4. The main new features are: Support XML export and import of test plans and children Support CSV export of test cases and results. New reports: worst offender and case roll-up Set priorities on indidual case-runs New clone options Uses the latest Extjs 3.0 library Converts Testopia into a true Bugzilla extension Numerous bug fixes Integration Points Testopia integrates with Bugzilla products, components, versions, and milestones to allow a single management interface for high level objects. Testopia allows users to login to one tool and uses Bugzilla group permissions to limit access to modifying test objects. Testopia allows users to attach bugs to test case run r...
What to do and what not to do in Bugzilla
canconfirm or editbugs, especially in order to triage bugs or to participate in a bug day, then you can ask in #bmo on irc, or you may create a bug requesting permissions. Include a link to your Bugzilla activity page in the bug description. Before you have canconfirm, you can still do good triaging by leaving comments with useful information on the bug that will help to confirm it. The same is true for editbugs: leave comments with the information you'd like to be able to edit into the bug, and that will help you get the editbugs permissions quickly. Canconfirm privilege The canconfirm privilege allows you to confirm bugs and also to start your bug reports in the confirmed state (NEW). It also governs which bug entry form you are presented with first (either the guided or advanced forms)...
Chrome registration
bug where if you use the comparisons <, > or =, the version string had be two or more characters long. If not, you would get a message in the error console that the appversion flag was not recognized. See bug 380398. platformversion When supporting more then one application, it is often more convenient for an extension to specify which Gecko version it is compatible with. This is particularly true for binary components. If there are chrome registration lines which only apply to a particular Gecko version, the flag platformversion=version platformversion<version platformversion<=version platformversion>version platformversion>=version indicates that the instruction should only be applied if the extension is installed into an application using the Gecko version identified. Multiple platfo...
Creating a spell check dictionary add-on
eate and edit it with a plain text editor such as Notepad. ...
Creating Sandboxed HTTP Connections
hods for working with headers: two for getting and setting request headers, and two for getting and setting response headers. The cookie header for requests is called "Cookie", while for responses it is "Set-Cookie". getRequestHeader(aHeader) - returns the request header value for the requested header. setRequestHeader(aHeader, aValue, aMerge) - sets the request header's value. If aMerge is true, the new value is appened, otherwise the old value is overwritten. getResponseHeader(aHeader) - returns the response header value for the requested header. setResponseHeader(aHeader, aValue, aMerge) - sets the response header's value. If aMerge is true, the new value is appened, otherwise the old value is overwritten. These methods provide all the required functionality needed to modify coo...
Adding APIs to the navigator object
. You can read about creating and registering XPCOM components in JavaScript. 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. The newly added object is a reference to the component specified by the contract ID MY_CONTRACT_ID. You can learn more about Contract IDs are unique text identifiers for XPCOM components. Using a manifest to add an object to navigator You can also add an object to the window.navigator object by using the chrome manifest of an ad...
How Mozilla's build system works
with the make tool, consuming makefiles. However, with the transition to moz.build files, you may eventually see non-make build backends, such as Tup or Visual Studio. When building the tree, most of the time is spent in Phase 3. This is when header files are installed, C++ files are compiled, files are preprocessed, and so on. Recursive Make Backend The recursive make backend is the tried-and-true backend used to build the tree. It's what's been used since the dawn of Mozilla. Essentially, there are makefiles in each directory. make starts processing the makefile in the root directory and then recursively descends into child directories until it's done. But there's more to the process than that. The recursive make backend divides the source tree into tiers. A tier is a grouping of related...
The Firefox codebase: CSS Guidelines
r: red; Put multiple selectors on different lines Do this: h1, h2, h3 { font-family: sans-serif; text-align: center; } Not this: h1, h2, h3 { font-family: sans-serif; text-align: center; } Naming standards for class names lower-case-with-dashes is the most common. But camelCase is also used sometimes. Try to follow the style of existing or related code. Other tips Assume ="true" in attribute selectors. Example: Use option[checked], not option[checked="true"]. Avoid ID selectors unless it is really the wanted goal, since IDs have higher specificity and therefore are harder to override. Using descendant selectors is good practice for performance when possible: For example: .autocomplete-item[selected] > .autocomplete-item-title would be more efficient ...
Obsolete Build Caveats and Tips
compilator is Visual Studio 2010; if you want to use it, you must use a previous version of it !), or 2005 Professional From Build_Instructions Those who need to work with the code for Firefox 3/Mozilla 1.9 and earlier can check out the latest source using CVS. In reality, you should probably not need to do this, since that code is very obsolete. This note below seems redundant as this is true by default https://msdn.microsoft.com/en-us/library/dh8che7s%28v=vs.110%29.aspx Note: Starting with Gecko 7.0, you should no longer include "-Zc:wchar_t-" in the command line when building on Windows. If you're using Visual Studio, go to Project Properties > C/C++ > Language > Treat wchar_t as Built-in Type and set it to "yes". From Source_Code/Mercurial mozilla-2.0 (Firefox 4.0) Code fo...
Listening to events on all tabs
bProgress webProgress, nsIURI aRefreshURI, long aMillis, boolean aSameURI ); Parameters aBrowser The browser that fired the notification. aWebProgress The nsIWebProgress instance that fired the notification. aRefreshURI The new URI that aWebProgress has requested redirecting to. aMillis The delay (in milliseconds) before refresh. aSameURI True if aWebProgress is requesting a refresh of the current URI. False if aWebProgress is requesting a redirection to a different URI. Return value true if the refresh may proceed. false if the refresh should be aborted. onLinkIconAvailable Notification that the site icon for a browser has been found. void onLinkIconAvailable( nsIDOMXULElement aBrowser, ); Parameters aBrowser The browser...
SVG Guidelines
ile since it only needs to store one pixel of data. At large dimensions the raster file may be much larger than the SVG file. Scalability, with caveats One of the primary advantages of SVG is that as it is scaled it does not pixelate. However, this is not to say that it always does away with the need to have a collection of raster images for display at different scales. This can be particularly true for icons. While SVG may scale well enough for flat-ish icons without a lot of detail, for icons that try to pack in a lot of detail graphic artists generally want to be able to pixel tweak. Performance While SVG provides a lot of flexibility in terms of scaling, themability, etc. this flexibility depends on doing computations for SVG images at the time they're displayed, rather than at the tim...
mach
mach commands. Currently, this is implemented through Python decorators. 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. The decorators are: @CommandProvider This is a class decorator that tells mach that this class contains methods that implement mach commands. Without this decorator, ma...
Experimental features in Firefox
loper Edition 60 No Beta 60 No Release 60 No Preference name security.mixed_content.upgrade_display_content FTP support disabled For security reasons, Mozilla intends to remove support for FTP from Firefox in 2020, effective in Firefox 82. See bug 1622409 for implementation progress. The network.ftp.enabled preference must be enabled (set to true) to allow FTP to be used. Release channel Version added Enabled by default? Nightly 77 Yes Developer Edition 77 No Beta 77 No Release 77 No Preference name network.ftp.enabled Developer tools Mozilla's developer tools are constantly evolving. We experiment with new ideas, add new features, and test...
Limitations of chrome scripts
ith the shim The shim intercepts chrome process code that adds listeners to XUL elements and sets up listeners in the content process, relaying the result back to the chrome process. The Event object itself is relayed to the chrome process as a CPOW. To make the shim unnecessary: register event listeners on the global object inside a frame script. For example: addEventListener("load", handler, true) // for example If you need to contact the chrome process when that happens, send it a message. Sandboxes You can create sandboxes in the chrome or the content process. Sandboxes are often used as a safe way to manipulate web content, and if that's your goal, create the sandbox in the content process. There is a shim for sandboxes: if you make a sandbox in the chrome process and give it...
Process scripts
nt process message manager and calling its loadProcessScript() function. The following code uses the global parent process message manager, which will load the script into the the chrome process and any child processes: // chrome code let ppmm = Cc["@mozilla.org/parentprocessmessagemanager;1"] .getService(Ci.nsIProcessScriptLoader); ppmm.loadProcessScript("chrome://whatever/process-script.js", true); ppmm.addMessageListener("Hello", function(msg) { ... }); The process script's global is a child process message manager, which enables the process script to receive messages from the chrome side, and to send messages to the chrome side: // process-script.js if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { dump("Welcome to the process script in a content process")...
HTMLIFrameElement.clearMatch()
search bar for more explanation. 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()
...
HTMLIFrameElement.getActive()
y also be large incompatibilities between implementations and the behavior may change in the future. The getActive() method of the HTMLIFrameElement indicates whether the current browser <iframe> is the currently active frame. Syntax var amIActive = instanceOfHTMLIframeElement.getActive(); Returns A Boolean indicating whether the current browser <iframe> is the currently active frame (true) or not (false.) Parameters None. Example var browser = document.querySelector('iframe'); var amIActive = browser.getActive(); Specification Not part of any specification. ...
HTMLIFrameElement.getMuted()
TMLIframeElement.getMuted(); and a Promise version: instanceOfHTMLIframeElement.getMuted().then(function(muted) { ... }); Returns Callback version: A DOMRequest that represents the get muted request. It has an onsuccess handler to handle the success case, and an onerror handler to handle the failure case. The muted value is available in the request.result property, and is a Boolean value -- true means muted, and false means unmuted. Promise version: A Promise that resolves with the muted value -- a Boolean where true means muted, and false means unmuted. Parameters None. Example Callback version: var browser = document.querySelector('iframe'); var request = browser.getMuted(); request.onsuccess = function() { if(request.result) { console.log('The browser is muted.'); } e...
HTMLIFrameElement.getVisible()
t to handle the getVisible() request's success and error cases. If the request is successful, the request's result is a Boolean indicating the visible state of the browser <iframe>. Parameters None. Example var browser = document.querySelector('iframe'); var request = browser.getVisible(); request.onsuccess = function() { console.log('The visible state is: ' + this.result ? 'true' : 'false'); } Specification Not part of any specification. ...
mozbrowsercontextmenu
e menu is associated with. uri A DOMString. In the case of an image or video context menu, this is the src of the image or video clicked on to get the context menu. In the case of an link context menu, it is the link's href. text A DOMString representing the text of the link clicked on, in the case of a link context menu. hasVideo A Boolean. In the case of a video context menu, this returns true if the video has metadata and is bigger than 0 x 0, or false if not. action A DOMString representing the action of a form, in the case of a form context menu. method A DOMString representing the method of a form, in the case of a form context menu. name A DOMString representing the name of a form, in the case of a form context menu. The Menu object An object representing a custom menu de...
mozbrowserfindchange
bubbles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: active A Boolean indicating whether a search is currently active (true), or not (false.) searchString A DOMString representing the string that is currently being searched for. searchLimit A number indicating the maximum number of searches that can be returned. numberOfMatches A number indicating the number of matches returned by the search. activeMatchOrdinal A number indicating the position of the currently highlighted search result, e.g. 3 out of 5. Exam...
mozbrowserlocationchange
cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. detail The detail property returns an anonymous JavaScript object with the following properties: url A DOMString representing the URL of the new location. canGoBack A Boolean that defines whether it's possible to go back in the navigation history (true) or not (false). canGoForward A Boolean that defines whether it's possible to go forward in the navigation history (true) or not (false). Example This example updates the URL bar so that it will always display the correct URL for the current location. var browser = document.querySelector("iframe"); browser.addEventListener('mozbrowserlocationchange', function (event) { urlBar.value = eve...
mozbrowsersecuritychange
tring representing the current loading state of mixed active content. Possible values are: loaded_mixed_active_content: Indicates that the mixed active content has been loaded. blocked_mixed_active_content: Indicates that the mixed active content has been blocked from loading. 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). Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowsersecuritychange", function( event ) { console.log("The SSL state ...
mozbrowserusernameandpasswordrequired
ils Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following members: host A DOMString representing the host requesting the HTTP authentification. realm A DOMString representing the value of the realm HTTP header. isProxy A Boolean indicating whether the server dealing with the authentication is a proxy server (true) or not (false). authenticate() A function that is called to enable the authentication to go ahead. It needs to take two parameters -- the username and password to authenticate. cancel() A function that is called to cancel the authentication. Example var browser = document.querySelector("iframe[mozbrowser]"); browser.addEventListener("mozbrowserusernameandpasswordrequired", function( even...
mozbrowservisibilitychange
bles Read only Boolean Whether the event normally bubbles or not. cancelable Read only Boolean Whether the event is cancellable or not. details Read only Object A custom object. details The details property returns an anonymous JavaScript object with the following properties: visible A Boolean that indicates whether the browser iframe is visible (true) or not (false). Example var browser = document.querySelector("iframe"); browser.addEventListener("mozbrowservisibilitychange", function( event ) { if(event.details.visible) { console.log("The browser is visible."); } else { console.log("The browser is hidden."); } }); Related Events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowseric...
HTMLIFrameElement.reload()
also be large incompatibilities between implementations and the behavior may change in the future. The reload() method of the HTMLIFrameElement interface is used to reload the content of the <iframe>. Syntax instanceOfHTMLIframeElement.reload(hardReload); Returns Void. Parameters hardReload Optional A boolean that indicates whether all the resources to reload must be revalidated (true) or may be taken directly from the browser cache (false). Examples stopReload.addEventListener('touchend',function() { if(stopReload.textContent === 'x') { browser.stop(); } else { browser.reload(); } }); Specification Not part of any specification. ...
HTMLIFrameElement.setActive()
implementations and the behavior may change in the future. The setActive() method of the HTMLIFrameElement sets the current <iframe> as the active frame, which has an effect on how it is prioritized by the process manager. Syntax instanceOfHTMLIframeElement.setActive(boolean); Returns Void. Parameters boolean A Boolean that indicates whether the iframe is to be the active frame (true) or not (false). Example var browser = document.querySelector('iframe'); browser.setActive(); Specification Not part of any specification. ...
CSS -moz-bool-pref() @supports function
Example Warning: This will only work when loaded from a Gecko chrome stylesheet. ...
:-moz-lwtheme-brighttext
...
:-moz-lwtheme-darktext
...
:-moz-lwtheme
...
Embedding the editor
r window limitation The current composer window XUL/C++ architecture has grown up with the assumption that there can be just one <editor> tag per window. At window construction time, we get the editorShell from the <editor> element, and put that into window.editorShell. Thence, lots of JavaScript in editor.js, ComposerCommands.js and the various dialog JS files assume that they can get at the one true editor via window.editorShell. This assumption was short-sighted, and must be fixed. Editor assumes XUL document structure There is C++ and JS code in the editor that assumes that the editor is living in a XUL document, and that there are XUL document nodes out there whose attributes can be tweaked to change the state of the UI (e.g. the inline style buttons). This needs to be changed to allow em...
How to Report a Hung Firefox
This won't produce useful results on a regular release/beta build. Instead of crashing Firefox, more advanced developers who know how to use a debugger can try attaching to the Firefox process and debugging in place. This is only useful if you h...
IPDL Best Practices
Specifically, because AllocPProtocol and DeallocPProtocol are asymmetric, if IPDL ends up shutting down the protocol tree due to an error, the auto pointer will attempt to trigger protocol delet...
Creating a New Protocol
IPDL-generated classes PNewProtocolParent and PNewProtocolChild. It must implement abstract methods for receiving the appropriate messages on each side. The method signatures can be read from the generated PNewProtocolParent.h and PNewProtocolChild.h headers. Writing the Tests Protocols which are managed by PBrowser must be tested using the mochitest-chrome test framework with a <browser remote="true">. It is acceptable to use synchronous calls on JPW wrappers for testing purposes. It may be possible to test protocols unrelated to a particular window using the xpcshell testing framework, which has additional primitives in Electrolysis for launching and running JS commands in a content process. ...
IPDL Type Serialization
Serializers and deserializers are security-sensitive and must always receive two reviews from module owners who understand IPC serialization well. If in doub...
Integrated Authentication
horization to the server. network.automatic-ntlm-auth.trusted-uris lists the trusted sites to use NTLM authentification. If you wish to use non-fully-qualified entries of the form mydomain.com in the above preferences for NTLM and SPNEGO authentication, you will also need to set the preferences network.automatic-ntlm-auth.allow-non-fqdn and network.negotiate-auth.allow-non-fqdn (respectively) to true. Original Document Information Author(s): Darin Fisher Last Updated Date: December 27, 2005 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
Internationalized Domain Names (IDN) Support in Mozilla Browsers
steps described below. Create a new preference item using the menu New > String via a right-mouse click. The name of the preference is: network.IDN_prefix. The value should be "bq--". This will change the default from Puncycode to RACE. Next create another new preference item using the right-mouse click menu New > Boolean. The name of the preference is: network.IDN_testbed. The value should be "true". Now access IDN sites under the .com and .net top domains. You should succeed in reaching the sample sites. Don't forget to set the value of these preferences to "default" once you are finished with testing! Caveats and Conclusions Netscape 7.1/Mozilla 1.4 has solid support for Internationalized Domain Names and is the first browser with built-in support for new RFC's for IDN established by...
Code Samples
if (addon.isActive) addon.userDisabled = addon.isActive; }); Listening for add-on uninstall This example sets a variable beingUninstalled that you can check when you get a profile-before-change message to do cleanup for your add-on on uninstall. ...
InstallListener
nstall representing the install onExternalInstall() Called when an add-on is installed through some system other than an AddonInstall. void onExternalInstall( in Addon addon, in Addon existingAddon, in boolean needsRestart ) Parameters addon The newly installed Addon existingAddon An Addon that will be replaced by this install or null if no add-on is being replaced needsRestart True if the installation requires a restart ...
TypeListener
with addTypeListener() and will then receive notification as AddonType are registered and unregistered. Method Overview void onTypeAdded(in AddonType type) void onTypeRemoved(in AddonType type) Methods onTypeAdded() Called when an add-on type has been added. void onTypeAdded( in AddonType type ) Parameters type The AddonType that is being added needsRestart True if an application restart is necessary for the change to take effect onTypeRemoved() Called when an add-on type has been removed. void onTypeRemoved( in AddonType type, ) Parameters type The AddonType that has been removed ...
Add-on Repository
erms) void cancelSearch() void retrieveRecommendedAddons(in integer maxResults, in SearchCallback callback) void searchAddons(in string searchTerms, in integer maxResults, in SearchCallback callback) Properties Property Type Description homepageURL string The URL of the repository site's home page. isSearching boolean true if a search is currently in progress; otherwise false. Methods getRecommendedURL() Returns the URL that can be visited to see recommended add-ons. string getRecommendedURL(); Parameters None. Return value An URL indicating the repository's page of recommended add-ons. getSearchURL() Returns an URL of a web page that can be visited to see search results for the specified search ter...
AsyncShutdown.jsm
condition. If several blockers have been registered for the same condition, remove all these blockers. If no blocker has been registered for this condition, this is a noop. boolean removeBlocker( in function|promise|* condition ) Arguments condition A condition blocking the completion of the phase. This must be the same condition as was passed to addBlocker prior. 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. Examples AsyncShutdown.profileBeforeChange.addBlocker("Module: just a promise", promise); // profileBeforeChange will not complete until // promise is resolved or r...
DeferredTask.jsm
nce Gecko 28 void cancel();Obsolete since Gecko 28 void arm(); void disarm(); Promise finalize(); Attributes isArmed boolean Indicates whether the task is currently requested to start again later, regardless of whether it is currently running. isRunning boolean Indicates whether the task is currently running. This is always true when read from code inside the task function, but can also be true when read from external code, in case the task is an asynchronous generator function. Methods isPending Obsolete since Gecko 28 Check the current task state. bool isPending(); Return value Returns true if pending, false otherwise. start Obsolete since Gecko 28 Start (or postpone) task. void start(); flush Obso...
DownloadList
keeping partial data. A filter function may be specified to remove only a subset of those downloads. This method finalizes each removed download, ensuring that any partially downloaded data associated with it is also removed. Promise removeFinished( Function aFilterFn ); Parameters aFilterFn The filter function is called with each download as its only argument, and should return true to remove the download and false to keep it. This parameter may be null or omitted to have no additional filter. ...
JavaScript OS.Constants
sses["@mozilla.org/net/osfileconstantsservice;1"]. getService(Components.interfaces.nsIOSFileConstantsService). init(); From a chrome worker No initialization is required. Module OS.Constants is always available for chrome workers. OS.Constants.Sys Constants related to system configuration. Name The name of the operating system (e.g. "Darwin"). DEBUG Set to true on debug build configurations, non-existent otherwise. OS.Constants.Path Paths of well-known files and directories. libxul The path to the file containing libxul. Useful, for instance, to access the platform code from JavaScript in conjunction with js-ctypes. profileDir The path to the current profile. homeDir The path to the user's home directory. ...
OS.File.Error
act that a file exists. Instances of OS.File.Error In case of any I/O error, the functions of OS.File raise instances of OS.File.Error. These exceptions hold both a human-readable error message detailing the I/O error and attributes to help determining the cause of the error. Cross-platform attributes operation The human-readable name of the failed operation. 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. Platform-specific attributes unixErrno (defined under Unix only) The syst...
OS.File.Info
vert an instance of OS.File.Info to a form that can be serialized and transmitted between threads or processes. object toMsg( in OS.File.Info value ) Arguments Returns An object with the same fields as value but that may be serialized and transmitted between threads or processes. value An instance of OS.File.Info. Instances of OS.File.Info Cross-platform Attributes isDir true if the file is a directory, false otherwise. isSymLink true if the false is a symbolic link, false otherwise. (As of Firefox 38 this is always true on all systems, this is a bug: Bugzilla 1145885) (On Windows this returns false for hard links) size The number of bytes in the file. creationDate Deprecated in Bugzilla :: Bug 807875. Before deprecation, this used ...
PerfMeasurement.jsm
Pass PerfMeasurement.ALL to record all event types. Return value A new PerfMeasurement object configured to record the specified event types. Methods canMeasureSomething() Indicates whether or not the platform on which your code is running supports this code module. static bool canMeasureSomething(); Parameters None. Return value If even one of the event types can be recorded, this will return true. Otherwise, it returns false. reset() Resets all the enabled counters to zero. void reset(); Parameters None. start() Starts measuring the performance indicators that were specified when the PerfMeasurement object was created. void start(); Parameters None. stop() Stops measuring performance data. For each enabled counter, the number of measured events of that type that occurred are added to th...
Index
ng some quality assurance testing on your work to make sure you're on the right track. 15 Release phase Localization You've made it! You've setup up your local and remote environments, you've selected your L10n tools and projects, done some localization and even some testing! Now you're ready for the final phase: becoming an official L10n release. Here, we'll continue to stay true to the original intent of this guide and only present you with the technical information you need to become an official release. We'll primarily focus on getting your release repository setup and the Mercurial commands you'll need to know to use that repository. 16 Translation phase Localization, Localization:Tools Congratulations on completing the initial setup! As a reward ...
Release phase
You've made it! You've setup up your local and remote environments, you've selected your L10n tools and projects, done some localization and even some testing! Now you're ready for the final phase: becoming an official L10n release. Here, we'll continue to stay true to the original intent of this guide and only present you with the technical information you need to become an official release. We'll primarily focus on getting your release repository setup and the Mercurial commands you'll need to know to use that repository. For more information on the release part of the L10n process, visit the Mozilla wiki here. Your official release repository Now that your locale has been registered, the localization files will live on Mozilla Mercurial server at hg.mozilla.org. Depending on which b...
Localization technical reviews
kit/chrome/global/intl.properties. For more info about UTF-7 in Firefox, see bug 441876. More intl.properties checkpoints, cont We also check the plural rule for the locale, that the general.useragent.locale is set to the locale code, that accept-lang shows the locale code(s) (like ab, ab-CD,...) and is followed by en and en-US, and finally that intl.menuitems.insertseparatorbeforeaccesskeys = true, where "true" should be left untranslated. Inspect firefox-l10n.js We ensure that there are no odd preferences, or #filter substitutions for general.useragent.locale. Most locales should have the following: #filter substitution pref("general.useragent.locale", "@AB_CD@") How it all works A large part of the review process takes place before you even submit your request for a technical rev...
gettext
ample, Gaeilge (Irish): Plural-Forms: nplurals=3; plural=n==1 ? 0 : n==2 ? 1 : 2; If n equals 10, the expression n==1 ? 0 : n==2 ? 1 : 2 is evaluated to 2, and so a msgstr[2] should be used. Read more about plurals in gettext at gnu.org. Using context with msgctxt Depending on context in which it is used, one English string might require two or more different translations. This is particularly true for short strings, like "File" or "Log in". For instance, "Log in" as a button label might be translated by a localizer as the imperative, but for a dialog title, the localizer may choose to use a different form, like gerund (much like "Logging in"). Gettext's context feature allows the developer to distinguish between two identical English strings and disambiguate the translation. In the PO file...
Fonts for Mozilla 2.0's MathML engine
/ directory (which may need to be created) on Unix/Linux systems. Alternatively, follow dafont's "How to install a font". These fonts are OpenType PostScript fonts, which are supported by most modern operating systems. However some operating systems may not support these fonts. On such systems, it will be necessary to convert the fonts to a supported format. For example Asana Math is available in TrueType format and there is an unofficial TrueType conversion for STIX fonts. The following fonts are not necessary when the above fonts are installed, but are worth noting because of their Unicode support for many mathematical characters. DejaVu Serif and DejaVu Sans are freely available and installed with many Linux distributions. They contain support for many mathematical characters, and Mozi...
MathML Demo: <mspace> - space
e="decrease height">-</a> Width <a class="control" href="javascript:upwidth();" title="increase width">+</a>/ <a class="control" href="javascript:downwidth();" title="decrease width">-</a> Depth <a class="control" href="javascript:updepth();" title="increase depth">+</a>/ <a class="control" href="javascript:downdepth();" title="decrease depth">-</a> <math display="block"> <mstyle displaystyle="true"> <msqrt> <mrow> <mn>3</mn> <mspace style="background-color: yellow" id="thespace" height="0.1ex" depth="0.1ex" width="0.1em" /> <mi>x</mi> </mrow> </msqrt> </mstyle> </math> </p> JavaScript Content var height=0; var width=0; var depth=0; function upheight() { height++; document.getElementById("thespace").setAttribute("height",height+".1ex"); } function downheight() { height--; docu...
Mozilla Web Developer FAQ
rs show the title attribute in the browser status bar, for example. At this point some people feel compelled to post a "But IE..." rant in the newsgroups or in Bugzilla. Please note that Mac IE 5 behaves in the same way as Mozilla when it comes to the alt and title attributes. Windows IE also shows the title attribute in a tooltip. Does Mozilla support downloadable fonts? Downloadable fonts in TrueType and OpenType formats (.ttf and .otf) are supported since Firefox 3.5. The fonts have to be served from the same origin (protocol, host, port) as the content that uses them unless the fonts are served with the appropriate Cross-Origin Resource Sharing HTTP headers. Downloadable fonts in the EOT format are not supported. If you use downloadable fonts, please make sure the fonts have the right...
Mozilla Style System
ions in the style system. Most callers who interact with the style system do so using the style structs. The style context has a getter for each struct, and nsIFrame, which represents the concept of a CSS box (or rendering object), also has getters that forward to the frame's style context. Thus, typical calling code looks like this: if (aFrame->GetStyleDisplay()->mOpacity < 1.0f) return PR_TRUE; or like this: const nsStylePosition *stylePos = aFrame->GetStylePosition(); if (stylePos->mWidth.GetUnit() == eStyleUnit_Coord) { nscoord w = stylePos->mWidth.GetCoordValue(); ... } else if (stylePos->mWidth.GetUnit() == eStyleUnit_Percent) { ... Rule tree Style data computation CSS style sheet backend Loading Parsing Data structures Cascading HTML Mapped Attribute backen...
JS::PerfMeasurement
Measurement::NUM_MEASURABLE_EVENTS This constant equals the total number of events defined by the API - not necessarily the total number of events that a particular OS allows you to measure. (At time of writing, Linux allows all the above events to be measured, and we don't have back ends for any other operating system. static bool PerfMeasurement::canMeasureSomething() This class method returns true if and only if some -- not necessarily all -- events can be measured by the current build of SpiderMonkey, running on the current OS. At present, it returns true on Linux when the <linux/perf_event.h> API is available (kernel 2.6.31 or later), and false everywhere else. PerfMeasurement::PerfMeasurement(EventMask toMeasure) The constructor creates a new profiling object, which measures some subse...
Memory reporting
gs to note about SizeOfIncludingThis when it is virtual. D::SizeOfIncludingThis is identical to B::SizeOfIncludingThis. You might think that D could just inherit SizeOfIncludingThis from B. In some cases this works, but there's a lot of C++ subtlety involving the aMallocSizeOf(this) and whether this actually points to the start of the allocated object or somewhere in its middle. This is doubly true if D features multiple inheritance. And if aMallocSizeOf is passed a pointer that doesn't point to the start of an object it will give bogus results or even crash. So, if in doubt, define D::SizeOfIncludingThis and you should be safe. The override annotations say that D's methods override the corresponding methods in B. On supporting compilers it gets expanded to the override keyword. It helps p...
Scroll-linked effects
If it is, then it triggers an animation to "snap" the scroll position to the top of the div. ...
browser.altClickSave
The preference browser.altClickSave controls whether clicking a link while holding the alt key starts the download of that link. 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.dom.window.dump.enabled
This setting enables the dump function, which sends messages to the system console. Set it to true to enable it, or false to disable it. Related browser.dom.window.dump.file window.dump ...
browser.dom.window.dump.file
Changes require an application restart. Type:string Default value:none Exists by default: no Application support: Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Status: Active; last updated 2012-03-18 Introduction: Pushed to Nightly on 2009-04-24 Bugs: bug 489938 Values The value holds the file system path for the file in which the content of the window.dump() calls get written, e.g. C:\dump.txt . ...
browser.download.lastDir.savePerSite
browser.download.lastDir.savePerSite controls whether the directory preselected in the file picker for saving a file download is being remembered on a per-website (host) base. If set to true, the data is stored as content preference. Type:boolean Default value:true Exists by default: no Application support:Firefox 11.0 Status: Active; last updated 2012-02-15 Introduction: Pushed to Nightly on 2011-12-11 Bugs: bug 702748 Values true (default) The last used directory for the website (host) serving the file for download will be preselected in the file picker. If no download directory for the current website has been stored, browser.download.lastDir will be used. false The last used directory for any download (stored in browser.download.lastDir) will be the preselected di...
browser.pagethumbnails.capturing_disabled
The preference browser.pagethumbnails.capturing_disabled controls whether the application creates screenshots of visited pages which will be shown if the web page is shown in the grid of the "New Tab Page" (about:newtab) which offers the most often visited pages for fast navigation. Type:boolean Default value:true Exists by default: no Application support: Firefox 14.0 Status: Active; last updated 2012-09-17 Introduction: Pushed to Nightly on 2012-04-13 Bugs: bug 726347 Values false The application creates screenshots of visited web pages. true (default) The application doesn't create screenshots of visited web pages. ...
browser.search.context.loadInBackground
with "Search <search engine> for <selected text>" opening a new tab will give focus to it and load it in the foreground or keep focus on the current tab and open it in the background. 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. ...
browser.urlbar.formatting.enabled
The preference browser.urlbar.formatting.enabled controls whether the domain name including the top level domain is highlighted in the address bar by coloring it black and the other parts grey. Type:boolean Default value: true Exists by default: yes Application support:Firefox 6.0 Status: Active; last updated 2012-04-03 Introduction: Pushed to Nightly on 2011-05-03 Bugs: bug 451833 Values true (default) The domain name including the top level domain is highlighted in the address bar by coloring it black and the other parts grey. false All parts of the url are given the same color: black. ...
dom.event.clipboardevents.enabled
dom.event.clipboardevents.enabled lets websites get notifications if the user copies, pastes, or cuts something from a web page, and it lets them know which part of the page had been selected. The emitting of the oncopy, oncut and onpaste events are controlled by this preference. Type:boolean Default value:true Exists by default: no Application support: Gecko 13.0 (Firefox 13.0 / Thunderbird 13.0 / SeaMonkey 2.10) Status: Active; last updated 2012-02-15 Introduction: Pushed to Nightly on 2012-02-14 Bugs: bug 542938 Values true (default) The oncopy, oncut and onpaste events are enabled for web content. false The oncopy, oncut and onpaste events are disabled for web content. ...
javascript.options.showInConsole
The preference javascript.options.showInConsole controls whether errors or warnings in chrome code are shown in the Error Console. Type:boolean Default value: false (true in debug builds) Exists by default: yes Application support:Firefox 1.0 Status: Active Introduction:2002-02-26 Bugs: bug 125181 bug 337875 Values false Only errors and warnings from content code are shown. true (default) Errors and warnings from both chrome and content are shown in the Error Console. Note: Since the Web Console was introduced in Firefox 4 specifically for debugging content, the default value for this preference has changed to true as of Gecko 2.0. ...
javascript.options.strict
vaScript Console. Example : <html> <head> <title>Sample</title> </head> <body> <label id="name">Enter you First Name</label> <p id ="sample"></p> <script> "use strict" name1= "John" ; // This will cause and an error as variable not declared . var name2= "Peter"; document.getElementById("sample").innerHTML = name1; </script> </body> </html> Possible values and their effects: True: Show JavaScript errors and warnings. False: Show JavaScript errors only. (Default) See also: http://kb.mozillazine.org/Javascript.options.strict ...
mail.tabs.drawInTitlebar
Starting in Thunderbird 17.0, the tabs are drawn in the title bar. The old behavior can be restored by setting the preference mail.tabs.drawInTitlebar to false. Type:boolean Default value: true Exists by default: yes Application support:Thunderbird 17.0 Status: Active; last updated 2012-09-17 Introduction: Pushed to Daily on 2012-08-08 Bugs: bug 771816 Values true (default) The tabs are drawn in the title bar of the mail program. false The tabs are drawn in a separate tab bar, and the title bar shows the title of the current tab (e.g. the subject of the currently selected mail). ...
nglayout.debug.disable_xul_cache
file, which saves a "compiled" version of the XUL and JavaScript in a document to disk for faster startup the next time the application runs. During development of XUL applications, it's convenient to disable the XUL cache so that changes you make to files on disk take effect the next time the window or dialog is loaded (instead of the next time Mozilla starts). Possible values and their effects: True: Do not cache parsed XUL documents and do not save the cache to the XUL FastLoad file on exit; re-read the source files each time the window or dialog needs to be displayed. False: Cache XUL documents in memory and save the cache to disk on exit to improve performance. (Default) See also: http://kb.mozillazine.org/Nglayout.debug.disable_xul_cache ...
nglayout.debug.disable xul fastload
The preference nglayout.debug.disable_xul_fastload controls whether or not XUL fastload is used. Never set nglayout.debug.disable_xul_fastload to true in a production environment; it exists solely to aid in debugging. In particular, add-ons should never change this preference.. Type:boolean Default value: false (true in debug builds) Exists by default: yes Application support:? Status: Active Introduction:? Bugs: Values false (default) XUL fastload is used. true XUL fastload is disabled. ...
reader.parse-on-load.force-enabled
should be enabled independent of the memory available in the device. By default, the reader mode in Firefox Mobile is only enabled if the memory is greater than 384MB. 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). ...
view_source.syntax_highlight
The preference view_source.syntax_highlight controls whether markup in the view source view is syntax highlighted. Type:boolean Default value: true Exists by default: yes Application support:Firefox 1.0 Status: Active Introduction: Bugs: bug 52154 Values true (default) Syntax hightlighting is enabled. false Syntax hightlighting is disabled. ...
A guide to searching crash reports
with that link's value added to the search criteria. A narrower search You can add criteria to perform a narrower search. For example, to perform a search for all Mac crash reports that occurred while JavaScript garbage collection was running, do the following. Add "Mac OS X" to the "Platform" field. Select "New line", and then choose a field ("is garbage collecting") and an operator ("is true"). The operators available for each field depends on its type. With these criteria added the search form looks like the following screenshot. After clicking on "Search" we get results like those in the following screenshot. The number of crash reports matching this search is in the thousands, i.e. much smaller than the previous search. Proto signature The "proto signature" field is just...
Debugging out-of-memory problems
ror (OOM) somewhere during load time. By the time about:memory is loaded in a new tab and you have clicked the "Measure" button to diagnose what's happened, the memory usage causing the spike has gone away, making temporary memory spikes difficult to diagnose. This article explains how to debug such problems. Out-of-memory exceptions from JS Setting memory.dump_reports_on_oom in about:config to true will cause the browser to automatically write about:memory dumps to a temp file printed to the Browser Console (note: not Web Console) when an OOM crash is encountered. For more information, see bug 969415. Out-of-memory crashes In some cases, running out of memory causes the browser to crash. Ideally, memory.dump_reports_on_oom would generate an about:memory dump, but it does not currently. ...
Introduction to NSPR
or modify the monitored data without being in the monitor. Monitoring is about protecting data, not code. A monitored invariant is a Boolean expression over the monitored data. The expression may be false only when a thread is in the monitor (holding the monitor's mutex). This requirement implies that when a thread first enters the monitor, an evaluation of the invariant expression must yield a true. The thread must also reinstate the monitored invariant before exiting the monitor. Therefore, evaluation of the expression must also yield a true at that point in execution. A trivial example might be as follows. Suppose an object has three values, v1, v2, and sum. The invariant is that the third value is the sum of the other two. Expressed mathematically, the invariant is sum = v1 + v2. Any mo...
PL_HashTableRemove
parameters: ht A pointer to the hash table from which to remove the entry. key A pointer to the key for the entry to be removed. Description If there is no entry in the table with the specified key, PL_HashTableRemove returns PR_FALSE. If the entry exists, PL_HashTableRemove removes the entry from the table, invokes freeEntry with the HT_FREE_ENTRY flag to frees the entry, and returns PR_TRUE. If the table is underloaded, PL_HashTableRemove also shrinks the number of buckets by half. Remark This function should return PRStatus. ...
PRBool
Boolean value. 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 standard C++ bool instead. Otherwise, use PRBool for variables and parameter types. Use PR_FALSE and PR_TRUE for clarity of target type in assignments and actual arguments. Use if (bool), while (!bool), (bool) ? x : y, and so on to test Boolean values, just as you would C int-valued conditions. ...
PR_ASSERT
Returns Nothing Description This macro evaluates the specified expression. When the result is zero (FALSE) the application terminates; otherwise the application continues. ...
PR_Initialized
Checks whether the runtime has been initialized. Syntax #include <prinit.h> PRBool PR_Initialized(void); Returns The function returns one of the following values: If PR_Init has already been called, PR_TRUE. If PR_Init has not already been called, PR_FALSE. ...
PR_LOG_TEST
parameters: _module A pointer to a log module structure. _level A level value. Possible values are: PR_LOG_NONE = 0 PR_LOG_ALWAYS = 1 PR_LOG_ERROR = 2 PR_LOG_WARNING = 3 PR_LOG_DEBUG = 4 PR_LOG_NOTICE = PR_LOG_DEBUG PR_LOG_WARN = PR_LOG_WARNING PR_LOG_MIN = PR_LOG_DEBUG PR_LOG_MAX = PR_LOG_DEBUG Returns PR_TRUE when logging is enabled for the given module and level, otherwise PR_FALSE. Description This macro tests whether logging is enabled for the specified module and level. Use it as an expression in a conditional execution statement to control logging. See also PR_LOG. ...
PR_QueueJob
If PR_FALSE, the job is not joinable. See PR_JoinJob. Returns Pointer to a PRJob structure or NULL on error. ...
PR_QueueJob_Accept
If PR_FALSE, the job is not joinable. See PR_JoinJob. Returns Pointer to a PRJob structure or NULL on error. ...
PR_QueueJob_Connect
If PR_FALSE, the job is not joinable. See PR_JoinJob. Returns Pointer to a PRJob structure or NULL on error. ...
PR_QueueJob_Read
If PR_FALSE, the job is not joinable. See PR_JoinJob. Returns Pointer to a PRJob structure or NULL on error. ...
PR_QueueJob_Timer
ameters The function has the following parameters: tpool A pointer to a PRThreadPool structure previously created by a call to PR_CreateThreadPool. iod A pointer to a PRJobIoDesc structure. timeout A value, expressed as a PRIntervalTime, to wait before queuing the job. fn The function to be executed when the job is executed. arg A pointer to an argument passed to fn. joinable If PR_TRUE, the job is joinable. If PR_FALSE, the job is not joinable. See PR_JoinJob. Returns Pointer to a PRJob structure or NULL on error. ...
PR_QueueJob_Write
If PR_FALSE, the job is not joinable. See PR_JoinJob. Returns Pointer to a PRJob structure or NULL on error. ...
PR_STATIC_ASSERT
An expression which cannot be evaluated at compile time will cause a compiler error; see PR_ASSERT for a runtime alternative. Returns Nothing Description This macro evaluates the specified expression. ...
PR_SetConcurrency
hreading model. The M x N model is not available on all host systems. On those where it is not available, PR_SetConcurrency is ignored. Virtual processors are actuallyglobal threads, each of which is designed to support an arbitrary number oflocal threads. Since global threads are scheduled by the host operating system, this model is particularly applicable to multiprocessor architectures, where true parallelism is possible. However, it may also prove advantageous on uniprocessor systems to reduce the impact of having a locally scheduled thread calling incidental blocking functions. In such cases, all the threads being supported by the virtual processor will block, but those assigned to another virtual processor will be unaffected. ...
PR_SetLogFile
Otherwise, PR_FALSE. Description Creates a log file with the specified file name. ...
PR_VersionCheck
offered by the runtime (the exported version). Syntax #include <prinit.h> PRBool PR_VersionCheck(const char *importedVersion); Parameter PR_VersionCheck has one parameter: importedVersion The version of the shared library being imported. Returns The function returns one of the following values: If the version of the shared library is compatible with that expected by the caller, PR_TRUE. If the versions are not compatible, PR_FALSE. Description PR_VersionCheck tests whether the version of the library being imported (importedVersion) is compatible with the running version of the shared library. This is a string comparison of sorts, though the details of the comparison will vary over time. See Also PR_VERSION ...
JSS FAQ
Mozilla › Projects › NSS › JSS › JSS FAQ
you can only have one initialized instance of JSS for each database. Once JSS initialized, I can't get anymore instances with CertificateFactory.getInstance("X.509")? In version previous to JSS 3.1, JSS removes the default SUN provider on startup. Upgrade to the latest JSS, or, in the CryptoManager.InitializationValues object you pass to CryptoManager.initialize(), set removeSunProivider=true. Is it possible to sign data in Java with JSS? What I am trying to do is write a Java applet that will access the Netscape certificate store, retrieve a X509 certificate and then sign some data. The best way to do this is with the PKCS #7 signedData type. Check out the javadoc. How do I convert org.mozilla.jss.crypto.X509Certificate to org.mozilla.jss.pkix.cert.Certificate? impo...
NSS 3.12.5 release_notes
o const unsigned char *. PK11_ConfigurePKCS11 (see nss.h) The name of some parameters have been slightly changed ("des" became "desc"). Deprecated headers The header file key.h is deprecated. Please use keyhi.h instead. Additional documentation In pk11pub.h: The caller of PK11_DEREncodePublicKey should free the returned SECItem with a SECITEM_FreeItem(..., PR_TRUE) call. PK11_ReadRawAttribute allocates the buffer for returning the attribute value. The caller of PK11_ReadRawAttribute should free the data buffer pointed to by item using a SECITEM_FreeItem(item, PR_FALSE) or PORT_Free(item->data) call. In secasn1.h: If both pool and dest are NULL, the caller should free the returned SECItem with a SECITEM_FreeItem(..., PR_TRUE) call. If pool is...
NSS 3.12.6 release notes
t allows clients to continue to renegotiate with vulnerable servers. This value should only be used during the transition period when few servers have been upgraded. NSS_SSL_REQUIRE_SAFE_NEGOTIATION values: 1: requireSafeNegotiation = TRUE unset: requireSafeNegotiation = FALSE Controls whether safe renegotiation indication is required for initial handshake. If TRUE, a connection will be dropped at initial handshake if the peer server or client does not support safe renegotiation. The default setting for this option is FALSE. These optio...
NSS 3.17 release notes
r 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. The SSL_REUSE_SERVER_ECDHE_KEY option defaults to PR_TRUE, which means the server's ephemeral ECDH key is reused for multiple handshakes. This option does not affect the TLS client code, which always generates a fresh ephemeral ECDH key for each handshake. New Macros in ssl.h SSL_REUSE_SERVER_ECDHE_KEY Notable Changes in NSS 3.17 The manual pages for the certutil and pp tools have been updated to document the new parameters that had bee...
NSS 3.34 release notes
hen using certutil, to set an inacceptable password in FIPS mode, a correct explanation of acceptable passwords will be printed. SSLKEYLOGFILE is now supported with TLS 1.3, see Bug 1287711 for details. SSLChannelInfo has two new fields (Bug 1396525) SSLNamedGroup originalKeaGroup holds the key exchange group of the original handshake, when the session was resumed. PRBool resumed is PR_TRUE when the session is resumed, and PR_FALSE otherwise. RSA-PSS signatures are now supported on certificates. Certificates with RSA-PSS or RSA-PKCS#1v1.5 keys can be used to create an RSA-PSS signature on a certificate, using the --pss-sign argument to certutil. New Functions Bugs fixed in NSS 3.34 This Bugzilla query returns all the bugs fixed in NSS 3.34: https://bugzilla.mozilla.org/b...
NSS Sample Code sample5
_ConvertAsciiToItem failed %d\n", PR_GetError()); goto cleanup; } /* KU_ALL includes a lot of different key usages, KU_DATA_ENCIPHERMENT * is enough for just RSA encryption. ...
NSS Sample Code sample6
id; keyiditem.type = siBuffer; keyiditem.data = (void *)keyid; keyiditem.len = sizeof(keyid[0]); /* Note: keysize must be 0 for fixed key-length algorithms like DES. ...
Python binding for NSS
will probablby just print the string representation of the returned CertVerifyLog object. Cert validation logging is handled by the Certificate.verify() method. Support has also been added for the various key usage and cert type entities which feature prominently during cert validation. Certificate() constructor signature changed from Certificate(data=None, der_is_signed=True) to Certificate(data, certdb=cert_get_default_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. It's is not likely that an previous code was failing to pass initialization data or the der_is_signed flag so this change should be backwards compa...
FC_GetSessionInfo
ser role). If the NSS cryptographic module is in the error state, FC_GetSessionInfo returns CKR_DEVICE_ERROR. Otherwise, it fills in the CK_SESSION_INFO structure with the following information: state: the state of the session, i.e., no role is assumed, the User role is assumed, or the Crypto Officer role is assumed flags: bit flags that define the type of session CKF_RW_SESSION (0x00000002): true if the session is read/write; false if the session is read-only. CKF_SERIAL_SESSION (0x00000004): this flag is provided for backward compatibility and is always set to true. Return value Examples See also FC_CloseSession, NSC_OpenSession ...
FC_GetSlotList
pSlotList [out] Either null or a pointer to an existing array of CK_SLOT_ID objects. ...
FC_GetTokenInfo
CKF_LOGIN_REQUIRED (0x00000004): this device requires the user to log in to use some of its services CKF_USER_PIN_INITIALIZED (0x00000008): the user's password has been initialized CKF_DUAL_CRYPTO_OPERATIONS (0x00000200): a single session with the token can perform dual cryptographic operations CKF_TOKEN_INITIALIZED (0x00000400): the token has been initialized. If login is required (which is true for the FIPS mode of operation), this flag means the user's password has been initialized. ulSessionCount: number of sessions that this application currently has open with the token ulRwSessionCount: number of read/write sessions that this application currently has open with the token hardwareVersion: hardware version number, for example, 8.3 (major=0x08, minor=0x03), which are the version nu...
NSS environment variables
n using leak reporting software. 3.11.8 NSS_ENABLE_AUDIT Boolean (1 to enable) Enable auditing of activities of the NSS cryptographic module in FIPS mode. Audit Data 3.11.2 NSS_ENABLE_PKIX_VERIFY Boolean (any non-empty value to enable) Use libPKIX, rather than the old cert library, to verify certificates. 3.12 NSS_FIPS String ("fips","true","on","1") Will start NSS in FIPS mode. 3.12.5 NSS_HASH_ALG_SUPPORT String Specifies agorithms allowed to be used in certain applications, such as in signatures on certificates and CRLs. See documentation at this link. 3.12.3 NSS_OUTPUT_FILE String (filename) Output file path name for the PKCS #11 Module Logger. Default is stdout. 3.7 NSS_SDB...
sslcrt.html
incx); Parameters This function has the following parameters: handle A pointer to the certificate database handle. cert A pointer to the certificate to be checked. checkSig Indicates whether certificate signatures are to be checked. PR_TRUE means certificate signatures are to be checked. PR_FALSE means certificate signatures will not be checked. certUsage One of these values: certUsageSSLClient certUsageSSLServer certUsageSSLServerWithStepUp certUsageSSLCA certUsageEmailSigner certUsageEmailRecipien...
Necko Architecture
hannels. It does this by looking up the protocol handler and asking it to create the channel. The primary responsibility of protocol handlers is to create channel instances that know how to interpret the protocol that the handler registered for. However, a protocol handler implementation also might "cache" the underlying transports so channels it creates can reuse them later. The channel does the true work of protocol interpretation and data movement (if any). Although the protocol handler creates channels, protocol interpretation doesn't begin until the user initiates the transaction using the nsIChannel API. Receiving data & nsIStreamListener You can read or write, from or to a channel using either the synchronous API, or the asynchronous API. If you want to move data asynchronously you n...
Pork Tools
ar); //case 3: nsresult decl nsresult rv2 = Getter(&var); NS_ENSURE_SUCCESS(rv2,rv2); } caller1 { // case 1 // figure out that rv was only used for the rewritten // outparam call + NS_ENSURE_SUCCESS. Then nuke the declaration // nsresult rv; // move outparam to lhs var = Getter(); // detect NS_ENSURE_SUCCESS immediately following // and change it to an equivalent NS_ENSURE_TRUE NS_ENSURE_TRUE(var, NS_ERROR_FAILURE); // case 2 var = Getter(); // case 3, eliminate rv2 decl given that it's not used elsewhere var = Getter(); NS_ENSURE_TRUE(var, NS_ERROR_FAILURE) } Outparamdel also support rewriting getters such that they return already_AddRefed<nsIFoo>. In this case all of the callsites are modified to: a) getter_AddRefs case: getter(getter_AddRef...
Small Footprint
.jar Ant build script in Rhino supports smalljar target that will generate smalljs.jar that does not include Tools, Optimizer, JavaAdapter and Class generation library, Regular Expressions, E4X implementataion and deprecated files. To build such minimalist jar without debug information, run the following command from the top directory of Rhino distribution: ant clean ant -Ddebug=off -Dno-regexp=true -Dno-e4x=true smalljar If you omit -Dno-regexp=true, then the resulting smalljs.jar will include Regular Expression support. Similarly omitting -Dno-e4x=true results in smalljs.jar that includes runtime support for E4X. ...
Rhino shell
or 170. See JavaScript Language Versions for more information on language versions. -strict Enable strict mode. -continuations Enable experimental support for continuations and set the optimization level to -1 to force interpretation mode. Starting with Rhino 1.7 this options is no longer available. Note If the shell is invoked with the system property rhino.use_java_policy_security set to true and with a security manager installed, the shell restricts scripts permissions based on their URLs according to Java policy settings. This is available only if JVM implements Java2 security model. Predefined Properties Scripts executing in the shell have access to some additional properties of the top-level object. arguments The arguments object is an array containing the strings of all the a...
SpiderMonkey Build Documentation
Refer the release notes under Command Line Tools -> New Features The release notes also states that this compatibility package will no longer be provided in the near future, so the build system on macOS will have to be adapted to look for headers in the SDK Until then, the following should help, open /L...
Hacking Tips
truction, you can use in visit function of each instruction the JSScript filename in lineno fields as well as the id() of the LIR / MIR instructions. The JSScript can be obtained from info().script(). bool CodeGeneratorX86Shared::visitGuardShape(LGuardShape *guard) { if (info().script()->lineno == 16934 && guard->id() == 522) { [... another impl only for this one ...] return true; } [... old impl ...] [Hack] Spewing all compiled code I usually just add this to the apropriate executableCopy. if (getenv("INST_DUMP")) { char buf[4096]; sprintf(buf, "gdb /proc/%d/exe %d -batch -ex 'set pagination off' -ex 'set arm force-mode arm' -ex 'x/%di %p' -ex 'set arm force-mode auto'", getpid(), getpid(), m_buffer.size() / 4, buffer); system(buf)...
How to embed the JavaScript engine
ne DOIT_MINARGS 2 // [SpiderMonkey 24] Use JSBool instead of bool. static bool doit(JSContext *cx, unsigned argc, jsval *vp) { JS::CallArgs args = CallArgsFromVp(argc, vp); /* * Look in argv for argc actual parameters, set *rval to return a * value to the caller. * * ex. Add two arguments as integer. * args.rval().setInt32(args[0].toInt32() + args[1].toInt32()); */ return true; } Then to wire it up to JS, you could write: ok = JS_DefineFunction(cx, global, "doit", doit, DOIT_MINARGS, 0); Or, if you had a bunch of native functions to define, you would probably put them in a table: static JSFunctionSpec my_functions[] = { JS_FN("doit", doit, DOIT_MINARGS, 0), /* etc... */ JS_FS_END }; JS_FS_END terminates the table. And say: ok = JS_DefineFunctions(cx, glo...
Exact Stack Rooting
available, even if it is not used. Since it is never correct to implicitly copy a js::RootedT (more on this in a second) we have deleted the copy constructor from these classes. Therefore, we are forced to force you to initialize with constructor syntax. Sorry. Note 2: In C++, destructors are required to run in declaration order, nicely maintaining our LIFO property. However, this does not hold true for temporaries: they are undeclared, after all. Some compilers maintain LIFO order, some do not. Incorrect use of js::RootedT as a temporary will crash at run time. There is also a static constructor method fromMarkedLocation() that creates a Handle from an arbitrary location. This is used to make Handles for things like scope chain objects, which aren't explicitly rooted themselves, but are a...
Statistics API
N API Addons can obtain the complete data in JSON format via an observer. The following adds an observer using the JetPack framework. 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. total_time: number (milliseconds) - The amount of wall time that this GC consumed. Note: this is the sum of all the slice durations, not end time - start time. compartments_collecte...
Property cache
he new property can be created simply by calling JSScope::extend, but there are many special cases and pitfalls to watch out for. When a prototype gains a property that could invalidate an entry of this type, rt->protoHazardShape is bumped, effectively marking all such entries invalid at once. Entry value words For the .vword member of a non-adding property cache entry, one of the following is true: vword.isShape() vword.toShape() points to the js::Shape that describes the property in question. This is the default type of vword generated when neither of the two special cases below applies. A cache hit of this type saves a property lookup, but the interpreter still has to examine vword.toShape() to determine what to do next. vword.isSlot() The property has a slot which the interp...
SpiderMonkey Internals
g that JavaScript NaN must be represented as one canonical NaN format). Other values are encoded as a value and a type tag: On x86, ARM, and similar 32-bit platforms, we use what we call "nunboxing", in which non-double values are a 32-bit type tag and a 32-bit payload, which is normally either a pointer or a signed 32-bit integer. There are a few special values: NullValue(), UndefinedValue(), TrueValue() and FalseValue(). On x64 and similar 64-bit platforms, pointers are longer than 32 bits, so we can't use the nunboxing format. Instead, we use "punboxing", which has 17 bits of tag and 47 bits of payload. Only JIT code really depends on the layout--everything else in the engine interacts with values through functions like val.isDouble(). Most parts of the JIT also avoid depending direct...
Introduction to the JavaScript shell
t8Array, otherwise returns an UTF-8 decoded string. readline() Reads a single line of input from stdin, returning it to the caller. You can use this to create interactive shell programs in JavaScript. Reflect.parse() See Parser API. Note: This function is intended only for use when testing the JavaScript engine. seal(object[, deep]) Seals the specified object, or an object graph if deep is true. By sealing an object or object graph, you disable modification of those objects. sleep(dt) Added in SpiderMonkey 1.8 Only in JS_THREADSAFE builds. Sleep for dt seconds. Fractions of a second are supported. Returns true on success, false if the sleep was interrupted. stackQuota([number]) Get or set the script stack quota. throwError() Throws an error from the JS_ReportError() function. N...
JIT Optimization Strategies
ation makes the assumption that a property that has not changed after it was first assigned, is likely a constant property. It then directly inlines the value of the property into hot code that accesses it. For example, in the following code: var Constants = {}; Constants.N = 100; function testArray(array) { for (var i = 0; i < array.length; i++) { if (array[i] > Constants.N) return true; } return false; } Will have the loop compiled into the following when testArray gets hot. for (var i = 0; i < array.length; i++) { if (array[i] > 100) return true; } When this optimization is successful, property access is eliminated entirely and replaced with an inline constant. GetProp_Constant Attempts to optimize reading a property that contains a uniquely-typed (or "singlet...
BOOLEAN_TO_JSVAL
Obsolete since JSAPI 42This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Cast a C integer to a boolean JS::Value without any type checking or error handling. Please use JS::BooleanValue/JS::TrueValue/JS::FalseValue instead in SpiderMonkey 45 or later. Syntax jsval BOOLEAN_TO_JSVAL(bool b); Name Type Description b bool C integer value to be converted to a boolean jsval. Description BOOLEAN_TO_JSVAL converts a bool argument, b, to a boolean jsval. If b is false, the result is JSVAL_FALSE. If b is true, the result is JSVAL_TRUE. See Also MXR ID Search for BOOLEAN_TO_JSVAL JS::BooleanValue bug 1177892 -- removed ...
INT_FITS_IN_JSVAL
d at any time. Try to avoid using it. Determines if a specified C integer is safe to pass to INT_TO_JSVAL. Syntax #define INT_FITS_IN_JSVAL(i) /* ... */ Name Type Description i jsint The C integer value to check. Description Determines if a specified C integer value, i, lies within the range allowed for integer jsvals. If so, INT_FITS_IN_JSVAL returns TRUE, and i can be cast to jsval by calling INT_TO_JSVAL(i). Otherwise, INT_FITS_IN_JSVAL returns FALSE. In this case, the application can still convert i to a jsval using JS_NewNumberValue. Warning: The type of the argument i must be jsint, but the C/C++ compiler does not enforce type safety here. If i is an unsigned or 64-bit value, INT_FITS_IN_JSVAL can silently give the wrong answer. Starting in...
JS::Add*Root
a static string constant, identifying the source location of the call to JS::AddNamed*Root for debugging purposes. Needs the Example for typical usage of the name parameter. All the JS::Add*Root methods are idempotent: multiple calls for the same address will add only one root. Correspondingly, only a single JS::Remove*Root is required to unroot the location. On success, these functions return true. Otherwise they report an out of memory error and return false. See Also MXR ID Search for JS::AddValueRoot MXR ID Search for JS::AddStringRoot MXR ID Search for JS::AddObjectRoot MXR ID Search for JS::AddNamedValueRoot MXR ID Search for JS::AddNamedValueRootRT MXR ID Search for JS::AddNamedStringRoot MXR ID Search for JS::AddNamedObjectRoot MXR ID Search for JS::AddNamedScriptRoot bu...
JS::AutoIdArray
JSContext *cx, JSIdArray *ida); Name Type Description cx JSContext * The context in which to add the root. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. ida JSIdArray * A pointer to JSIdArray to take the ownership. Methods Method Description bool operator!() const Return true if this has no owned array. jsid operator[](size_t i) const Return a jsid in specified index of the owned array. size_t length() const Return the length of the owned array. JSIdArray *steal() Return the owned array and release the ownership. Description JS::AutoIdArray takes the ownership of JSIdArray, and frees it in destructor by calling JS_DestroyIdA...
JS::BooleanValue
features introduced in SpiderMonkey 24 Convert a C boolean of type bool to a JS::Value. Syntax JS::Value JS::BooleanValue(bool boo) Name Type Description boo bool C bool to convert. Description JS::BooleanValue converts a C boolean of type bool to JS::Value, the type of JavaScript values. See Also MXR ID Search for JS::BooleanValue JS::Value JS::TrueValue JS::FalseValue ...
JS::Compile
cript. length indicates the size of the text version of the script in characters. file is the filehandle containing the text of the script. filename is the name of the file (or URL) containing the script. This information is included in error messages if an error occurs during compilation.. On success, JS::Compile stores an object representing the newly compiled script into script, and returns true. Otherwise, it returns false and the value left in script is undefined. See Also The JSAPI User Guide contains example code using compiled scripts. MXR ID Search for JS::Compile JS::Evaluate JS::CompileOffThread JS::CompileFunction JS_DecompileScript bug 771705 bug 1143793 -- removed obj parameter ...
JS::CompileFunction
lement of an array of names to assign each argument. The number of argument names should match the number of arguments specified in nargs. chars, bytes, or srcBuf is a string containing the source code of the function. length is the length of the source code in characters. On success, JS::CompileFunction stores an function object representing the newly compiled function into fun and and returns true. Otherwise, it returns false and the value left in fun is undefined. See Also The JSAPI User Guide contains example code using compiled scripts. MXR ID Search for JS::CompileFunction JS::Evaluate JS::Compile JS::CompileOffThread JS_ExecuteScript JS_DecompileScript bug 771705 ...
JS::CreateError
JSErrorReport * A pointer to JSErrorReport instance. message JS::HandleString The value of Error.prototype.message. rval JS::MutableHandleValue Out parameter. Receives the created error object. Description JS::CreateError creates an Error object with specified properties. If successful, JS::CreateError stores the created error object to *rval and returns true, otherwise returns false and the value of *rval is undefined. See Also MXR ID Search for JS::CreateError JSExnType JSErrorReport bug 984048 bug 1038238 -- change stack parameter from JS::HandleString to JS::HandleObject ...
JS::Evaluate
e way as for the standard eval function. In the common case where the script is just an expression, the result value is simply the value of that expression. More generally, the result value is the value of the last-executed expression statement in the script that isn't in a function. If a script compiles and executes successfully, JS::Evaluate stores the result in *rval, if non-null, and returns true. Otherwise it returns false and the value left in *rval is undefined. See Also MXR ID Search for JS::Evaluate JS::Compile JS_ExecuteScript bug 771705 bug 1097987 -- remove obj parameter ...
JS::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 ...
JS::GetFirstArgumentAsTypeHint
fs CallArgs The arguments of the function call. behavior JSType * Receives the result of conversion. See below. Description JS::GetFirstArgumentAsTypeHint converts first argument of @@toPrimitive method to JSType. If args.get(0) is one of the strings "string", "number", or "default", set *result to JSTYPE_STRING, JSTYPE_NUMBER, or JSTYPE_VOID accordingly and return true. Otherwise, return false with a TypeError pending. See Also MXR ID Search for JS::GetFirstArgumentAsTypeHint bug 1054756 - added ...
JS::NullHandleValue
This article covers features introduced in SpiderMonkey 24 The JS::Value that represents the JavaScript value null. Syntax const JS::HandleValue JS::NullHandleValue; Description JS::NullHandleValue is a JS::HandleValue constant that represents the JavaScript value null. See Also MXR ID Search for JS::NullHandleValue JS::UndefinedHandleValue JS::TrueHandleValue JS::FalseHandleValue bug 865969 ...
JS::OrdinaryToPrimitive
ied in ES6 draft rev 28 (2014 Oct 14) 7.1.1, second algorithm. Most users should not call this -- use JS::ToNumber, JS::ToBoolean, or JS::ToString instead. This should only be called from custom convert hooks. It implements the default conversion behavior shared by most objects in JS, so it's useful as a fallback. On success, JS::OrdinaryToPrimitive stores the converted value in *vp and returns true. On error or exception, it returns false, and the value left in *vp is undefined. See Also MXR ID Search for JS::OrdinaryToPrimitive JS::ToNumber JS::ToBoolean JS::ToString bug 1103152 ...
JS::PropertySpecNameEqualsId
ol JS::PropertySpecNameEqualsId(const char *name, JS::HandleId id); Name Type Description name const char * JSPropertySpec::name or JSFunctionSpec::name. id JS::HandleId A jsid to compare with. Description JS::PropertySpecNameEqualsId determines if the given JSPropertySpec::name or JSFunctionSpec::name value equals the given jsid, and returns true if so. See Also MXR ID Search for JS::PropertySpecNameEqualsId JS::PropertySpecNameIsSymbol JS::PropertySpecNameToPermanentId JSPropertySpec JSFunctionSpec bug 1082672 ...
JS::PropertySpecNameIsSymbol
See Also MXR ID Search for JS::PropertySpecNameIsSymbol JS::PropertySpecNameEqualsId JS::PropertySpecNameToPermanentId JSPropertySpec JSFunctionSpec bug 1082672 ...
JS::ToInt32
his JSContext. v JS::HandleValue The value to convert. out int32_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt32 converts a JavaScript value to a signed 32bit integer. It implements the ToInt32 operator described in ECMA 262-3 ?9.5. On success, JS::ToInt32 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is undefined. See Also MXR ID Search for JS::ToInt32 bug 739541 ...
JS::ToInt64
t. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. out int64_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt64 converts a JavaScript value to a signed 64bit integer. On success, JS::ToInt64 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is undefined. See Also MXR ID Search for JS::ToInt64 bug 742188 ...
JS::ToNumber
request on this JSContext. v JS::HandleValue The value to convert. out double * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToNumber converts a JavaScript value to a number. It implements the ToNumber operator described in ECMA 262-3 ?9.3. On success, JS::ToNumber stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is undefined. See Also MXR ID Search for JS::ToNumber bug 739541 ...
JS::ToPrimitive
ass the corresponding type as a hint, or JSTYPE_VOID to pass no hint. Do not pass any other type. vp JS::MutableHandleObject Out parameter. On success, *vp receives the converted value. Description JS::ToPrimitive converts a JavaScript object, obj, to a primitive value using ECMAScript 6 ToPrimitive. On success, JS::ToPrimitive stores the converted value in *vp and returns true. On error or exception, it returns false, and the value left in *vp is undefined. See Also MXR ID Search for JS::ToPrimitive JS::GetFirstArgumentAsTypeHint JS_DefaultValue -- old name of this function bug 1054756 - added ...
JS::ToString
*cx, JS::HandleValue v) Name Type Description cx JSContext * The context in which to perform the conversion. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. Description JS::ToString returns a string representation of a JavaScript value. If v.isString() is true, it calls v.toString(). Otherwise, it converts the value to string. On success, JS::ToString returns a JSString instance. On error or exception, it returns nullptr. See Also MXR ID Search for JS::ToString bug 933834 ...
JS::ToUint16
JSContext. v JS::HandleValue The value to convert. out uint16_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt16 converts a JavaScript value to an unsigned 16bit integer. It implements the ToInt16 operator described in ECMA 262-3 ?9.7. On success, JS::ToInt16 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is undefined. See Also MXR ID Search for JS::ToUint16 bug 779601 ...
JS::ToUint32
Context. v JS::HandleValue The value to convert. out int32_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToUint32 converts a JavaScript value to an unsigned 32bit integer. It implements the ToUint32 operator described in ECMA 262-3 ?9.5. On success, JS::ToUint32 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is undefined. See Also MXR ID Search for JS::ToUint32 bug 739541 ...
JS::ToUint64
n a JS_THREADSAFE build, the caller must be in a request on this JSContext. v JS::HandleValue The value to convert. out uint64_t * Out parameter. On success, *out receives the converted floating-point value. Description JS::ToInt64 converts a JavaScript value to an unsigned 64bit integer. On success, JS::ToInt64 stores the converted value in *out and returns true. On error or exception, it returns false, and the value left in *out is undefined. See Also MXR ID Search for JS::ToUint64 bug 742188 ...
JS::UndefinedHandleValue
This article covers features introduced in SpiderMonkey 24 The JS::Value that represents the JavaScript value undefined. Syntax const JS::HandleValue JS::UndefinedHandleValue; Description JS::UndefinedHandleValue is a JS::HandleValue constant that represents the JavaScript value undefined. See Also MXR ID Search for JS::UndefinedHandleValue JS::NullHandleValue JS::TrueHandleValue JS::FalseHandleValue bug 865969 ...
JSAutoByteString
wnership of the returned string, and return the string. void clear() Free the owned string. You should call this before calling encode* methods or initBytes method if a string is already owned, otherwise the string will never be freed. char *ptr() const Return a pointer to the owned string. This could be NULL if no string is owned. bool operator!() const Return true if no string is owned. size_t length() const Return the length of the owned string. Return 0 if no string is owned. Description JSAutoByteString takes the ownership of string and frees it in destructor. If JSAutoByteString instance is initialized with JSAutoByteString bytes(cx, str); style, it calls JS_EncodeString(cx, str) to get the string to take ownership. If JSAutoByteS...
JSBool
Obsolete since JSAPI 26This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Every instance of JSBool has been replaced by bool. JS_TRUE has been replaced by just true and in the same way JS_FALSE by false. JSBool is the return type of many JSAPI functions and callbacks. JS_TRUE indicates success; JS_FALSE indicates an error or exception occurred. JSBool is an integer type. JS_TRUE is (JSBool) 1 and JS_FALSE is (JSBool) 0. These values must not be used as jsvals. Instead, use JSVAL_TRUE and JSVAL_FALSE, and use BOOLEAN_TO_JSVAL and JSVAL_TO_BOOLEAN to convert. ...
JSCheckAccessOp
e properties are being accessed. id jsval The name or index of the property being accessed. mode JSAccessMode The type of access being checked. vp jsval * Out parameter. On success, the callback must set *vp to the stored value of the property. Description Check whether obj[id] may be accessed per mode, returning JS_FALSE on error/exception, JS_TRUE on success with obj[id]'s stored value in *vp. As for JSPropertyOp, id is either a string or an int jsval. JSCheckAccessOp implementations generally work by using JSDBGAPI functions such as JS_FrameIterator and JS_StackFramePrincipals to obtain the principals of the code attempting the checked operation, then examining those principals and comparing them with the system's security policy. The na...
JSClass.flags
ances. An object obj that emulates undefined behaves like any other object, except in the following ways: typeof obj === "undefined" obj converts to false when obj is converted to a boolean when used in boolean contexts (if conditions, loop continuation/termination conditions [for/while/do { } while], the condition in a ternary ?: expression, and so on) (obj == undefined) is true, and (obj != undefined) is false (obj == null) is true, and (obj != null) is false == and != comparisons to values other than null or undefined (including to an object that emulates undefined) are unaffected by this flag. Strict equality (=== and !==) comparisons are also unaffected by this flag. MXR ID Search for JSCLASS_EMULATES_UNDEFINED JSCLASS_HAS_RESER...
JSClass
* JSObject *obj = JS_NewObjectForConstructor(cx, &printer_class, vp); */ if (!obj) return false; MyPrinter *p = new MyPrinter; if (p == NULL) { JS_ReportOutOfMemory(cx); return false; } JS_SetPrivate(cx, obj, p); args.rval().setObject(*obj); /* SpiderMonkey 31 or older * JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(obj)); */ return true; } { JS_InitClass(cx, global, JS::NULL(), &printer_class, printer_construct, 1, NULL, NULL, NULL, NULL); } See also MXR ID Search for JSClass JSClass.flags JS_GetClass JS_InitClass JS_NewObject JS_NewObjectForConstructor JS_InstanceOf bug 638291 - added trace bug 702507 - removed JSCLASS_CONSTRUCT_PROTOTYPE bug 726944 - removed xdrObject, reserved0 and reserved1 b...
JSConvertOp
rimitive value in *vp. Implementations of this hook have historically been required to accept any type. However, the engine itself only requires support for JSTYPE_STRING, JSTYPE_NUMBER, and JSTYPE_VOID, if JS_ConvertValue is not used. If you do not use the JS_ConvertValue method, you may omit support for other types. (Support for the other types may eventually be removed.) The callback returns true to indicate success or false to indicate failure. JSClass hooks JSClass offers the following hook: The JSClass.convert callback implements the [[DefaultValue]] behavior for objects having that class. See Also MXR ID Search for JSConvertOp JSClass ...
JSErrorReport
ld the text that generated the error condition. Set linebuf to point at the buffer before your application executes a script. For Unicode scripts, define a second buffer that holds the Unicode version of the text the generated the error. For application that do not use Unicode, set uclinebuf and uctokenptr to NULL. Macros Name Description JSREPORT_IS_WARNING(flags) Returns true if flags has JSREPORT_WARNING. JSREPORT_IS_EXCEPTION(flags) Returns true if flags has JSREPORT_EXCEPTION. JSREPORT_IS_STRICT(flags) Returns true if flags has JSREPORT_STRICT. JSREPORT_IS_STRICT_MODE_ERROR(flags) Returns true if flags has JSREPORT_STRICT_MODE_ERROR. See Also MXR ID Search for JSErrorReport JS_ReportError JS_ReportWarning JS_ReportOutO...
JSFastNative
turns the argv pointer. This points to element 0 of an array of argc jsvals, the arguments supplied by the caller. JS_RVAL(cx, vp) Returns the jsval that is currently in the return-value slot. JS_SET_RVAL(cx, vp, value) Sets the return value of the native function. It is safe to call this multiple times within a single call to a JSFastNative. If the JSFastNative returns JS_TRUE, the last value passed to this macro will be returned to the caller. On success, the callback must call JS_SET_RVAL (at least once) and return JS_TRUE. On error or exception, it must return JS_FALSE. To create a JSFunctionSpec that points to a JSFastNative, use JS_FN. When a JSFastNative is called, no JSStackFrame is generated. This is what makes a fast native fast. However, it causes t...
JSHasInstanceOp
e check is occurring. obj JS::HandleObject The "type" in the type check. v JS::MutableHandleValue The value whose type is being checked. bp bool * Out parameter. On success, the callback stores the result of the type check in *bp. Description JSHasInstanceOp is called to check whether v is an instance of obj. Return false on error or exception, true on success with true in *bp if v is an instance of obj, false in *bp otherwise. JSClass hooks JSClass offers the following hook: The JSClass.hasInstance callback implements JS_HasInstance and the JavaScript instanceof keyword. See Also MXR ID Search for JSHasInstanceOp JSClass JS_HasInstance ...
JSID_IS_GCTHING
Testing and conversion functions between a JS ID and a GC thing. Syntax bool JSID_IS_GCTHING(jsid id); JS::GCCellPtr JSID_TO_GCTHING(jsid id); Name Type Description id jsid The property identifier to test or convert. Description JSID_IS_GCTHING tests whether a specified JS ID, id, is a GC thing, and returns true if it's a GC thing. JSID_TO_GCTHING converts a specified JS ID, id to a GC thing. See Also MXR ID Search for JSID_IS_GCTHING MXR ID Search for JSID_TO_GCTHING ...
JSID_IS_INT
integer. Syntax bool JSID_IS_INT(jsid id); int32_t JSID_TO_INT(jsid id); bool INT_FITS_IN_JSID(int32_t i); jsid INT_TO_JSID(int32_t i); Name Type Description id jsid The property identifier to test or convert. i int32_t An integer to test or convert. Description JSID_IS_INT tests whether a specified JS ID, id, is an integer, and returns true if it's an integer. JSID_TO_INT converts a specified JS ID, id to an integer. INT_FITS_IN_JSID tests whether a specified integer fits in jsid, it means the integer value is not negative. INT_TO_JSID converts a specified integer, i to a jsid. See Also MXR ID Search for JSID_IS_INT MXR ID Search for JSID_TO_INT MXR ID Search for INT_FITS_IN_JSID MXR ID Search for INT_TO_JSID ...
JSID_IS_STRING
* Pointer to a JS context from which to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. id jsid The property identifier to test or convert. str JSString * An interned string to convert to an id. Description JSID_IS_STRING tests whether a specified JS ID, id, is a string, and returns true if it's a string. JSID_TO_STRING converts a specified JS ID, id to a JSString *. INTERNED_STRING_TO_JSID converts a specified interned string, str to a jsid. JSID_TO_FLAT_STRING converts a specified JS ID, id to a JSFlatString *. See Also MXR ID Search for JSID_IS_STRING MXR ID Search for JSID_TO_STRING MXR ID Search for INTERNED_STRING_TO_JSID MXR ID Search for JSID_TO_FLAT_STRING bug...
JSID_IS_SYMBOL
a JS Symbol. Syntax bool JSID_IS_SYMBOL(jsid id); JS::Symbol * JSID_TO_SYMBOL(jsid id); jsid SYMBOL_TO_JSID(JS::Symbol *sym); Name Type Description id jsid The property identifier to test or convert. sym JS::Symbol A JS Symbol to test or convert. Description JSID_IS_SYMBOL tests whether a specified JS ID, id, is a JS Symbol, and returns true if it's a JS Symbol. JSID_TO_SYMBOL converts a specified JS ID, id to a JS Symbol. SYMBOL_TO_JSID converts a specified JS Symbol, i to a jsid. See Also MXR ID Search for JSID_IS_SYMBOL MXR ID Search for JSID_TO_SYMBOL MXR ID Search for SYMBOL_TO_JSID bug 645416 ...
JSIteratorOp
ed in SpiderMonkey 1.8 Callback for creating iterators. Syntax typedef JSObject * (*JSIteratorOp)(JSContext *cx, JSObject *obj, JSBool keysonly); Name Type Description cx JSContext * Pointer to the JS context in which the iterator creation should take place. obj JSObject * Pointer to the object to iterate over. keysonly JSBool If true, the iterator should yield keys only, not [key, value] pairs. Description The JavaScript engine calls the JSExtendedClass.iteratorObject callback to create an iterator object for a given object. The callback should return an iterator object or NULL if an error or exception occurred on cx. See Also bug 909178 ...
JSNative
ented using a JS::CallArgs structure Added in SpiderMonkey 17. (This structure is now provided in "js/CallArgs.h" Added in SpiderMonkey 24 as well as through "jsapi.h".) This structure encapsulates access to the callee function, this, the function call's arguments, and the eventual return value. On success, the callback must set JS::CallArgs::rval() or call JS_SET_RVAL (at least once) and return true. Otherwise it should either report an error (using e.g. JS_ReportError or JS_ReportOutOfMemory) or raise an exception (using JS_SetPendingException), and the callback must return false. (Returning false without reporting an error or raising an exception terminates the script with an uncatchable error. This has limited use cases; it's used to implement Firefox's "slow script" dialog, for example.)...
JSNewResolveOp
he resolve hook must set *objp to the object in which the property has been defined, or NULL if it was not defined. Description Like JSResolveOp, but flags provide contextual information about the property access. On success, the callback must set the *objp out parameter to null if id was not resolved; or non-null, referring to obj or one of its prototypes, if id was resolved; and return JS_TRUE. On failure, it must return JS_FALSE. This hook instead of JSResolveOp is called via the JSClass.resolve member if JSCLASS_NEW_RESOLVE is set in JSClass.flags. Setting JSCLASS_NEW_RESOLVE and JSCLASS_NEW_RESOLVE_GETS_START further extends this hook by passing in the starting object on the prototype chain via *objp. Thus a resolve hook implementation may define the property id being resolved in th...
JSObjectOps.defaultValue
icit conversion of the operands using [[DefaultValue]]. The default [[DefaultValue]] behavior for ordinary objects is as described in ES5 ?8.12.8. It calls the JavaScript methods obj.valueOf() and/or obj.toString(). Provide a custom JSObjectOps.defaultValue callback to implement customized [[DefaultValue]] behavior. The JSClass.convert callback should convert obj to the given type, returning JS_TRUE with the resulting value in *vp on success, and returning JS_FALSE on error or exception. On success, *vp must be a primitive value: per ES5 ?8.12.8, every object "must ensure that its [[DefaultValue]] internal method can return only primitive values." Debug builds of SpiderMonkey will assert if a convert callback is successful but leaves *vp holding a primitive value. JS_ConvertStub implements ...
JSObjectOps.getAttributes
id jsid The name or index of the property whose attributes are being accessed. prop JSProperty * The property whose attributes are being accessed. This may be NULL. attrsp unsigned int * In/out parameter. See the Description section below. Description Get or set attributes of the property obj[id]. Returns JS_FALSE on error or exception, else JS_TRUE with current attributes in *attrsp. If prop is non-null, it must come from the *propp out parameter of a prior JSObjectOps.defineProperty or JSObjectOps.lookupProperty call. For more information on property attributes, see JS_GetPropertyAttributes. ...
JSObjectOps.getProperty
on cx JSContext * Pointer to the JS context in which the property access is happening. obj JSObject * The object to be accessed. id jsid The name or index of the property to access. vp jsval * In/out parameter. See the Description section below. Description Get, set, or delete obj[id], returning JS_FALSE on error or exception, JS_TRUE on success. If getting or setting, the new value is returned in *vp on success. If deleting without error, *vp will be JSVAL_FALSE if obj[id] is permanent, and JSVAL_TRUE if id named a direct property of obj that was in fact deleted, or if id names no direct property of obj (id could name a property of a prototype, or no property in obj or its prototype chain). This reflects the quirky behavior ...
JSObjectOps.lookupProperty
jp JSObject ** Out parameter. If the property is found, the callback stores the object on which the property was found in *objp. propp JSProperty ** Out parameter. On success, the callback stores in *propp a pointer to the property, if it exists, or NULL if it doesn't. Description Look for id in obj and its prototype chain, returning JS_FALSE on error or exception, JS_TRUE on success. On success, return null in *propp if id was not found. If id was found, return the first object searching from obj along its prototype chain in which id names a direct property in *objp, and return a non-null, opaque property pointer in *propp. If JSLookupPropOp succeeds and returns with *propp non-null, that pointer may be passed as the prop parameter to a JSAttributesOp, as a short...
JSPrincipalsTranscoder
bjects, so it must also provide a JSPrincipalsTranscoder if it intends to serialize or deserialize principals. The callback XDR-encodes or -decodes a principals instance, based on whether xdr->mode is JSXDR_ENCODE, in which case *principalsp should be encoded; or JSXDR_DECODE, in which case implementations must return a held (via JSPRINCIPALS_HOLD), non-null *principalsp out parameter. Return JS_TRUE on success, JS_FALSE on any error, which the implementation must have reported. MXR ID Search for JSPrincipalsTranscoder ...
JSPropertyDescriptor
onding property of an object. Descriptor. Examples The following example demonstrates how to use the Object.defineProperty() function to create a property under an object in a javascript via a descriptor. var language = {}; // Define an empty object language Object.defineProperty(language, 'log', { // Define the log attribute under the language object value : ['CN','EN'], writable : true, enumerable : true, configurable : true }) In the above example we defined a writable, deletable enumerable property.This is the same as the javascript directly defined property. In other words, the above code is equivalent to the following code. var language = {}; // Define an empty object language languange.log = ['CN','EN']; // Define the log attribute under the language object ...
JSResolveOp
esult of resolve operation. Description JSResolveOp callback is a hook which is called when a property is not found on an object. It resolves a lazy property named by id in obj by defining it directly in obj. Lazy properties are those reflected from some peer native property space (e.g., the DOM attributes for a given node reflected as obj) on demand. The callback must set *resolvedp to true and 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. Note: JSNewResolveOp provides ...
JSType
The values of the JSType enumeration represent the types of JavaScript values. Value Description JSTYPE_VOID The undefined value. JSTYPE_OBJECT JavaScript objects. JSTYPE_FUNCTION Functions. JSTYPE_STRING Strings. JSTYPE_NUMBER Numbers. JSTYPE_BOOLEAN Boolean values, true and false. JSTYPE_NULL The null value. JSTYPE_SYMBOL Symbols. See Also MXR ID Search for JSType ...
JSVAL_IS_BOOLEAN
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determines if a given jsval is a JavaScript 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). To convert between JavaScript boolean values (jsval) and C boolean values, use JSVAL_TO_BOOLEAN and BOOLEAN_TO_JSVAL. See Also bug 952650 ...
JSVAL_IS_DOUBLE
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determines if a given jsval is a number represented as a jsdouble. Syntax JSVAL_IS_DOUBLE(v) Description JSVAL_IS_DOUBLE(v) is true if v is a number represented in memory as a jsdouble. To check whether v is a number, regardless of implementation details, use JSVAL_IS_NUMBER instead. Example The following code snippet illustrates how a JavaScript variable, MyItem, is conditionally tested in an if statement to see if it is a JS double data type. if (JSVAL_IS_DOUBLE(MyItem)) { . . . } See Also bug 952650 ...
JSVAL_IS_GCTHING
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Indicates whether a JS value has a type that is subject to garbage collection. Syntax JSVAL_IS_GCTHING(v) Description JSVAL_IS_GCTHING(v) is true if the jsval v is either JSVAL_NULL or a reference to a value that is subject to garbage collection. JavaScript performs automatic garbage collection of objects, strings, and doubles. This macro exposes JavaScript engine implementation details and usually isn't what the application really means. See jsval for alternatives. See Also bug 952650 ...
JSVAL_IS_INT
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determine if a given jsval is a JavaScript number represented in memory as an integer. Syntax JSVAL_IS_INT(v) Description JSVAL_IS_INT(v) is true if the jsval v is a number represented in memory as an integer. To test whether a value is a number, regardless of how it is represented in memory, use JSVAL_IS_NUMBER instead. To convert between C integer types and jsval, use JSVAL_TO_INT, INT_FITS_IN_JSVAL, and INT_TO_JSVAL. Example The following code snippet illustrates how a JavaScript variable, MyItem, is conditionally tested in an if statement to see if it is a JS integer data type. if (JSVAL_IS_INT(MyItem)) { ...
JSVAL_IS_NULL
Determine if a given jsval is null. Syntax JSVAL_IS_NULL(v) Description JSVAL_IS_NULL(v) is true if v is JSVAL_NULL, which is the JavaScript null value. (Note: JSVAL_IS_OBJECT(JSVAL_NULL) is also true.) Example The following code snippet illustrates how a JavaScript variable, MyItem, is conditionally tested in an if statement to see if it contains a null value. if (JSVAL_IS_NULL(MyItem)) { ... } See Also bug 952650 ...
JSVAL_IS_NUMBER
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determine if a given jsval is a JavaScript number. Syntax JSVAL_IS_NUMBER(v) Description JSVAL_IS_NUMBER(v) is true if v is a JavaScript number. To convert a numeric jsval to a C floating-point number, use JS_ValueToNumber. Example The following code snippet illustrates how a JavaScript variable, MyItem, is conditionally tested in an if statement to see if it is a JS integer or double value. if (JSVAL_IS_NUMBER(MyItem)) { ... } See Also bug 952650 ...
JSVAL_IS_OBJECT
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determine whether a given jsval is an object or null. Syntax JSBool JSVAL_IS_OBJECT(jsval v); Description JSVAL_IS_OBJECT(v) returns true if v is either an object or JSVAL_NULL. This indicates that it is safe to call JSVAL_TO_OBJECT(v) to convert v to type JSObject *. If v is a string, number, boolean, or undefined, the result is false. This function is obsolete and has been removed. Instead use !JSVAL_IS_PRIMITIVE(v) to detect objects and JSVAL_IS_NULL(v) to detect null. See Also bug 952650 ...
JSVAL_IS_PRIMITIVE
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determine if a given jsval is of a primitive type. Syntax JSVAL_IS_PRIMITIVE(v) Description JSVAL_IS_PRIMITIVE(v) is true if v is undefined, null, a boolean, a number, or a string. Otherwise it is false, and v is an object. See Also bug 952650 ...
JSVAL_IS_STRING
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determines if a given jsval is a string. Syntax JSVAL_IS_STRING(v) Description JSVAL_IS_STRING(v) is true if v is a string. To access the content of a string jsval, use JSVAL_TO_STRING, JS_GetStringChars, and JS_GetStringLength. Example The following code snippet illustrates how a JavaScript variable, MyItem, is conditionally tested in an if statement to see if it is a string. if (JSVAL_IS_STRING(MyItem)) { ... } See Also bug 952650 ...
JSVAL_IS_VOID
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determines if a given jsval is the JavaScript value undefined. Syntax JSVAL_IS_VOID(v) Description JSVAL_IS_VOID(v) is true if v is JSVAL_VOID, which represents the JavaScript value undefined. Example The following code snippet illustrates how a JavaScript variable, MyItem, is conditionally tested in an if statement to see if it is void. if (JSVAL_IS_VOID(MyItem)) { ... } See Also bug 952650 ...
JSVAL_LOCK
local roots with JS_AddRoot. JSVAL_LOCK locks a JS value, v, to prevent the value from being garbage collected. v is a JS object, string, or double value. JSVAL_LOCK determines if v is an object, string, or double value, and if it is, it locks the value. If locking is successful, or v already cannot be garbage collected because it is not an object, string, or double value, JSVAL_LOCK evaluates to true. Otherwise, it evaluates to false. See Also JSVAL_IS_GCTHING JSVAL_TO_GCTHING JSVAL_UNLOCK JS_AddRoot JS_LockGCThing bug 787580 ...
JSVAL_NULL
Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. The jsval that represents the JavaScript value null. Syntax JSVAL_NULL Description JSVAL_NULL is a jsval constant that represents the JavaScript value null. It is equivalent to OBJECT_TO_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
ce JSAPI 42This feature is obsolete. ...
JSVAL_TO_BOOLEAN
it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Cast a boolean JavaScript value to a C integer, either 0 or 1, without any type checking or error handling. Syntax JSBool JSVAL_TO_BOOLEAN(jsval v); Description JSVAL_TO_BOOLEAN casts the value v to a C integer, either 0 or 1. As a precondition, JSVAL_IS_BOOLEAN(v) must be true. That is, v must be either JSVAL_TRUE or JSVAL_FALSE. Otherwise the behavior is undefined. The result is JS_TRUE or JS_FALSE respectively. These are constants of type JSBool, which is an integer type, the SpiderMonkey version of bool. JS_FALSE is 0; JS_TRUE is 1. To convert any value to a boolean, use JS_ValueToBoolean instead. That function has well-defined behavior even when the argument is an ...
JSVAL_TO_DOUBLE
gh it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Casts a given jsval to a jsdouble without any type checking or error handling. Syntax jsdouble JSVAL_TO_DOUBLE(jsval v); Description JSVAL_TO_DOUBLE casts a specified JS value, v, to a C floating-point number of type jsdouble. As a precondition, JSVAL_IS_DOUBLE(v) must be true. This function is not type-safe: if v is an integer, string, null, or anything else, the behavior is undefined. To convert any value to a number, use JS_ValueToNumber instead. See Also bug 952650 ...
JSVAL_TO_OBJECT
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Cast a jsval to a JSObject * without a type check. Syntax JSObject * JSVAL_TO_OBJECT(jsval v); Description JSVAL_TO_OBJECT casts the argument, v, to type JSObject *. As a precondition, JSVAL_IS_OBJECT(v) must be true. That is, v must be either a reference to an object or JSVAL_NULL. This function is not type-safe: if v is not an object or JSVAL_NULL, the behavior is undefined. To convert a value to an object, use the JS_ValueToObject function, which has well-defined behavior even when the argument is not an object or null. See Also bug 952650 ...
JSVAL_TO_STRING
Obsolete since JSAPI 32This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Cast a jsval to type JSString * without a type check. Syntax JSString * JSVAL_TO_STRING(jsval v); Description JSVAL_TO_STRING casts the argument, v, to type JSString *. As a precondition, JSVAL_IS_STRING(v) must be true. This function is not type-safe: if v is not a string, the behavior is undefined. To coerce any value to a string, use the JS_ValueToString function instead. (The difference is that the latter will convert an object, array, number, or other value to a string in a type-safe way, creating a new string if needed.) To convert the return type of this macro (JSString *) to a char pointer, use JS_GetStr...
JSVAL_UNLOCK
ith JS_RemoveRoot. JSVAL_UNLOCK unlocks a previously locked JS value, v, so it can be garbage collected. v is a JS object, string, or double value. JSVAL_UNLOCK determines if v is an object, string, or double value, and if it is, it unlocks the value. If unlocking is successful, or v not affected by garbage collection because it is not an object, string, or double value, JSVAL_UNLOCK evaluates to true. Otherwise, it evaluates to false. See Also JSVAL_IS_GCTHING JSVAL_TO_GCTHING JSVAL_LOCK JS_AddRoot JS_LockGCThing bug 787580 ...
JSVAL_VOID
JSAPI 42This feature is obsolete. ...
JSVAL_ZERO
JSAPI 42This feature is obsolete. ...
JS_AddFinalizeCallback
Callback)(JSFreeOp *fop, JSFinalizeStatus status, bool isCompartment, void *data); Name Type Description fop JSFreeOp * A pointer to an instance of JSFreeOp. status JSFinalizeStatus One of the JSFinalizeStatus constants, described below, indicating the stage of finalize. isCompartment bool false if all compartments are being collected, true if a compartment is being collected. data void * data parameter specified in JS_AddFinalizeCallback. Added in SpiderMonkey 38 Name Description JSFINALIZE_GROUP_START Called when preparing to sweep a group of compartments, before anything has been swept. The collector will not yield to the mutator before calling the callback with JSFINALIZE_GROUP_END s...
JS_Add*Root
ng constant, identifying the source location of the call to JS_AddNamedRoot for debugging purposes. JS_DumpNamedRoots can be used to access this information from a debugger. All the JS_Add*Root methods are idempotent: multiple calls for the same address will add only one root. Correspondingly, only a single JS_RemoveRoot is required to unroot the location. On success, these functions return JS_TRUE. Otherwise they report an out of memory error and return JS_FALSE. See Also MXR ID Search for JS_AddValueRoot MXR ID Search for JS_AddStringRoot MXR ID Search for JS_AddObjectRoot MXR ID Search for JS_AddNamedValueRoot MXR ID Search for JS_AddNamedStringRoot MXR ID Search for JS_AddNamedObjectRoot bug 912581 ...
JS_AliasElement
cated, meaning that it is currently supported only for backward compatibility with existing applications. Future versions of the engine may no longer support this function. An alias does not replace an element's current index number; it supplements it, providing a second way to reference the element. If the alias is successfully created and associated with the property, JS_AliasElement returns JS_TRUE. Adding an alias element does not change the element array length. If the property name you specify does not exist, JS_AliasElement reports an error, and 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. Once you create an alias, you can reassign it to o...
JS_AliasProperty
the object to which the property belongs. name is the property's current name in the object, and alias is the alternate name to assign to the property. Notes This feature has been removed. An alias does not replace a property's name; it supplements it, providing a second way to reference a property. If the alias is successfully created and associated with the property, JS_AliasProperty returns JS_TRUE. Creating an alias does not change the length of the property array. If the property name you specify does not exist, JS_AliasProperty reports an error, and 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. Once you create an alias, you can reassign i...
JS_BufferIsCompilableUnit
aller must be in a request on this JSContext. obj JS::HandleObject The global object, or NULL. utf8 const char * String containing the script to compile. length size_t The length of utf8 in characters. Description Given a buffer, return false if the buffer might become a valid JavaScript statement with the addition of more lines. Otherwise return true. The intent is to support interactive compilation - accumulate lines in a buffer until JS_BufferIsCompilableUnit is true, then pass it to the compiler. See Also MXR ID Search for JS_BufferIsCompilableUnit JS::Evaluate JS::Compile JS::CompileOffThread JS::CompileFunction JS_DecompileScript ...
JS_CStringsAreUTF8
an optionally interpret these strings as UTF-8. There are two ways to enable this: at compile time, by building SpiderMonkey with JS_C_STRINGS_ARE_UTF8 defined; or at run time, by calling JS_SetCStringsAreUTF8 before the first call to JS_NewRuntime. Enabling this option also causes JS_GetStringBytes and JS_EncodeCharacters to produce UTF-8 strings instead of Latin-1. JS_CStringsAreUTF8 returns JS_TRUE if the JavaScript engine is configured (either at compile time or at run time) to interpret char strings as UTF-8. See Also bug 805080 ...
JS_CallFunction
om the number of arguments defined for the function. Obsolete since JSAPI 30. In argc, indicate the number of arguments passed to the function. In argv, pass a pointer to the actual argument values to use. rval is a pointer to a variable that will hold the function's return value, if any, on successful function execution. If the called function executes successfully, JS_CallFunction returns true. Otherwise it returns false, and rval is undefined. Calling JS_CallFunction is safe only if the fun argument could be passed to JS_GetFunctionObject safely: that is, it is a function implemented by a JSNative or JSFastNative or the result of a call to JS_CompileFunction, JS_CompileUCFunction, JS_CompileFunctionForPrincipals, or JS_CompileUCFunctionForPrincipals. Passing any other JSFunction poin...
JS_CheckAccess
ck is delegated to the JSObjectOps.checkAccess callback. Otherwise, if obj's class has a non-null JSClass.checkAccess callback, then it is called to perform the check. Otherwise, if a runtime-wide check-object-access callback has been installed by calling JS_SetCheckObjectAccessCallback, then that is called to perform the check. Otherwise, access is granted. On success, JS_CheckAccess returns JS_TRUE, *vp is set to the current value of the specified property, and *attrsp is set to the property's attributes. On error or exception, including if access is denied, JS_CheckAccess returns JS_FALSE, and the values left in *vp and *attrsp are undefined. MXR ID Search for JS_CheckAccess ...
JS_ClearRegExpStatics
me Type Description cx JSContext * The context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject A pointer to a global object. Description JS_ClearRegExpStatics clears the pending input string and flags of the built-in RegExp object. On successful, JS_ClearRegExpStatics returns true, otherwise returns false. See Also MXR ID Search for JS_ClearRegExpStatics JS_NewRegExpObject JS_NewUCRegExpObject JS_SetRegExpInput RegExp ...
JS_CompareStrings
result int32_t * The out parameter. See description for value of *result. Description JS_CompareStrings compares two JS strings, str1 and str2. If the strings are identical in content and length, JS_CompareStrings stores 0 in *result. If str1 is less than str2, *result is less than 0. If str1 is greater than str2, *result is greater than 0. On success the function returns JS_TRUE. On error, it returns JS_FALSE and the value in result is unchanged. This function imposes a total order on all JavaScript strings, the same order imposed by the JavaScript string comparison operators (<, <=, >, >=), as described in ECMA 262-3 ? 11.8.5. As the standard says: The comparison of strings uses a simple lexicographic ordering on sequences of code point value values. There is no attem...
JS_CompileScript
ript compiles a script, source, for execution. JS_CompileUCScript is the Unicode version of the function. The script is associated with a JS object. ascii and chars are the string containing the text of the script. length indicates the size of the text version of the script in characters. On success, JS_CompileScript and JS_CompileUCScript stores the newly compiled script to *script and returns true. Otherwise, they report an error, stores NULL to *script, and return false. See Also The JSAPI User Guide contains example code using compiled scripts. MXR ID Search for JS_CompileScript MXR ID Search for JS_CompileUCScript JS::Evaluate JS::CompileOffThread JS::CompileFunction JS_ExecuteScript JS_DecompileScript bug 1143793 -- removed obj parameter ...
JS_ConvertArguments
a JSObject *, and the last value into a bool. To skip a given argument, pass an asterisk in the corresponding position in format. If argc is less than the number of arguments required by format, JS_ConvertArgument reports an error and returns false. If argc is greater than the number of arguments described in format, the extraneous arguments are ignored. On success, JS_ConvertArgument returns true. If any argument conversion fails or there are not enough arguments, it returns false. To perform the opposite conversion, converting values of various C types to an array of jsvals, use JS_PushArguments. See Also MXR ID Search for JS_ConvertArguments JS_ConvertArgumentsVA bug 607292 - obsolete s format bug 933946 - obsolete j format bug 969798 - added args bug 1125784 ...
JS_ConvertArgumentsVA
to store the converted types. There should be one pointer for each converted value. The type va_list is a standard feature of the C programming language. It is defined in <stdarg.h>. Description JS_ConvertArgumentsVA is to JS_ConvertArguments as vprintf is to printf. See JS_ConvertArguments for further information. If JS_ConvertArgumentsVA successfully converts all arguments, it returns true. Otherwise it returns false. See Also MXR ID Search for JS_ConvertArgumentsVA JS_ConvertArguments bug 969798 - added args bug 1125784 ...
JS_ConvertValue
e result is a function object that has not been stripped of its lexical scope. It is safe to call the result (e.g. using JS_CallFunctionValue). Converting to JSTYPE_STRING works like JS::ToString. Converting to JSTYPE_NUMBER works exactly like JS::ToNumber. Converting to JSTYPE_BOOLEAN works exactly like JS::ToBoolean. On success, JS_ConvertValue stores the converted value in *vp and returns true. On error or exception, it returns false, and the value left in *vp is undefined. See Also MXR ID Search for JS_ConvertValue JS_ConvertArguments JS_GetTypeName JS_TypeOfValue bug 1125784 ...
JS_DefaultValue
case for Date objects). Objects with a custom JSClass specified by the embedder will invoke that class's convert hook, which must convert the object to a primitive value, to determine the primitive result of conversion. Behavior when the convert hook is JS_ConvertStub is identical to that for objects defined by ECMAScript. On success, JS_DefaultValue stores the converted value in *vp and returns true. On error or exception, it returns false, and the value left in *vp is undefined. See Also MXR ID Search for JS_DefaultValue JS::ToPrimitive bug 1054756 - renamed to JS::ToPrimitive ...
JS_DefineConstDoubles
array of JSConstDoubleSpec/JSConstIntegerSpec structures. Each array element defines a single property name and property value to create. The name field of the last element of the array must contain 0. JS_DefineConstDoubles/JS_DefineConstIntegers create one property for each element in the array what contains a non-zero name field. On success, JS_DefineConstDoubles/JS_DefineConstIntegers returns true, indicating it has created all properties listed in the array. Otherwise it returns false. See Also MXR ID Search for JS_DefineConstDoubles MXR ID Search for JS_DefineConstIntegers JSConstDoubleSpec JSConstIntegerSpec JS_DefineElement JS_DefineProperties JS_DefineProperty JS_DefinePropertyWithTinyId bug 1066020 - added JS_DefineConstIntegers ...
JS_DefineElement
efines the property's initial value. getter and setter identify the getProperty and setProperty methods for the property, respectively. If you pass NULL values for these entries, JS_DefineElement assigns the default getProperty and setProperty methods to this element. Obsolete since JSAPI 32 flags contains the property attributes to set for the new property. On success, JS_DefineElement returns true. Otherwise it returns false. Obsolete since JSAPI 32. While you can assign a setProperty method to a property and set flags to JSPROP_READONLY, the setter method will not be called on this property. See Also MXR ID Search for JS_DefineElement JS_DefineConstDoubles JS_DefineFunction JS_DefineFunctions JS_DefineObject JS_DefineProperties JS_DefineProperty JS_DefinePropertyWithTinyId JS_Delet...
JS_DefineFunctions
he array must contain 0 values. (The macro JS_FS_END can be used for the last element.) JS_DefineFunctions creates one function for each non-zero element in the array. PropertyDefinitionBehavior is used to select if properties with JSPROP_DEFINE_LATE flag should be defined on the object. Normal JSAPI consumers probably always want DefineAllProperties here. On success, JS_DefineFunctions returns true. On error or exception, it stops defining functions and returns false. See Also MXR ID Search for JS_DefineFunctions JS_CallFunctionName JS_DefineObject JS_DefineProperties JS_NewFunction bug 959787 - make fs type to const bug 825199 - added PropertyDefinitionBehavior ...
JS_DefineOwnProperty
. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject Object on which the property should be defined own. id JS::HandleId The jsid of the property that should be defined. descriptor JS::HandleValue This should be an jsval consisting of an object interpretable as property descriptor. bp bool * true if successful. Description JS_DefineOwnProperty implements the ECMAScript defined function Object.defineProperty. So the same restrictions apply as for that function (e.g. it is not possible to change a non-configurable property). descriptor is supposed to be a property descriptor, this means you need to create an object with properties such as value, writable, get or set. See Object.define...
JS_DefineProperties
single property: its name, attributes, getter, and setter. The name field of the last array element must be NULL. JS_DefineProperties creates one property for each element in the array before the element with a null name field. Each property is defined as though by calling JS_DefineProperties. The initial stored value of each property created is undefined. On success, JS_DefineProperties returns true, indicating it has created all properties listed in the array. Otherwise it returns false. See Also MXR ID Search for JS_DefineProperties JS_DefineConstDoubles JS_DefineElement JS_DefineFunction JS_DefineFunctions JS_DefineObject JS_DefineProperty JS_InitClass bug 855582 ...
JS_DefineProperty
Property) callback from obj's class. If attrs contains the JSPROP_GETTER (or JSPROP_SETTER) flag, then getter (or setter) must point to a JavaScript Function, not a C/C++ function. That is, it must be a JSObject * that points to a JavaScript Function, cast to type JSPropertyOp. For more about JavaScript getters and setters, see Defining Getters and Setters. On success, JS_DefineProperty returns true. On error or exception, it returns false. See Also MXR ID Search for JS_DefineProperty MXR ID Search for JS_DefineUCProperty MXR ID Search for JS_DefinePropertyById JS_DefineElement bug 461163 bug 1113369 -- added desc and result parameters ...
JS_DefinePropertyWithTinyId
If the property already exists or cannot be created, they return JS_FALSE. See Also bug 975069 ...
JS_DeleteElement
:ObjectOpResult &amp; (out parameter) Receives the result of the operation. Description JS_DeleteElement removes a specified element or numeric property, index, from an object, obj. If an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. If deletion is successful, JS_DeleteElement returns true. Otherwise it returns false. For JavaScript 1.2 and earlier, if failure occurs because you attempt to delete a permanent or read-only element, JS_DeleteElement reports the error before returning false. For JavaScript 1.3 and later, the attempt is silently ignored. To truncate an array, use JS_SetArrayLength. To remove all elements and properties from an object, call JS_ClearScope. See Also ...
JS_DeleteElement2
e information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject Object from which to delete an element. index uint32_t Index number of the element to delete. succeeded bool * Out parameter. On success, *succeeded receives false if the property was not deleted because it is permanent and true otherwise. Description JS_DeleteElement2 removes a specified element or numeric property, index, from an object, obj. If an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. If deletion is successful, JS_DeleteElement2 stores true to *succeeded and returns true. Otherwise it returns false an...
JS_DeleteProperty
property but it is permanent, nothing happens. No property is deleted, but this is not an error. Otherwise obj has a non-permanent own property with the given name or id. In this case, obj's JSClass.delProperty hook is called. If the hook returns false, the error is propagated. Otherwise, if obj is not configurable, an error is raised. Otherwise, the property is removed. These functions return true on success, regardless of whether a property was actually deleted, and false on error or exception. (In JavaScript 1.2 and earlier, attempting to delete a permanent property caused an error. There is no longer any way to get this behavior.) Internally, property deletion is implemented by the JSObjectOps.deleteProperty callback. To remove all properties from an object, call JS_ClearScope. See ...
JS_DoubleIsInt32
(comment from mozilla::NumberEqualsInt32) Casting a floating-point value that doesn't truncate to int32_t, to int32_t, induces undefined behavior. We should definitely fix this (bug 744965), but as apparently it "works" in practice, it's not a pressing concern now. See Also MXR ID Searc...
JS_EncodeCharacters
en, NULL, &dstlen)) return JS_FALSE; /* Allocate. */ char *dst = (char *) JS_malloc(cx, dstlen); if (dst == NULL) return JS_FALSE; /* Convert characters to bytes. */ JS_EncodeCharacters(cx, src, srclen, dst, &dstlen); /* Use the converted bytes for something. */ ... /* Remember to free the bytes afterwards. */ JS_free(cx, dst); return JS_TRUE; On success, JS_EncodeCharacters sets *dstlenp to the real result length and returns JS_TRUE. Otherwise it reports an error and returns JS_FALSE. This happens if the destination is too small for the resulting string or if the source buffer isn't proper UTF-16 because it contains unpaired surrogate values. The user is responsible for allocating and freeing the memory of the destination string. J...
JS_EncodeString
Name Type Description cx JSContext * A context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext.. str JSString * / JS::HandleString A string to encode. Description JS_EncodeString and JS_EncodeStringToUTF8 convert the specified JavaScript str to a C string (an array of 8-bit chars). If JS_CStringsAreUTF8 is true, then the returned string of JS_EncodeString is UTF-8, and the conversion is lossless. Otherwise the high byte is simply dropped from each char16_t. JS_EncodeStringToUTF8 encode the string to UTF-8. The array returned by JS_EncodeString on success is allocated as though by a call to JS_malloc. The caller may modify it and is responsible for freeing it. Note that for non-ASCII strings, if JS_CS...
JS_EvaluateScript
function. In the common case where the script is just an expression, the result value is simply the value of that expression. More generally, the result value is the value of the last-executed expression statement in the script that isn't in a function. If a script compiles and executes successfully, JS_EvaluateScript or JS_EvaluateUCScript stores the result in *rval, if non-null, and returns JS_TRUE. Otherwise it returns JS_FALSE and the value left in *rval is undefined. See Also MXR ID Search for JS_EvaluateScript MXR ID Search for JS_EvaluateUCScript JS_CompileFile JS_CompileScript JS_DecompileScript JS_DestroyScript JS_EvaluateScriptForPrincipals bug 1100579 ...
JS_EvaluateScriptForPrincipals
sed in messages if an error occurs during compilation. Similarly, lineno is used to report the line number of the script or file where an error occurred during compilation. If the script compiles and executes successfully, *rval receives the value from the last-executed expression statement processed in the script, and JS_EvaluateScriptForPrincipals or JS_EvaluateUCScriptForPrincipals returns JS_TRUE. Otherwise it returns JS_FALSE, and the value left in *rval is undefined. See Also JS::Evaluate JS_CompileFile JS_CompileScriptForPrincipals JS_EvaluateScript bug 980180 ...
JS_ExecuteScript
Description JS_ExecuteScript executes a previously-compiled script, script. JS::CloneAndExecuteScript handles a cross-compartment script. If the script is cross-compartment, it is cloned into the current compartment before executing. If the script executes successfully, rval receives the value from the last executed expression statement processed in the script, and JS_ExecuteScript returns true. Otherwise it returns false, and the value left in rval is unspecified. The JSAPI User Guide contains example code using compiled scripts. To execute a script that has not been compiled, use JS::Evaluate instead. See Also MXR ID Search for JS_ExecuteScript MXR ID Search for JS::CloneAndExecuteScript JS::Compile JS::Evaluate bug 993438 bug 1145294 -- removed obj from JS::CloneAndExecut...
JS_ExecuteScriptPart
in the script. Description JS_ExecuteScriptPart executes part of a previously compiled script, script. The part parameter must be either JSEXEC_PROLOG to execute the script prolog or JSEXEC_MAIN to execute the main section of the script. If the script executes successfully, JS_ExecuteScriptPart stores the value of the last-executed expression statement in the script in *rval and returns JS_TRUE. Otherwise it returns JS_FALSE, and the value left in *rval is undefined. To execute both parts of a script, use JS_ExecuteScript instead. See Also MXR ID Search for JS_ExecuteScriptPart JS_ExecuteScript bug 555104 ...
JS_ExecuteScriptVersion
ss, *rval receives the value from the last executed expression statement processed in the script. version JSVersion Version for the script. Description JS_ExecuteScript executes a previously-compiled script, script. If the script executes successfully, *rval receives the value from the last executed expression statement processed in the script, and JS_ExecuteScript returns true. Otherwise it returns false, and the value left in *rval is unspecified. To execute a script that has not been compiled, use JS::Evaluate instead. See Also JS::Compile JS_ExecuteScript JS::Evaluate bug 1095660 ...
JS_FileEscapedString
to write into. str JSString * A string to write into the file. quote char One of 0, single quote, and double quote. Description JS_FileEscapedString writes str into file fp escaping any non-printable or non-ASCII character. If quote is not 0, it must be a single or double quote character that will quote the output. If successful, JS_FileEscapedString returns true, otherwise false. See Also MXR ID Search for JS_FileEscapedString bug 609440 ...
JS_ForwardGetPropertyTo
Description JS_ForwardGetPropertyTo is the base implementation of JS_GetProperty, JS_GetUCProperty, JS_GetPropertyById etc, where onBehalfOf is same to obj. onBehalfOf is Receiver in [[Get]] internal method of Proxy, defined in ES2015 draft spec (rev 29, 9.5.8). On success, these functions set *vp to the current value of the property, or undefined if obj has no such property, and return true. On an error or exception, these functions return false, and the value left in *vp is undefined. See Also MXR ID Search for JS_ForwardGetPropertyTo JS_GetProperty bug 698551 ...
JS_GetArrayLength
array. Description JS_GetArrayLength gets the .length property of obj as though by calling JS_GetProperty and converts it to a 32-bit unsigned integer. If obj is an array (see JS_IsArrayObject), this is guaranteed to succeed, because the .length property of an array is always a number and can't be deleted or redefined. On success, JS_GetArrayLength stores the length in *lengthp and returns true. On failure, it reports an error and returns false, and the value left in *lengthp is undefined. See Also MXR ID Search for JS_GetArrayLength JS_GetElement JS_SetArrayLength ...
JS_GetClassObject
ust be in a request on this JSContext. key JSProtoKey The key of the prototype. objp JS::MutableHandle&lt;JSObject*&gt; Out parameter. If successful, receive the class constructor. Description JS_GetClassObject gets the builtin class costructor for the specified prototype key. If successful, JS_GetClassObject stores the class constructor to *objp and returns true, otherwise returns false and the value of *objp is undefined. See Also MXR ID Search for JS_GetClassObject JS_GetClassPrototype JSProtoKey ...
JS_GetClassPrototype
est on this JSContext. key JSProtoKey The key of the prototype. objp JS::MutableHandle&lt;JSObject*&gt; Out parameter. If successful, receive the class prototype object. Description JS_GetClassPrototype gets the builtin class costructor for the specified prototype key. If successful, JS_GetClassPrototype stores the class prototype object to *objp and returns true, otherwise returns false and the value of *objp is undefined. See Also MXR ID Search for JS_GetClassPrototype JS_GetClassObject JSProtoKey ...
JS_GetElement
ableHandleValue Out parameter. On success, *vp receives the current value of the element, if it exists, and undefined otherwise. Description JS_GetElement examines a specified JS object, obj, and its prototype chain, for an element or numeric property numbered index. If the element exists, JS_GetElement sets *vp to the element's current value. If not, it sets *vp to undefined and returns true (to indicate no error occurred). If the search fails with an error or exception, JS_GetElement returns false, and the value left in *vp is undefined. See Also MXR ID Search for JS_GetElement JS_DefineElement JS_DeleteElement JS_GetArrayLength JS_IsArrayObject JS_LookupElement JS_NewArrayObject JS_SetArrayLength JS_SetElement ...
JS_GetGCParameter
encyHighLimit" JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MAX / "highFrequencyHeapGrowthMax" JSGC_HIGH_FREQUENCY_HEAP_GROWTH_MIN / "highFrequencyHeapGrowthMin" JSGC_LOW_FREQUENCY_HEAP_GROWTH / "lowFrequencyHeapGrowth" Heap growth percentage for low frequency GCs. JSGC_DYNAMIC_HEAP_GROWTH / "dynamicHeapGrowth" If false, the heap growth percentage is fixed at 300%. If true, it is determined based on whether GCs are high- or low- frequency. JSGC_DYNAMIC_MARK_SLICE / "dynamicMarkSlice" If true, high-frequency GCs will use a longer mark slice. JSGC_ALLOCATION_THRESHOLD / "allocationThreshold" Lower limit after which we limit the heap growth. The heap will be collected if it is greater than: MAX(allocThreshold, lastSize) * thresholdFactor, This ...
JS_GetPendingException
as thrown. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. vp JS::MutableHandleValue Out parameter. On success, *vp receives the current pending exception. Description If an exception has been thrown in the context cx, and it has not yet been caught or cleared, JS_GetPendingException stores the exception object in *vp and returns true. Otherwise, it returns false, and the value left in *vp is undefined. See examples in the JSAPI Phrasebook. See Also MXR ID Search for JS_GetPendingException JS_IsExceptionPending JS_ClearPendingException JS_ReportPendingException JS_SetPendingException ...
JS_GetPropertyDefault
MutableHandleValue Out parameter. On success, *vp receives the current value of the property, or undefined if no such property is found. Description JS_GetPropertyDefault examines a specified JS object obj and its prototype chain for a property with the specified name. On success, these functions set *vp to the current value of the property, or def if obj has no such property, and return true. On an error or exception, these functions return false, and the value left in *vp is undefined. See Also bug 905774 ...
JS_GetPrototype
Description JS_GetPrototype retrieves the prototype of a specified object, obj. A prototype object provides properties inherited by similar JS objects. This is the equivalent of Object.getPrototypeOf(obj) from javascript. If JS_GetPrototype returns false, that signals an exception, which should be handled as usual. Otherwise, it stores a pointer to the prototype or null to *protop and returns true. To set an object's prototype, use JS_SetPrototype. See Also MXR ID Search for JS_GetPrototype JS_SetPrototype ...
JS_GetStringBytes
x, JSString *str); // Added in JSAPI 1.8.2 Name Type Description cx JSContext * (JS_GetStringBytesZ and JS_EncodeString only) A context. str JSString * String to retrieve bytes from. Description JS_GetStringBytes and JS_GetStringBytesZ convert the specified JavaScript string, str, to a C string (an array of 8-bit chars). If JS_CStringsAreUTF8 is true, then the returned string is UTF-8, and the conversion is lossless. Otherwise the high byte is simply dropped from each jschar. On success, the return value is a pointer to the char array, which is null-terminated. On failure, JS_GetStringBytes returns a pointer to a null-terminated empty string; JS_GetStringBytesZ returns NULL. Note: JS_GetStringBytes() and JS_GetStringBytesZ() have both been ...
JS_GetStringCharAt
g * The string to get character. index size_t An integer between 0 and 1-less-than the length of the string. res char16_t * (JS_GetStringCharAt only) Out parameter. On successful, receives the character code. Description JS_GetStringCharAt and JS_GetFlatStringCharAt get the specified character from the string str. On successful, JS_GetStringCharAt returns true and stores the character code into *res, otherwise returns false. JS_GetFlatStringCharAt always succeeds, and returns the character code. index should not be greater than or equal to the length of str. See Also MXR ID Search for JS_GetStringCharAt MXR ID Search for JS_GetFlatStringCharAt bug 1034627 ...
JS_HasArrayLength
ntext. obj JSObject * Array object to get the length of. lengthp jsuint * Out parameter. On success, *lengthp receives the length of the array. Description JS_HasArrayLength determines if an object, obj, has a length property. If the property exists, JS_HasArrayLength stores the current value of the property in *lengthp. On success, JS_HasArrayLength returns JS_TRUE, and *lengthp receives the current value of the length property. On failure, JS_HasArrayLength returns JS_FALSE, and the value left in *lengthp is undefined. This function differs from JS_GetArrayLength in the treatment of errors and unusual cases, like when an object's length is negative or not a number. This function may return JS_FALSE without having reported any error or exception. See Also ...
JS_HasElement
ype Description cx JSContext * The context in which to perform the property lookup. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The object to search for the element. index uint32_t Index of the element to look up. foundp bool * Out parameter. On success, it stores true to *foundp, false otherwise. Description JS_HasElement examines a specified JS object, obj, and its prototype chain, for an element or numeric property numbered index. If the element exists, JS_HasElement sets *foundp to true. If not, it sets *foundp to false and returns true (to indicate no error occurred). If the search fails with an error or exception, JS_HasElement returns false, and...
JS_HasInstance
S::Handle&lt;JS::Value&gt; The value to test. bp bool * Out parameter. On success, *bp receives the result of the test. Description JS_HasInstance determines if a specified JS value, v, is an instance of JS object, obj. This function is equivalent to v instanceof obj test in JavaScript. On success, JS_HasInstance stores the result of the instanceof test in *bp and returns true. On error or exception, it returns false, and the value left in *bp is undefined. When providing a prototype as obj, the prototype's JSClass must have its hasInstance method set. Otherwise JS_HasInstance returns false. See Also MXR ID Search for JS_HasInstance JS_InstanceOf ...
JS_IdToValue
n a JS_THREADSAFE build, the caller must be in a request on this JSContext. id jsid The property identifier to convert. vp JS::MutableHandle&lt;JS::Value&gt; Out parameter. On success, *vp receives the converted value. Description JS_IdToValue converts a specified JS ID, id, to a JS value. On success, JS_IdToValue stores the converted value in *vp and returns true. Otherwise it returns false. The inverse of JS_IdToValue is JS_ValueToId. See Also MXR ID Search for JS_IdToValue JS_ValueToId ...
JS_Init
Once this method has succeeded, it is safe to call JS_NewRuntime and other JSAPI methods. This method must be called before any other JSAPI method is used on any thread. ...
JS_InitStandardClasses
s, and constants are created as properties of obj. As a side effect, JS_InitStandardClasses establishes obj as the global object for cx, if one is not already established. This means that scripts executed in cx will see the properties of obj as global variables. See JS_SetGlobalObject for details. obj must be of a JSClass that has the JSCLASS_GLOBAL_FLAGS flag. JS_InitStandardClasses returns JS_TRUE on success, and JS_FALSE if an error occurs. To initialize custom classes, use JS_InitClass. See Also MXR ID Search for JS_InitStandardClasses ...
JS_IsArrayObject
ect obj); Name Type Description cx JSContext * A context. value JS::HandleValue The value to examine. obj JS::HandleObject The object to examine. isArray bool Whether the value/object is an array. Description JS_IsArrayObject determines if a specified object, obj or value, is an Array object. On success, returns true and sets isArray indicating whether obj is an Array object or a wrapper around one. Otherwise returns false on failure. See Also MXR ID Search for JS_IsArrayObject bug 959787 - added value bug 1179003 - added isArray ...
JS_IsAssigning
Obsolete since JavaScript 1.8.5This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Determine whether script is executing assignment operation. Syntax JSBool JS_IsAssigning(JSContext *cx); Name Type Description Description JS_IsAssigning returns true if a script is executing and its current bytecode is a set (assignment) operation, even if there are native (no script) stack frames between the script and the caller to JS_IsAssigning. See Also bug 458421 ...
JS_IsConstructing
SContext *cx, jsval *vp); Name Type Description cx JSContext * The cx parameter passed to the JSNative. vp jsval * The vp parameter passed to the JSNative. Description JS_IsConstructing must be called only from a JSNative called from the engine. cx and vp must be the arguments that the engine passed to that JSNative. JS_IsConstructing returns JS_TRUE if the native was defined with JSFUN_CONSTRUCTOR (JS_InitClass automatically sets that flag when defining a constructor) and it was called as a constructor, either from JavaScript, using the new keyword, or from C/C++ using a JSAPI function such as JS_ConstructObject. Otherwise it returns JS_FALSE. Ordinary non-constructor JSNatives have no need to call this; it always returns JS_FALSE for such f...
JS_IsConstructor
rticle covers features introduced in SpiderMonkey 24 Return whether the given function is a valid constructor. Syntax bool JS_IsConstructor(JSFunction *fun); Name Type Description fun JSFunction * The function to examine. Description JS_IsConstructor determines if a specified function, fun is a valid constructor object. If so, JS_IsConstructor returns true. Otherwise it returns false. See Also MXR ID Search for JS_IsConstructor JS::IsConstructor bug 807228 ...
JS_IsExceptionPending
Determine whether an exception is pending in the JS engine. Syntax bool JS_IsExceptionPending(JSContext *cx); Name Type Description cx JSContext * Pointer to a JS context to check for pending exceptions. Description JS_IsExceptionPending returns true if an exception has been thrown in the context cx and the exception has not yet been caught or cleared. Otherwise, it returns false This can be used from JSNative functions which call JS code to determine if the called JS code threw an exception or not. Example /* JSAPI */ bool pending; JS::RootedValue exception(cx); /* If an exception is pending, save and clear it. */ pending = JS_IsExceptionPending(cx); if (pending) { if (!JS_GetPendingException(cx, &exception)) return false; JS_ClearPend...
JS_IsExtensible
y of the given object. Syntax bool JS_IsExtensible(JSContext *cx, JS::HandleObject obj, bool *extensible); Name Type Description cx JSContext * The context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject The object to examine. extensible bool * Out parameter. Receives true if extensible, false otherwise. Description JS_IsExtensible queries [[Extensible]] property of the specified object, obj. If successful, JS_IsExtensible stores [[Extensible]] property to *extensible and returns true, otherwise returns false and the value of *extensible is undefined. See also MXR ID Search for JS_PreventExtensions JS_PreventExtensions bug 492845 ...
JS_IsExternalString
See Also MXR ID Search for JS_IsExternalString bug 651041 ...
JS_IsGlobalObject
This article covers features introduced in SpiderMonkey 24 Determine if given object is a global object. Syntax bool JS_IsGlobalObject(JSObject *obj); Name Type Description obj JSObject * The object to examine. Description JS_IsGlobalObject returns true if obj is a global object, false otherwise. See also MXR ID Search for JS_IsGlobalObject JS_NewGlobalObject bug 797821 ...
JS_IsIdentifier
char16_t * The pointer of the string to test. length size_t The length of chars. isIdentifier bool * Out parameter. On success, *isIdentifier receives whether str is an identifier or not. Description JS_IsIdentifier tests if the given string is a valid ECMAScript identifier. On successful, JS_IsIdentifier stores the test result to *isIdentifier and returns true, otherwise returns false and the value of *isIdentifier is undefined. JS_IsIdentifier which takes chars and length is infallible, so just returns whether the chars are an identifier. See Also MXR ID Search for JS_IsIdentifier JS_ValueToId bug 692627 bug 990484 ...
JS_IsNative
This article covers features introduced in SpiderMonkey 17 Determines if given JSObject is a native object. Syntax bool JS_IsNative(JSObject *obj); Name Type Description str JSObject * The object to check. Description JS_IsNative returns true if the object is a native object. See Also MXR ID Search for JS_IsNative JS_IsNativeFunction bug 648647 ...
JS_IsNativeFunction
Otherwise it returns false. See Also MXR ID Search for JS_IsNativeFunction JS_IsNative bug 648801 ...
JS_IsRunning
Indicates whether or not a script or function is currently executing in a given context. Syntax bool JS_IsRunning(JSContext *cx); Name Type Description cx JSContext * The context to query. Description JS_IsRunning determines if a script or function is currently executing in a specified JSContext, cx. If a script is executing, JS_IsRunning returns true. Otherwise it returns false. See Also MXR ID Search for JS_IsRunning ...
JS_IsStopIteration
article covers features introduced in SpiderMonkey 31 Determine whether the value is a StopIteration exception or not. Syntax // Added in SpiderMonkey 42 bool JS_IsStopIteration(JS::Value v); // Obsolete since SpiderMonkey 42 bool JS_IsStopIteration(jsval v); Name Type Description v JS::Value The value to check. Description JS_IsStopIteration returns true if v is StopIteration, otherwise false. See Also MXR ID Search for JS_IsStopIteration JS_ThrowStopIteration bug 918170 bug 1184564 -- Changed jsval to JS::Value ...
JS_LinkConstructorAndPrototype
object. proto JS::Handle&lt;JSObject*&gt; Pointer to the prototype object. Description JS_LinkConstructorAndPrototype sets the prototype property of class constructor function, ctor, to prototype object, proto with JSPROP_PERMANENT | JSPROP_READONLY flags, and sets the constructor property of proto to ctor with no flag. On successful, JS_LinkConstructorAndPrototype returns true. See Also MXR ID Search for JS_LinkConstructorAndPrototype JS_InitClass bug 722729 ...
JS_LookupElement
whose names are numeric strings. For example, obj[6] is always exactly the same as obj["6"]. The ECMAScript standard also specifies this behavior: see ECMA 262-3 ?11.2.1, step 6. So any call to JS_LookupElement is equivalent to a call to JS_LookupProperty passing a numeric string for the name. If the property obj[index] exists, JS_LookupElement sets *vp to the property's stored value and returns true. If no such property exists, JS_LookupElement sets *vp to undefined and returns true (to indicate that no error occurred). On error or exception, JS_LookupElement returns false, and the value left in *vp is undefined. JS_LookupElement does not distinguish between a property with a value of undefined and a property that does not exist. See Also JS_DefineElement JS_DeleteElement JS_GetArrayL...
JS_LookupProperty
ription The functions JS_LookupProperty, JS_LookupUCProperty, JS_LookupPropertyById, JS_LookupPropertyWithFlags, and JS_LookupPropertyWithFlagsById search a specified object, obj, for a property with the given name. These functions all have similar behavior: The search starts with obj and proceeds along the prototype chain. If the property is found, *vp receives the property's stored value, or true if the property has no stored value; and the return value is true. If neither obj nor any of its prototypes have such a property, *vp receives undefined and the return value is true (to indicate no error occurred). On error or exception (such as running out of memory during the search), the return value is false, and the value left in *vp is undefined. There is no way to tell the difference be...
JS_LooselyEqual
er must be in a request on this JSContext. v1, v2 JS::Handle&lt;JS::Value&gt; The value to compare. equal bool * Out parameter. Receives the comparison result. Description JS_LooselyEqual determines if v1 is loosely equal to v2 under the JavaScript == operator, as specified in ECMA 262-3 ?11.9.3. If the comparison attempt was successful, the method returns JS_TRUE and stores the result in *equal; otherwise it returns JS_FALSE. Comparing jsvals directly in C++, as in v1 == v2, does not produce a meaningful result, since it is possible for two distinct JSStrings or jsdoubles to represent the same string or number. See Also MXR ID Search for JS_LooselyEqual JS_StrictlyEqual JS_SameValue ...
JS_NewDoubleValue
l. If it is, JS_NewDoubleValue creates a bad jsval that might behave as desired in some cases but not others. The result is subject to garbage collection until you protect against it using a local root, an object property, or the JS_AddRoot function. This can be avoided by using the address of a rooted variable as rval. On success, JS_NewDoubleValue stores a numeric jsval in *rval and returns JS_TRUE. Otherwise it returns JS_FALSE and the value left in *rval is unspecified. See Also JS_NumberValue bug 549143 ...
JS_NewNumberValue
is created. Some space for the new value may be allocated from the JS garbage collection heap. In this case, the value is subject to garbage collection until you protect against it using a local root, an object property, or the JS_AddRoot function. This can be avoided by using the address of a rooted variable as rval. On success, JS_NewNumberValue stores a numeric jsval in *rval and returns JS_TRUE. Otherwise it returns JS_FALSE and the value left in *rval is unspecified. See Also JS_NumberValue bug 752223 ...
JS_NextProperty
in a request on this JSContext. iterobj JS::HandleObject The opaque iterator object returned by a previous call to JS_NewPropertyIterator. idp JS::MutableHandleId Out parameter. On success, *idp receives the name or index of the next property name; or JSID_VOID if there are no more enumerable properties to visit. Description On success, JS_NextProperty returns true, with *idp containing the id of the next enumerable own property to visit using iterobj, or JSID_VOID if there is no such property left to visit. On error, it returns false, and the value left in *idp is undefined. See Also bug 1081660 ...
JS_ObjectIsDate
to derive runtime information. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JSObject * JSObject that should be checked. Description JS_ObjectIsDate() can be used to check if you are dealing with a Date object, or a Date object used across compartments (or windows or sites, in the browser embedding). This function returns true if the object is a Date. See also MXR ID Search for JS_ObjectIsDate JS_NewDateObject JS_NewDateObjectMsec bug 625870 ...
JS_ObjectIsFunction
JSObject * The object to test. This must not be NULL. Description JS_ObjectIsFunction tests whether obj is a function object (faster than comparing obj's class name to Function, but equivalent unless someone has overwritten the Function identifier with a different constructor and then created instances using that constructor that might be passed in as obj). JS_ObjectIsFunction returns true if obj is a Function and false otherwise. If JS_ObjectIsFunction returns true, JS_ValueToFunction will always return non-null. JS_ObjectIsFunction always succeeds. Note that the result may be false even for some callable objects, such as regular expression objects or proxy objects See Also MXR ID Search for JS_ObjectIsFunction JS_ValueToFunction JS_ObjectIsFunction ...
JS_ObjectIsRegExp
erMonkey 17 Determine if a specified object is a RegExp. Syntax bool JS_ObjectIsRegExp(JSContext *cx, JS::HandleObject obj); Name Type Description cx JSContext * A context. obj JS::HandleObject The object to examine. Description JS_ObjectIsRegExp determines if a specified object, obj, is a RegExp object. If so, JS_ObjectIsRegExp returns true. Otherwise it returns false. See Also MXR ID Search for JS_ObjectIsRegExp JS_NewRegExpObject JS_NewUCRegExpObject RegExp bug 650931 ...
JS_PreventExtensions
, but the object simply refuses to be made non-extensible. For example, a proxy might refuse to be made non-extensible; this refusal would show up in the post-call value of *succeeded. var target = {}; var handler = { preventExtensions: function(obj) { return false; } }; var obj = new Proxy(target, handler); // bool succeeded; // bool rv = JS_PreventExtensions(cx, obj, &succeeded); // // rv == true, succeeded == false Note that as with most JSAPI methods, *succeeded is only set if JS_PreventExtensions returns true (that is, does not fail). Thus you should always check the return value of JS_PreventExtensions, and only if that is true check the value of *succeeded. See Also MXR ID Search for JS_PreventExtensions bug 1113369 -- added result parameter ...
JS_Remove*Root
rp void ** Address of the pointer variable to remove from the root set. This must have been passed to either JS_AddGCThingRoot or JS_AddNamedGCThingRoot. Description JS_RemoveRoot removes the variable that rp points to from the garbage collector's root set. The entry for rp is removed from the root set for the JSRuntime associated with the context cx. JS_RemoveRoot always returns JS_TRUE. See Also MXR ID Search for JS_RemoveValueRoot MXR ID Search for JS_RemoveStringRoot MXR ID Search for JS_RemoveObjectRoot MXR ID Search for JS_RemoveGCThingRoot bug 912581 ...
JS_RemoveRootRT
are protected from garbage collection. rp is thus a pointer to a pointer to a JS double, String, or Object. Do not pass a pointer to a JS double, string, or object -- you must pass a pointer to a pointer or a pointer to a jsval that's a GC thing. The entry for the GC thing rp points to is removed in the garbage collection hash table for the specified runtime, rt. JS_RemoveRootRT always returns JS_TRUE. See Also MXR ID Search for JS_RemoveRoot JSVAL_IS_GCTHING JS_AddRoot JS_AddNamedRoot JS_AddNamedRootRT JS_DumpNamedRoots, JS_RemoveRoot ...
JS_ReportPendingException
text in which the exception was thrown. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. Description If an exception is pending in the context cx, JS_ReportPendingException converts the exception to a string and reports it to the current error reporter. On success, it clears the exception as though by calling JS_ClearPendingException and returns true. If no exception is pending, or if a second error occurs while trying to report the first one, it returns false. This function can be used to catch exceptions thrown from scripts and send them to the error reporter to be logged or ignored. Note that certain JSAPI functions automatically do this for uncaught exceptions; see "Automatic handling of uncaught exceptions" in the JSAPI User Guide. See A...
JS_SealObject
ject are near-substitutes compatible with ECMAScript semantics, implementing semantics compatible with those of Object.freeze. Prevent modification of object fields. Syntax JSBool JS_SealObject(JSContext *cx, JSObject *obj, JSBool deep); Name Type Description cx JSContext * A context. obj JSObject * The object to seal. deep JSBool If true, seal all objects directly or indirectly reachable from obj's slots. Description JS_SealObject prevents all write access to the object, either to add a new property, delete an existing property, or set the value or attributes of an existing property. See Also bug 492849 ...
JS_SetElement
::MutableHandleValue In/out parameter. *vp is the value to assign to the element. JS_SetElement ordinarily leaves *vp unchanged, but a JSClass.addProperty hook or non-default setter may modify it. Obsolete since JSAPI 29 Description JS_SetElement assigns a value to a numeric property of an object. It behaves like the JavaScript expression obj[index] = v. On success, JS_SetElement returns true. On error or exception, JS_SetElement returns false. Obsolete since JSAPI 29 On success, JS_SetElement returns true and the value left in *vp is left unchanged unless an addProperty hook or setter modified it. On error or exception, JS_SetElement returns false and the value left in *vp is unspecified. See Also MXR ID Search for JS_SetElement bug 963167 - added v ...
JS_SetFunctionCallback
JSFunction *fun,const JSScript *scr, const JSContext *cx, int entering); Name Type Description fun const JSFunction * The JavaScript function being invoked or exited. scr const JSScript * The script being executed. cx JSContext * The JavaScript context in which the script is being run. entering int true if the callback is being called because the specified function is being invoked or false if the function is exiting. See Also MXR ID Search for JS_SetFunctionCallback Function tracing JS_GetFunctionCallback bug 1103269 ...
JS_SetGCCallback
ginal callback when the new callback is no longer needed. To restore the original callback, call JS_SetGCCallback a second time, and pass the old callback in as the cb argument. During each complete garbage collection cycle, the current GC callback is called four times: JSGC_BEGIN Start of GC. The callback may prevent GC from starting by returning false. But even if the callback returns true, the garbage collector may determine that GC is not necessary, in which case the other three callbacks are skipped. JSGC_MARK_END Obsolete since JSAPI 13 End of marking. The callback may use JS_IsAboutToBeFinalized to clean up weak references to JS objects (that is, pointers that are not traced by the GC). JSGC_FINALIZE_END Obsolete since JSAPI 13 End of finalization. JSGC_END...
JS_SetParent
rty. In fact, once an object is exposed to a script, the object's parent must not change. The JavaScript engine relies on this invariant. JS_SetParent has no way to check that this is the case, but nonetheless, applications must not call JS_SetParent on an object that has already been exposed to a script. If an application does this, the behavior is undefined. On success, JS_SetParent returns JS_TRUE. Otherwise, it reports an error or sets an exception and returns JS_FALSE. See Also MXR ID Search for JS_SetParent bug 1136980 - removed ...
JS_SetProperty
bj. This is done as follows. If the property has a JavaScript setter, it is called; otherwise, if it has a JavaScript getter, then an error is reported; otherwise the property's setter is called, passing the arguments (cx, obj, id, &v). If the setter succeeds and the property has a stored value, then the value left in v becomes the stored value of the property. On success, JS_SetProperty returns true, and the value in v is left unchanged unless a hook or setter modified it. On error or exception, it returns false, and the value left in v is unspecified. Internally, property assignment, including all the behavior described above, is implemented by obj's JSObjectOps.setProperty callback. See Also MXR ID Search for JS_SetProperty MXR ID Search for JS_SetUCProperty MXR ID Search for JS_Set...
JS_SetPropertyAttributes
properties, and is cast to a const char *. 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. Then, if the property exists, but is associated with a different object, JS_SetPropertyAttributes returns JS_TRUE. Otherwise, it sets foundp to JS_TRUE, and attempts to set the attributes as specified. If the attributes can be set, JS_SetPropertyAttributes returns JS_TRUE. If not, it returns JS_FALSE. To get the attributes of a property, use JS_GetPropertyAttributes. Property attributes bug 893186 ...
JS_SetPrototype
are shared by similar JS object instances. Ordinarily you set a prototype for an object when you create the object with JS_NewObject, but if you do not set a prototype at that time, you can later call JS_SetPrototype to do so. obj is a pointer to an existing JS object, and proto is a pointer to second existing object upon which the first object is to be based. On success, JS_SetPrototype returns true. Otherwise it returns false. Take care not to create a circularly-linked list of prototypes using this function, because such a set of prototypes cannot be resolved by the JavaScript engine and can easily lead to an infinite loop. To get an object's prototype, use JS_GetPrototype. See Also LXR ID Search JS_GetPrototype ...
JS_SetRegExpInput
String input, bool multiline); Name Type Description cx JSContext * The context. Requires request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. obj JS::HandleObject A pointer to a global object. input JS::HandleString A pointer to the input string. multiline bool true if input is multiline. Description JS_SetRegExpInput sets the pending input string of the built-in RegExp object to the specified input string. The JSREG_MULTILINE is set to multiline parameter, and other flags are all reset. On successful, JS_SetRegExpInput returns true, otherwise returns false. See Also MXR ID Search for JS_SetRegExpInput JS_NewRegExpObject JS_NewUCRegExpObject ...
JS_StrictlyEqual
be in a request on this JSContext. v1, v2 JS::Handle&lt;JS::Value&gt; / jsval The value to compare. equal bool * Out parameter. Receives the comparison result. Description JS_StrictlyEqual determines if v1 is strictly equal to v2 under the JavaScript === operator, as specified in ECMA 262-3 ?11.9.6. If the comparison attempt was successful, the method returns true and stores the result in *equal; otherwise it returns false. Comparing jsvals directly in C++, as in v1 == v2, does not produce a meaningful result, since it is possible for two distinct JSStrings or jsdoubles to represent the same string or number. See Also MXR ID Search for JS_StrictlyEqual JS_LooselyEqual JS_SameValue bug 1132045 -- use handle ...
JS_StringEqualsAscii
String to compare. asciiBytes const char * ASCII string to compare with. match bool * (JS_StringEqualsAscii only) Out parameter. Received the comparison result. Description JS_StringEqualsAscii and JS_FlatStringEqualsAscii compare string str and ASCII string asciiBytes. On successful, JS_StringEqualsAscii stores the comparison result into *match and returns true, otherwise returns false. JS_FlatStringEqualsAscii always succeeds, and returns the comparison result. See Also MXR ID Search for JS_StringEqualsAscii MXR ID Search for JS_FlatStringEqualsAscii bug 609440 ...
JS_StringHasBeenInterned
This article covers features introduced in SpiderMonkey 17 Determine if string is interned. Syntax bool JS_StringHasBeenInterned(JSContext *cx, JSString *str); Name Type Description str JSString * A string to examine. Description JS_StringHasBeenInterned returns true if the string str is interned. See Also MXR ID Search for JS_StringHasBeenInterned bug 724810 ...
JS_StringHasLatin1Chars
This article covers features introduced in SpiderMonkey 38 Determine if a string's characters are stored as Latin1. Syntax bool JS_StringHasLatin1Chars(JSString *str); Name Type Description str JSString * String to examine. Description JS_StringHasLatin1Chars returns true iff the string's characters are stored as Latin1. String characters are stored as either Latin1Char (8-bit) or char16_t (16-bit). Clients can use JS_StringHasLatin1Chars and can then call either the Latin1* or TwoByte* functions. Some functions like JS_CopyStringChars and JS_GetStringCharAt accept both Latin1 and TwoByte strings. See Also MXR ID Search for JS_StringHasLatin1Chars bug 1032726 ...
JS_StringIsFlat
This article covers features introduced in SpiderMonkey 38 Determine if a string is flattened. Syntax bool JS_StringIsFlat(JSString *str); Name Type Description str JSString * String to examine. Description JS_StringIsFlat returns true if the string is flattened. See Also MXR ID Search for JS_StringIsFlat bug 1037869 ...
JS_ValueToBoolean
s JSContext. v jsval The value to convert. bp JSBool * Out parameter. On success, *bp receives the converted boolean value. Description JS_ValueToBoolean converts a specified JavaScript value, v, to a boolean value. It implements the ToBoolean operator specified in ECMA 262-3 ?9.2. On success, JS_ValueToBoolean stores the converted value in *bp and returns JS_TRUE. 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). This is the behavior specified in ECMA 262-3 ?9.2. See related discussion on Google Groups. See Also MXR ID Search for JS_ValueToBoolean JS::ToBoolean bug 93455...
JS_ValueToECMAInt32
nt16 implements the ToUint16 operator specified in ECMA 262-3 9.7. All three functions first convert v to a floating-point number as if by calling JS_ValueToNumber; NaN values are then converted to zero. If that succeeds, the result is then converted to the target integer type. This second conversion cannot fail. On success, JS_ValueToECMAInt32 stores the converted value in *ip and returns JS_TRUE. On error or exception, it returns JS_FALSE, and the value left in *ip is undefined. See Also JS::ToUint16 JS::ToInt32 JS::ToUint32 JS::ToInt64 JS::ToUint64 JS::ToNumber bug 933810 bug 933946 ...
JS_ValueToId
d string jsid based on the value of v. If v is not a string, it is converted to a string as if by calling JS_ValueToString. JS_StringToId and JS_CharsToId convert a specified string to a jsid. JS_IndexToId converts a specified integer index to an integer jsid. JS::ProtoKeyToId converts a specified prototype key to a jsid. On success, JS_ValueToId stores the converted value in *idp and returns true. Otherwise it returns false. The inverse of JS_ValueToId is JS_IdToValue. MXR ID Search for JS_ValueToId See Also MXR ID Search for JS_IdToValue MXR ID Search for JS_StringToId MXR ID Search for JS_IndexToId MXR ID Search for JS_CharsToId MXR ID Search for JS::ProtoKeyToId JS_ValueToId bug 698495 - added JS_IndexToId bug 830500 - added JS_CharsToId bug 959787 - added JS_StringToId ...
JS_ValueToInt32
integer (-2147483648 to 2147483647). First it converts v to a floating-point number as if by calling JS::ToNumber. If the result is NaN, an infinity, or a number outside the 32-bit range, JS_ValueToInt32 reports an error and conversion fails. Otherwise, the floating-point number is rounded to the nearest integer value. On success, JS_ValueToInt32 stores the converted value in *ip and returns JS_TRUE. On error or exception, it returns JS_FALSE, and the value left in *ip is undefined. JS_ValueToInt32 is pre-ECMA-262 Edition 1, and rounds differently than JS_ValueToECMAInt32 and JS::ToInt32. This routine was added for layers-based graphics programming in Netscape 4, but unless you know you need its rounding behavior, it is best to avoid it in favour of JS::ToInt32. JS::ToInt32 rounds as specif...
JS_ValueToObject
st on this JSContext. v JS::HandleValue The value to convert. objp JS::MutableHandleObject Out parameter. On success, *objp receives NULL or a pointer to the resulting object. Description JS_ValueToObject converts a specified JavaScript value, v, to an object. On success, this function stores either NULL or a pointer to the resulting object in *objp and returns true. Otherwise it returns false and the value left in *objp is unspecified. If v is JSVAL_NULL or JSVAL_VOID, the result is NULL. If v is a boolean value, a number, or a string, the result is a new wrapper object of type Boolean, Number, or String. Otherwise v is an object, and the result depends on the object. If v is a native JavaScript Object, this calls the object's valueOf method, if any. In...
JS_ValueToString
request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. v jsval The value to convert. Description JS_ValueToString converts a specified JavaScript value, v, to a string. It implements the ToString operator specified in ECMA 262-3 ?9.8. The result is like the JavaScript expression ""+v. If v is already a string, conversion succeeds. If v is true, false, null, or undefined, conversion succeeds, and the result is the string "true", "false", "null", or "undefined", accordingly. If v is a number, conversion succeeds, and the result is a string representation of that number as specified in ECMA 262-3 ?9.8.1. This might be "NaN", "Infinity", or "-Infinity". Otherwise the result is a decimal representation of the number, possibly using exponen...
SpiderMonkey 31
ficant changes: Many of the garbage collector changes require type signature changes to JSAPI methods: specifically introducing JS::Rooted, JS::Handle, and JS::MutableHandle types. These types, with the appropriate parametrizations, can roughly be substituted for plain types of GC things (values, string/object pointers, etc.). 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. Many JSClass and js::Class instances are now explicitly const, and several APIs have been updated to use const JSClass * and const js::Class * pointers. All references to shortid/tinyid have been removed. That includes the APIs JS_DefinePropertyWithTinyId and JS_DefineUCPropertyWithTinyId as well as the JSPr...
Split object
global object is returned in this case. For consistency with the rule, if that global object is an outer object, SpiderMonkey returns the inner object instead. Inner and outer objects are in certain other respects the same object: If Object.hasOwnProperty is called on an inner object, and the named property is found on an outer object, that's considered close enough and hasOwnProperty returns true. Note that none of the rules listed here affects ordinary property accesses. SpiderMonkey's split object support, by itself, does not cause inner object properties to appear on the outer object or vice versa. Split objects that need this behavior must implement it in custom JSClass hooks. In the case of window, each half has custom hooks. ...
TPS Pref Lists
A prefs asset list is an array of objects with name and value keys, representing browser preferences. For example: var prefs1 = [ { name: "browser.startup.homepage", value: "http://www.getfirefox.com" }, { name: "browser.urlbar.maxRichResults", value: 20 }, { name: "browser.tabs.autoHide", value: true } ]; Pref lists and phase actions The only actions supported for preference asset lists are modify and verify: Prefs.modify Prefs.verify Sync only syncs certain preferences. To find the list of valid preferences, go to about:config on a browser that has Weave installed, and search for services.sync.prefs.sync. For a more detailed test example, see the TPS prefs unit test. ...
TPS Tests
o options are passed, a default sync operation is performed. Otherwise, a special sync can be performed if one of the following are passed: SYNC_WIPE_SERVER, SYNC_WIPE_CLIENT, SYNC_RESET_CLIENT. This will cause TPS to set the firstSync pref to the relevant value before syncing, so that the described actionwill take place Logger.logInfo(msg) Logs the given message to the TPS log. Logger.AssertTrue(condition, msg) Asserts that condition is true, otherwise an exception is thrown and the test fails. Logger.AssertEqual(val1, val2, msg) Asserts that val1 is equal to val2, otherwise an exception is thrown and the test fails. Custom functions You can also write your own functions to be called as actions. For example, consider the first action in the phase above: [Bookmarks.add, bookmarks_i...
Web Replay
ng on whether the tab is currently recording (red) or replaying (blue). The current position within the recording is shown on the timeline with a progress indicator. Console error/messages are marked on the timeline and can be clicked to seek to that point. Advanced Options Preferences devtools.recordreplay.enableRewinding When disabled, Firefox records a page signifcantly faster. default true. devtools.recordreplay.fastLogpoints When enabled, Firefox Web Replay evaluates logpoints consecutively. Logpoints cannot have side-effects or diverge from the recording in any othe way in this mode. default false. devtools.recordreplay.logging When enabled, Firefox will log Web Replay's internal actions to the terminal, which is helpful when debugging hangs and crashes. default false Archit...
Redis Tips
This document is a collection of some examples and tips for using redis, the open-source data structure server. It is intended primarily for developers, and deliberately omits some topics that will be important in any redis deployment, like security and backups. Some Uses for Redis Data Types You may have heard of Redis referred to as a NoSQL Database. Technically, this is true: It's a database that doesn't use SQL. But the statement is meaningless. It is also true that ice cream is a food that isn't made from whale meat. But obviously, calling ice cream a NoWhale Food doesn't give you any sense of how good the ice cream is, or what sets it apart from other kinds of food that aren't made from whale meat but that are also very unlike ice cream -- it just gives the whaling indus...
Setting up an update server
for more information on building Firefox locally. These changes will need to be made in order to use the locally built MAR: Put this line in the mozconfig file in root of the build directory (create it if it does not exist): ac_add_options --disable-verify-mar Several files contain a line that must be uncommented. Open them and find this line: #DEFINES['DISABLE_UPDATER_AUTHENTICODE_CHECK'] = True. Delete the # at the beginning of the line to uncomment it. These are the files that must be changed: toolkit/components/maintenanceservice/moz.build toolkit/mozapps/update/tests/moz.build Firefox should otherwise be built normally. After building, you may want to copy the installation of Firefox elsewhere. If you update the installation without moving it, attempts at further incr...
ROLE_ALERT
ically respond to the role by reading the entire onscreen contents of containers advertising this role. Should be used for warning dialogs, etc. Mapped to AT-SPI: ROLE_ALERT ATK: ATK_ROLE_ALERT MSAA/IA2: ROLE_SYSTEM_ALERT UA: NSAccessibilityWindowRole Events EVENT_ALERT - fires when the widget is shown. Used by ARIA: alert, alertdialog XUL: <notification/>, <panel noautofocus = "true"/> ...
XUL Accessibility
d and it allows to have accessible value then aria-valuetext or aria-valuenow are used If the element is XLink then value is generated from link location actions If the element is XLink then jump action is exposed If the element has registered click event handler then click action is exposed XUL Elements notification Used to display an informative message. Role ROLE_ALERT <panel noautofocus = "true" /> ROLE_ALERT ...
Embedded Dialog API
the application's own. Skins are very rich and capable; this scheme can probably be made to work for nearly all applications. Many embeddors however choose to implement their own dialogs, and this is of course the only way to gain complete control and consistency. An embedding application may implement its own version of all dialogs in Gecko. (Note that at time of writing this may not be strictly true; work continues on this topic.) All overrideable dialogs are implemented by Gecko as a component. A default (XUL) implementation of each is provided as part of the Gecko package. To replace these default dialogs with its own versions, an application must replace the component which implements them. And note that if an application chooses to replace one of Gecko's default dialog components, that a...
Feed content access API
However, you could also parse it from a file using parseFromSt...
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...
Using the Places annotation service
getPageAnnotationNames(aURI, count, result); getItemAnnotationNames(aItem, count, result); Retrieves a list of all the annotations on a given URI or id. C++ callers will want to use GetPageAnnotationNamesTArray which returns a COM array, making memory management much easier and reducing the chance of leaks. pageHasAnnotation(aURI, aName); itemHasAnnotation(aItemId, aName); Returns true if the page/item has an annotation with the given name. removePageAnnotation(aURI, aName); removeItemAnnotation(aItemId, aName); Removes a given annotation from a page/item. removePageAnnotations(aURI); removeItemAnnotations(aItemId); Removes all the annotations from a given page/item. copyPageAnnotations(aSourceURI, aDestURI, aOverwriteDest); copyItemAnnotations(aSourceIte...
Using the Places history service
en displayed in the UI. This is used for bookmark titles.This function may be removed if the bookmark service is changed. nsINavHistoryService.setPageDetails: Used to set all of the global bits associated with a URL. It is designed for synchronizing or backup services. Basic querying of the history system nsIGlobalHistory2.isVisited: Called by Gecko when rendering links. When isVisited returns true, the link gets the "visited" style. Otherwise, the link is colored as unvisited. nsIGlobalHistory3.getGeckoFlags: Retrieves information previously set using setGeckoFlags. It is not yet implemented in the Places history system. nsIBrowserHistory.lastPageVisited: Contains the URI of the last page visited. This is used when the preference is set that causes the last page in new windows. nsIBrows...
extIExtension
on the FUEL (Firefox), STEEL (Thunderbird) and SMILE (SeaMonkey) pages. Method overview FIXME: Attributes Attribute Type Description id readonly attribute AString The id of the extension. name readonly attribute AString The name of the extension. enabled readonly attribute boolean True if the extension is currently enabled. version readonly attribute AString The version number of the extension. firstRun readonly attribute boolean Indicates whether this is the extension's first run after install prefs readonly attribute extIPreferenceBranch The preferences object for the extension. Defaults to th...
extISessionStorage
sIVariant get(in AString aName, in nsIVariant aDefaultValue) Attributes Attribute Type Description events readonly attribute extIEvents The events object for the storage supports: "change" Methods has() Determines if a storage item exists with the given name. boolean has(in AString aName) Parameters aName The name of an item Return value true if an item exists with the given name, false otherwise. set() Sets the value of a storage item with the given name. void set(in AString aName, in nsIVariant aValue) Parameters aName The name of an item Return value get() Gets the value of a storage item with the given name. Returns a default value if the item does not exist. nsIVariant get(in AString aName, in nsIVariant aDefaultV...
Accessing the Windows Registry Using XPCOM
the startWatching(), stopWatching(), and hasChanged() methods. You must call startWatching() for the key to be monitored. The method takes one parameter, a boolean indicating whether child keys should be watched. After that, you can call hasChanged() to determine whether or not you need to reread the value. Calling hasChanged() automatically resets the watch, so you can be sure that if it returns true there are changes. This example demonstrates a trivial registry value cache for one key: var cache = {}; function readRegistryValueNoCache(wrk, value) { switch (wrk.getValueType(value)) { case wrk.TYPE_STRING: return wrk.readStringValue(value); case wrk.TYPE_BINARY: return wrk.readBinaryValue(value); case wrk.TYPE_INT: return wrk.readIntValue(value); case wrk...
XPCOM array guide
Mozilla › Tech › XPCOM › Guide › Arrays
existing callback-style code however. One particularly nice thing about the callback mechanism is that it is typesafe. 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; } ... // enumerate to find the object ClosureObject closureObject = { 0 }; if (!mElements.EnumerateForwards(getFirstVisible, closureObject)) processElement(closureObject->element); ... Enumerators A nsISimpleEnumerator can be created to provide access to a nsCOMArray<T>. When the enumerator is created, it takes a snapshot of the elements in the array, so that the enumerator can outlive the...
Avoiding leaks in JavaScript XPCOM components
The _filterRadioGroup object is a JavaScript function that is wrapped so that XPCOM code can use it. The reason closures matter here is th...
An Overview of XPCOM
manage reference counting. NS_ADDREF Calls AddRef on an nsISupports object. NS_IF_ADDREF Same as above but checks for null before calling AddRef. NS_RELEASE Calls Release on an nsISupports object. NS_IF_RELEASE Same as above but check for null before calling Release. Status Codes These macros test status codes. NS_FAILED Return true if the passed status code was a failure. NS_SUCCEEDED Returns true is the passed status code was a success. Variable Mappings nsrefcnt Default reference count type. Maps to a 32-bit integer. nsresult Default error type. Maps to a 32-bit integer. nsnull Default null value. Common XPCOM Error Codes NS_ERROR_NOT_INITIALIZED ...
Building the WebLock UI
above illustrates. In XUL individual <radio/> elements are contained within a parent element called <radiogroup/>. Grouping radio elements together creates the toggling UI by requiring that one or another of the elements be selected, but not both. The XUL that defines the radiogroup in the web lock manager dialog is this: <radiogroup> <radio label="lock"/> <radio label="unlock" selected="true"/> </radiogroup> Since the WebLock component always starts up in the unlocked position, you can add the selected="true" attribute and value on the unlock radio button and reset it dynamically as the user takes action. Site Adding UI The next step is to create that part of the user interface that lets you add a new site to the white list. There are other, more sophisticated ways to do this; yo...
Components.utils.exportFunction
ted function is called each argument, including this, is checked to make sure that the caller subsumes that argument. This prevents passing cross-origin objects (like Window or Location) to privileged functions, since the privileged code will have full access to those objects and might unintentionally do something dangerous. This provision can be overridden by passing { allowCrossOriginArguments: true } to exportFunction. Example Export to global scope This add-on script defines a function, then exports it to a content window: // addon-script.js var salutation = "hello "; function greetme(user) { return salutation + user; } Components.utils.exportFunction(greetme, contentWindow, {defineAs: "foo"}); Instead of using defineAs, the script can assign the result of exportFunction to an o...
Components.utils.import
fied code each time it is invoked, with the caller's global object. Components.utils.import evaluates the code of each module only once, in its own scope. For example: var scope1 = {}, scope2 = {}; Components.utils.import("resource://gre/modules/JSON.jsm", scope1); Components.utils.import("resource://gre/modules/JSON.jsm", scope2); assert(scope2.XPCOMUtils === scope1.XPCOMUtils); ...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. This means Components.utils.import is bet...
Components.utils.reportError
unction myDump(aMessage) { var consoleService = Components.classes["@mozilla.org/consoleservice;1"] .getService(Components.interfaces.nsIConsoleService); consoleService.logStringMessage("My component: " + aMessage); } Firefox 3: The Error Console will not display chrome errors by default. To show them, set the preference 'javascript.options.showInConsole' to true, or use nsConsoleService instead to show a message. Firefox 4: The preference 'javascript.options.showInConsole' is set to true by default in this version. Examples Usage in an exception handler: try { this.could.raise.an.exception; } catch(e) { Components.utils.reportError(e); // report the error and continue execution } Sending debugging messages to the Error Console: Components.util...
Components.utils.waiveXrays
y, this function just returns obj. ...
HOWTO
returns. Solution 1. 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. In all callbacks where your script is finished, i.e. both success and error callbacks, put: gScriptDone = true; If you forget some condition where your script should exit but you don't add this statement, your script will hang (busy wait). This is of course a massive, ugly hack prone to error, but this is what the xp...
Language bindings
The scriptable methods on the nsIComponentManager interface can be called directly on this object.Components.resultsComponents.results is a read-only object whose properties are the names listed as the first parameters of the macros in js/xpco...
nsScriptableInputStream
m Remarks This component should be accessed via the XPCOM Component Manager. Example Code const nsIScriptableInputStream = Components.interfaces.nsIScriptableInputStream; function consumeStream(inputStream) { var factory = Components.classes["@mozilla.org/scriptableinputstream;1"]; var sis = factory.createInstance(nsIScriptableInputStream); sis.init(inputStream); try { while (true) { var chunk = sis.read(512); if (chunk.length == 0) break; // ok, chunk now contains a portion of the stream's data. // Do something with it! } } catch (e) { dump("Error: failed reading from stream:\n" + e + "\n"); } } See Also nsIScriptableInputStream ...
NS_NewLocalFile
aResult ); Parameters aPath [in] A UTF-16 string object that specifies an absolute filesystem path. This path does not need to reference an existing file. It is an error to pass a relative filesystem path. aFollowLinks [in] This attribute will determine if the nsILocalFile instance will automatically resolve symbolic links. This parameter has no effect on UNIX systems. On Windows, passing true causes shortcuts to be automatically resolved, and on MacOS, passing true causes finder aliases to be automatically resolved. aResult [out] A reference to the newly created nsILocalFile instance. Return Values The NS_NewLocalFile function returns NS_OK if successful. Otherwise, it returns an error code. NS_ERROR_FILE_UNRECOGNIZED_PATH Indicates that the specified path is invalid. This er...
NS_NewNativeLocalFile
should be encoded using ASCII or the multibyte character coding corresponding to the native filesystem. This path does not need to reference an existing file. It is an error to pass a relative filesystem path. aFollowLinks [in] This attribute will determine if the nsILocalFile instance will automatically resolve symbolic links. This parameter has no effect on UNIX systems. On Windows, passing true causes shortcuts to be automatically resolved, and on MacOS, passing true causes finder aliases to be automatically resolved. aResult [out] A reference to the newly created nsILocalFile instance. Return Values The NS_NewNativeLocalFile function returns NS_OK if successful. Otherwise, it returns an error code. NS_ERROR_FILE_UNRECOGNIZED_PATH Indicates that the specified path is invalid. T...
nsACString_internal
of the string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters char** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(char, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters char aChar PRInt32 aOffset ...
nsAString_internal
e string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters PRUnichar** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(PRUnichar, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters PRUnichar aChar PRInt32 aOffset ...
nsDependentCSubstring
of the string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters char** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(char, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters char aChar PRInt32 aOffset ...
nsDependentSubstring
e string is used. The caller MAY modify the characters at the returned address (up to but not exceeding the length of the string). @returns The length of the buffer in characters or 0 if unable to satisfy the request due to low-memory conditions. Parameters PRUnichar** data PRUint32 newLen SetIsVoid void SetIsVoid(PRBool) - source string data is never null, but can be marked void. if true, the string will be truncated. @see nsTSubstring::IsVoid Parameters PRBool <anonymous> StripChar void StripChar(PRUnichar, PRInt32) - source This method is used to remove all occurrences of aChar from this string. @param aChar -- char to be stripped @param aOffset -- where in this string to start stripping chars Parameters PRUnichar aChar PRInt32 aOffset ...
HeapMinimize
<< XPCOM API Reference Summary The HeapMinimize function attempts to shrink the size of the heap. static nsresult HeapMinimize( PRBool aImmediate ); Parameters aImmediate [in] If true, heap minimization will occur immediately if the call was made on the main thread. If false, the flush will be scheduled to happen when the app is idle. Return Values This function return NS_OK if successful. Otherwise, it returns an error code. ...
RefPtr
} See this post for more details. ...
IAccessibleHyperlink
extual representation of the hyperlink starts. The returned value is related to the IAccessibleText interface of the object that owns this hyperlink. Return value S_OK. valid() Returns whether the target object referenced by this link is still valid. This is a volatile state that may change without sending an appropriate event. [propget] HRESULT valid( [out] boolean valid ); Parameters valid true if the referenced target is still valid and false otherwise. This has also been used to indicate whether or not the URI of the anchorTarget is malformed. Return value S_FALSE if there is nothing to return, [out] value is false. S_OK. See also IAccessibleAction IAccessibleText ...
IAccessibleTableCell
RESULT columnIndex( [out] long columnIndex ); Parameters columnIndex Returns the 0 based column index of the cell of the specified cell or the index of the first column if the cell spans multiple columns. Return value S_OK. isSelected() Returns a boolean value indicating whether this cell is selected. [propget] HRESULT isSelected( [out] boolean isSelected ); Parameters isSelected Returns true if the specified cell is selected and false otherwise. Return value S_OK. rowColumnExtents() Gets the row and column indexes and extents of this cell accessible and whether or not it is selected. This is a convenience function. It is not mandatory to implement it. [propget] HRESULT rowColumnExtents( [out] long row, [out] long column, [out] long rowExtents, [out] long columnExtents, [ou...
amIWebInstaller
o be installed. aHashes The hashes for the add-ons to be installed. aNames The names for the add-ons to be installed. aIcons The icons for the add-ons to be installed. aCallback Optional An optional callback to notify about installation success and failure. aInstallCount Optional An optional argument including the number of add-ons to install. Return value true if the installation was successfully started. isInstallEnabled() Checks if installation is enabled for a web page. boolean isInstallEnabled( in AString aMimetype, in nsIURI aReferer ); Parameters aMimetype The MIME type for the add-on to be installed. aReferer The URI of the web page for which to see if installation is allowed. Return value true if installation is enabled. ...
imgICache
e will not be present in the cache returned from a call with a null parameter). Method overview void clearCache(in boolean chrome); nsIProperties findEntryProperties(in nsIURI uri); void removeEntry(in nsIURI uri); Methods clearCache() Evict images from the cache. void clearCache( in boolean chrome ); Parameters chrome If true, evict only chrome images. If false, evict everything except chrome images. findEntryProperties() Find Properties Used to get properties such as 'type' and 'content-disposition' 'type' is a nsISupportsCString containing the images' mime type such as 'image/png' 'content-disposition' will be a nsISupportsCString containing the header If you call this before any data has been loaded from a URI, it...
imgILoader
nd data to. Can be null, in which case imagelib has found a cached image and is not interested in the data. aChannel will be canceled for you in this case. Return value supportImageWithMimeType() Checks if a decoder for the an image with the given mime type is available. boolean supportImageWithMimeType( in string mimeType ); Parameters mimeType The type to find a decoder for. Return value true if a decoder is available, false otherwise. ...
mozIJSSubScriptLoader
oaded script will be created as global variables in the caller (ie.: in the caller's global object). This object will be searched for variables that cannot be resolved in the subscript scope. charset string An optional string to specify the character encoding of the file. If absent, the file is interpreted as ASCII. ignoreCache boolean If present and set to true, the cache will be bypassed when reading the file. See also Appendix D: Loading Scripts ...
mozIPersonalDictionary
id addWord( in wstring word, in wstring lang ); Parameters word The word to add to the dictionary. lang The language of the word. Note that this parameter is currently unused. check() Checks a Unicode string. boolean check( in wstring word, in wstring lang ); Parameters word The word to check. lang The language of the word. Note that this parameter is currently ignored. Return value true if the word is in either the dictionary or the ignore list, false if it is not in either list. endSession() Clears the ignore list. void endSession(); Parameters None. getCorrection() Gets a list of previous corrections for the word. void getCorrection( in wstring word, [array, size_is(count)] out wstring words, out PRUint32 count ); Parameters word The word to get the list of correction...
mozIRepresentativeColorCallback
Inherits from: nsISupports Last changed in Gecko 17.0 (Firefox 17.0 / Thunderbird 17.0 / SeaMonkey 2.14) Method overview void onComplete(in boolean success, [optional] in unsigned long color); Methods onComplete() Will be called when color analysis finishes. void onComplete( in boolean success, [optional] in unsigned long color ); Parameters success True if analysis was successful, false otherwise. Analysis can fail if the image is transparent, imageURI doesn't resolve to a valid image, or the image is too big. color The representative color as an integer in RGB form. e.g. 0xFF0102 == rgb(255,1,2). If success is false, color is not provided. ...
mozISpellCheckingEngine
IFile dir ); Parameters dir An nsIFile object indicating the directory from which to add dictionaries. check() Checks a word to determine if it's spelled correctly. When this changes, the spell checker sends a "spellcheck-dictionary-update" notification. boolean check( in wstring word ); Parameters word A word to check for correct spelling. Return value Returns true if word is spelled correctly according to the dictionary attribute, and returns false if word is misspelled. getDictionaryList() Gets the list of dictionaries. void getDictionaryList( [array, size_is(count)] out wstring dictionaries, out PRUint32 count ); Parameters dictionaries A list of dictionaries supported by this spell checker. The dictionary attribute can be set to one ...
mozIStorageAggregateFunction
t32 mean = total / mNumbers.Length(); nsTArray<PRInt64> data(mNumbers); for (PRUint32 i = 0; i < data.Length(); i++) { PRInt32 value = data[i] - mean; data[i] = value * value; } total = 0; for (PRUint32 i = 0; i < data.Length(); i++) total += data[i]; nsCOMPtr<nsIWritableVariant> result = do_CreateInstance("@mozilla.org/variant;1"); NS_ENSURE_TRUE(result, NS_ERROR_OUT_OF_MEMORY); rv = result->SetAsDouble(sqrt(double(total) / double(data.Length()))); NS_ENSURE_SUCCESS(rv, rv); NS_ADDREF(*_result = result); return NS_OK; } private: nsTArray<PRInt32> mNumbers; }; // Now, register our function with the database connection. nsCOMPtr<mozIStorageFunction> func = new standardDeviationFunc(); NS_ENSURE_TRUE(func, NS_ERROR_OUT...
mozIStoragePendingStatement
view void cancel(); Methods cancel() Cancels the pending statement. Fails only if you attempt to cancel the operation more than once. Note: For read statements, such as SELECT, once you cancel the statement, you will receive no further notifications about results. void cancel(); Parameters None. Return value In versions of Gecko prior to Gecko 1.9.2, this returned a boolean value that was true if the query was canceled successfully or false if not. Starting with Gecko 1.9.2, this information is no longer provided and the method doesn't return a value. See also Storage mozIStorageConnection mozIStorageStatement ...
mozIStorageProgressHandler
ss() The onProgress() method is called periodically while an sqlite operation is ongoing. This allows you to monitor the progress and possibly display status information to the user. boolean onProgress( in mozIStorageConnection aConnection ); Parameters <tt>aConnection</tt> A mozIStorageConnection connection indicating the connection for which the callback was invoked. Return value Return true to abort the request or false to allow it to continue. See also Storage mozStorage introduction and how-to article mozIStorageConnection Database connection to a specific file or in-memory data storage mozIStorageStatement Create and execute SQL statements on a SQLite database. mozIStorageValueArray Wraps an array of SQL values, such as a result row. mozIStorageFunction Create a new SQLite fu...
mozIStorageStatement
t before being reused. boolean executeStep(); Return value Returns a boolean indicating whether there are more rows or not. Row data may be accessed using mozIStorageValueArray methods on the statement. step() Identical to calling executeStep(), and then calling reset() when no more rows are returned. Note: This method may only be called from JavaScript code. boolean step() Return value true if there are more rows left in the results, otherwise false. execute() Execute the query, ignoring any results. This is accomplished by calling executeStep(), and then calling reset(). void execute(); See also Storage introduction and how-to article mozIStorageConnection Database connection to a specific file or in-memory data storage mozIStorageValueArray Wraps an array of SQL values,...
mozIStorageStatementWrapper
this. Methods initialize() This method initializes this wrapper with aStatement. void initialize( in mozIStorageStatement aStatement ); Parameters aStatement The statement to be initialized. reset() This method resets the wrapped statement. void reset(); Parameters None. step() This method steps the wrapped statement. boolean step(); Parameters None. Return value Returns true if the stepping the wrapped statement was successful, otherwise returns false. execute() This method executes the wrapped statement. void execute(); Parameters None. See also Storage mozIStorageStatement mozIStorageStatementRow mozIStorageStatementParams ...
mozIStorageValueArray
meters aIndex The zero-based numerical index for the column to get the data from. aDataSize The size of the returned array. Return value The blob for the specified entry. getIsNull() Checks if given column index is NULL. boolean getIsNull( in unsigned long aIndex ); Parameters aIndex The zero-based numerical index for the column to get the data from. Return value Returns true if the column specified by aIndex is NULL, or false otherwise. See also Storage introduction and how-to article mozIStorageConnection Database connection to a specific file or in-memory data storage mozIStorageStatement Create and execute SQL statements on a SQLite database. mozIStorageFunction Create a new SQLite function. mozIStorageAggregateFunction Create a new SQLite aggregate functi...
mozIVisitStatusCallback
See also mozIAsyncHistory ...
nsIAccessibleTextChangeEvent
...
nsIAccessibleValue
y. minimumIncrement double Read only. minimumValue double Read only. Methods setCurrentValue() Obsolete since Gecko 1.9 (Firefox 3) Return a success condition of the value getting set. That is if the value is within the range of minimumValue - maximumValue. boolean setCurrentValue( in double value ); Parameters value New value for current value. Return value true if the value is within the range of minimumValue - maximumValue, false if it is not. ...
nsIApplicationCache
Read only. clientID ACString The client ID for this application cache. Clients can open a session with nsICacheService.createSession() using this client ID and a storage policy of STORE_OFFLINE to access this cache. Read only. groupID ACString The group ID for this cache group. This is the URI of the cache manifest file. Read o...
nsIAsyncInputStream
caller must then wait for the stream to have some data to read. If the stream implements nsIAsyncInputStream, then the caller can use this interface to request an asynchronous notification when the stream becomes readable or closed (via the AsyncWait() method). While this interface is almost exclusively used with non-blocking streams, it is not necessary that nsIInputStream.isNonBlocking() return true. Nor is it necessary that a non-blocking nsIInputStream implementation also implement nsIAsyncInputStream. Method overview void asyncWait(in nsIInputStreamCallback aCallback, in unsigned long aFlags, in unsigned long aRequestedCount, in nsIEventTarget aEventTarget); void closeWithStatus(in nsresult aStatus); Constants Constant Value Description WAIT_CLOSURE_ONLY (1<<0) If passed to a...
nsIAsyncOutputStream
The caller must then wait for the stream to become writable. If the stream implements nsIAsyncOutputStream, then the caller can use this interface to request an asynchronous notification when the stream becomes writable or closed (via the AsyncWait() method). While this interface is almost exclusively used with non-blocking streams, it is not necessary that nsIOutputStream.isNonBlocking() return true. Nor is it necessary that a non-blocking nsIOutputStream implementation also implement nsIAsyncOutputStream. Method overview void asyncWait(in nsIOutputStreamCallback aCallback, in unsigned long aFlags, in unsigned long aRequestedCount, in nsIEventTarget aEventTarget); void closeWithStatus(in nsresult reason); Constants Constant Value Description WAIT_CLOSURE_ONLY (1<<0) If passed to...
nsIAuthModule
ver. Calls to this method are used to protect items of data to be sent to the server. void wrap( [const] in voidPtr aInToken, in unsigned long aInTokenLength, in boolean confidential, out voidPtr aOutToken, out unsigned long aOutTokenLength ); Parameters aInToken A buffer containing the data to be sent to the server. aInTokenLength The length of the input token. confidential If set to true, it will encrypt the data, otherwise data will just be integrity protected (checksummed). aOutToken A buffer containing the resulting data to be sent to the server. aOutTokenLength The length of the output token buffer. Exceptions thrown NS_ERROR_NOT_IMPLEMENTED If the underlying authentication mechanism does not support security layers. ...
nsIAuthPrompt2
thInformation authInfo ); Parameters aChannel The channel that requires authentication. level One of the level constants. authInfo Authentication information object. The implementation should fill in this object with the information entered by the user before returning. Return value false, authentication should be cancelled, usually because the user did not provide username/password. true, authentication can proceed using the values in the authInfo object. See also nsIAuthPrompt ...
nsIBadCertListener2
to obtain more information about the active connection. This object usually supports nsISSLSocketControl, nsITransportSecurityInfo, nsIIdentityInfo, nsISSLStatusProvider, nsIClientAuthUserDecision and possibly other interfaces. status The SSL status object that describes the problem(s). targetSite The Site name that was used to open the current connection. Return value The consumer shall return true if it wants to suppress the error message related to the bad cert (the connection will still get canceled). See also nsISocketTransport ...
nsIBidiKeyboard
NS_ERROR_NOT_IMPLEMENTED if the widget layer doesn't provide this information. Currently, this is only implemented on Windows. Methods isLangRTL() Determines if the current keyboard language is right-to-left. (supported on: win32, mac, gtk2) Note: Prior to Gecko 1.9 this method used a parameter 'out PRBool aIsRTL' to return the value. boolean isLangRTL(); Parameters None. Return value true if the current keyboard is right-to-left, false if it is not. Exceptions thrown NS_ERROR_FAILURE If no right-to-left keyboards are installed. setLangFromBidiLevel() Sets the keyboard language to left-to-right or right-to-left. (supported on: win32) void setLangFromBidiLevel( in PRUint8 aLevel ); Parameters aLevel If odd set the keyboard to right-to-left, if even set left-to-...
nsIBlocklistPrompt
); Parameters aAddons An array of addons and plugins that are blocked. 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
ject to be checked. appVersion Optional from Gecko 1.9.1 The version of the application we are checking in the blocklist. If this parameter is null, the version of the running application is used. toolkitVersion Optional from Gecko 1.9.1 The version of the toolkit we are checking in the blocklist. If this parameter is null, the version of the running toolkit is used. Return value true if the item is blocklisted, otherwise false. ...
nsICacheEntryInfo
entry. Read only. lastFetched PRUint32 Get the last time the cache entry was opened (in seconds since the Epoch). Read only. lastModified PRUint32 Get the last time the cache entry was modified (in seconds since the Epoch). Read only. Methods isStreamBased() This method finds out whether or not the cache entry is stream based. boolean isStreamBased(); Parameters None. Return value Returns true if the cache entry is stream based, otherwise returns false. See also nsICache nsICacheVisitor ...
nsICacheMetaDataVisitor
See also nsICache nsICacheEntryDescriptor ...
nsICategoryManager
persist across application sessions. You must pass false for this parameter. aReplace A flag indicating whether or not to overwrite the value of an existing category entry. Return value The previous value for the given category entry (if any). Exceptions thrown NS_ERROR_INVALID_ARG This error is returned if aReplace is false and the category entry already has a value, or if aPersist is true. deleteCategory() Delete a category and all entries. Note: If the category does not exist, then this method does nothing. void deleteCategory( in string aCategory ); Parameters aCategory The name of the category being deleted. deleteCategoryEntry() Delete an entry from the category. Note: If the category does not exist, then this method does nothing. void deleteCategoryEntry( ...
nsIChromeFrameMessageManager
DelayedLoad); void removeDelayedFrameScript(in AString aURL); Methods loadFrameScript() Loads a script into the remote frame. void loadFrameScript( in AString aURL, in boolean aAllowDelayedLoad ); Parameters aURL The URL of the script to load into the frame; this must be an absolute URL, but data: URLs are supported. aAllowDelayedLoad If true, the script will be loaded when the remote frame becomes available; otherwise, the script will only be loaded if the frame is already available. removeDelayedFrameScript() Removes a script from the list of scripts supporting delayed load. void removeDelayedFrameScript( in AString aURL ); Parameters aURL The URL of the script to remove from the list of scripts supporting delayed...
nsIChromeRegistry
hat is to be converted. Return value A new nsIURI object containing the loadable URI for the specified chrome URL. Violates the XPCOM interface guidelines wrappersEnabled() Returns whether XPCNativeWrappers are enabled for the specified URI. boolean wrappersEnabled( in nsIURI aURI ); Parameters aURI The URI for which to determine if XPCNativeWrappers are enabled. Return value true if XPCNativeWrappers are enabled for the specified URI; otherwise false. See also Chrome Registration ...
nsICommandLine
d. This is useful for Boolean flags; that is, flags that don't accept a parameter. You can determine if the flag was provided and remove it from the list of flags waiting to be processed in one operation. boolean handleFlag( in AString aFlag, in boolean aCaseSensitive ); Parameters aFlag The flag name to find and remove. aCaseSensitive Whether to do case-sensitive comparisons. Return value true if the flag was found, otherwise false. handleFlagWithParam() Finds a flag in the list of flags waiting to be processed and returns its value, after removing both the flag and its value from the list of flags waiting to be handled. This is useful for processing flags that accept a value. This is, essentially, a helper method that combines findFlag() and removeArguments() into one operation. AStri...
nsIComponentRegistrar
ID string. nsISimpleEnumerator enumerateContractIDs(); Parameters None. Return value An nsISimpleEnumerator over the list of registered classes. Elements of the enumerator implement nsISupportsCString. isCIDRegistered() This method is used to test for the existence of a specific ClassID. boolean isCIDRegistered( in nsCIDRef aClass ); Parameters aClass The ClassID to be queried. Return value true if a factory is registered for the ClassID, false otherwise. isContractIDRegistered() This method is used to test for the existence of a class implementing a specific ContractID. boolean isContractIDRegistered( in string aContractID ); Parameters aContractID The ContractID to be queried. Return value true if a factory is registered for the ContractID, false otherwise. registerFactory() Regis...
nsICompositionStringSynthesizer
et() are not called properly, e.g., sum of aLength of calls of appendClause() is not same as composition string set by setString(), this throws an exception. After a call of this, all stored composition string information is cleared. Therefore, you can reuse the instance for modifying composition string. boolean dispatchEvent(); Return value If dispatched event's default is prevented, returns true. However, this must always return false since all dispatching DOM events are not cancelable. setCaret() Sets caret position in the composition string set by setString(). This is optional. I.e., you may not call this before dispatchEvent(). void setCaret(in unsigned long aOffset, in unsigned long aLength); Parameters aOffset Caret offset in the composition string. This valu...
nsIContentPrefService
p for which to see if a preference exists; this may be specified as either a URI or as a string. In either case, the group consists of all sites matching the hostname portion of the specified URI. Specify null to check for the preference in the global preference space; those preferences apply to all sites. aName The name of the preference whose existence is to be determined. Return value true if the preference exists; otherwise false. Exceptions thrown NS_ERROR_ILLEGAL_VALUE If aGroup is not a string, nsIURI, or null. Or if aName is null or an empty string removeGroupedPrefs() Remove all grouped prefs. Useful for removing references to the sites the user has visited when the user clears their private data. void removeGroupedPrefs(); removeObserver() Removes an observer that...
nsIContentPrefService2
ccept a "context" parameter. This parameter relates to private browsing and determines the kind of storage that a method uses, either the usual permanent storage or temporary storage set() aside for private browsing sessions. Pass null to unconditionally use permanent storage. Pass an nsILoadContext to use storage appropriate to the context's usePrivateBrowsing attribute: if usePrivateBrowsing is true, temporary private-browsing storage is used, and otherwise permanent storage is used. A context can be obtained from the window or channel whose content pertains to the preferences being modified or retrieved. Callbacks The methods of callback objects are always called asynchronously. See nsIContentPrefCallback2 for more information about callbacks. Method overview void addObserver...
nsIContentViewer
Missing Description permitUnload() Determins whether or not the document wants to prevent unloading by firing beforeunload on the document, and if it does, prompts the user. The result is returned. boolean permitUnload( in boolean aCallerClosesWindow Optional ); Parameters aCallerClosesWindow Optional Indicates that the current caller will close() the window. If the method returns true, all subsequent calls will be ignored. Return value true if the document will allow unloading; otherwise false. requestWindowClose() boolean requestWindowClose(); Parameters None. Return value Missing Description Exceptions thrown Missing Exception Missing Description resetCloseWindow() Works in tandem with permitUnload(), if the caller decides not to close() the window it indicated i...
nsICookie
ed in Gecko 1.7 Inherits from: nsISupports Attributes Attribute Type Description expires PRUint64 Expiration time in seconds since midnight (00:00:00), January 1, 1970 UTC. expires = 0 represents a session cookie. expires = 1 represents an expiration time earlier than Jan 1, 1970. Read only. host AUTF8String The host (possibly fully qualified) of the cookie. Read only. isDomain boolean true if the cookie is a domain cookie, false otherwise. Read only. isSecure boolean true if the cookie was transmitted over ssl, false otherwise. Read only. name ACString The name of the cookie. Read only. path AUTF8String The path pertaining to the cookie. Read only. policy nsCookiePolicy Holds the sites compact policy value. Read only. status nsCookieStatus Holds the P3P status of cookie. ...
nsICookie2
ec 1.0) Inherits from: nsICookie Attributes Attribute Type Description creationTime PRInt64 The creation time of the cookie, in microseconds since midnight (00:00:00), January 1, 1970 UTC. Read only. expiry PRInt64 The actual expiry time of the cookie, in seconds since midnight (00:00:00), January 1, 1970 UTC. (where 0 does not represent a session cookie). Read only. isHttpOnly boolean true if the cookie is an http only cookie. Read only. isSession boolean true if the cookie is a session cookie. Note: That expiry time will also be honored for session cookies; thus, whichever is the more restrictive of the two will take effect. Read only. lastAccessed PRInt64 The last time the cookie was accessed, in microseconds since midnight (00:00:00) on January 1, 1970 UTC. "Accessed" mea...
nsICookieConsent
one with a cookie, based on a site's p3p policy and the user's preferences. the policy for the given URI and channel is also returned. nsCookieStatus getConsent( in nsIURI uri, in nsIHttpChannel httpChannel, in boolean isForeign, out nsCookiePolicy policy ); Parameters uri The URI to find the policy for. httpChannel The channel to extract the p3p headers from. isForeign True if the cookie originates from a third-party site. this is used to decide the cookie status based on user preferences. policy The policy for the given URI, or nsICookie::POLICY_UNKNOWN if one cannot be found. valid values are defined in nsICookie.idl. Return value Returns nsCookieStatus. Valid values are defined in nsICookie.idl. See also nsICookie ...
nsICookiePermission
ng added to the cookie database. aIsSession When canSetCookie is invoked, this is the current isSession attribute of the cookie. canSetCookie may leave this value unchanged to preserve this attribute of the cookie. aExpiry When canSetCookie is invoked, this is the current expiry time of the cookie. canSetCookie may leave this value unchanged to preserve this attribute of the cookie. Return value true if the cookie can be set. getOriginatingURI() Determines the originating URI for a load given a channel, for third-party cookie blocking. This is done by leveraging the loadgroup of the channel to find the root content docshell, and the URI associated with its principal. If the root content docshell or its principal's URI cannot be obtained, this method will throw. nsIURI getOriginatingURI( in ...
nsICryptoHMAC
e Hash Algorithm 256 SHA384 5 Secure Hash Algorithm 384 SHA512 6 Secure Hash Algorithm 512 Methods finish() Completes this HMAC object and produces the actual HMAC diegest data. Note: This method may be called any time after init() is called. This call resets the object to its pre-init state. ACString finish( in PRBool aASCII ); Parameters aASCII If true then the returned value is a base-64 encoded string. if false, then the returned value is binary data. Return value A hash of the data that was read by this object. This can be either binary data or base 64 encoded. Exceptions thrown NS_ERROR_NOT_INITIALIZED If init() has not been called. init() Initialize the hashing object. This method may be called multiple times with different algo...
nsIDNSRecord
The value of the next IP address. getNextAddrAsString() This function returns the value of the next IP address as a string and increments the internal address iterator. ACString getNextAddrAsString(); Parameters None. Return value The value of the next IP address as a string. hasMore() This method checks if there is another address in the record. boolean hasMore(); Parameters None. Return value true if there is another address in the record. rewind() This function resets the internal address iterator to the first address in the record. void rewind(); Parameters None. ...
nsIDOMElement
e. nsIDOMNodeList getElementsByTagNameNS( in DOMString namespaceURI, in DOMString localName ); Parameters namespaceURI Namespace URI localName Tag name Return value A nsIDOMNodeList containg all the descendants of this tag name. hasAttribute() Check if the element have this attribute set. boolean hasAttribute( in DOMString name ); Parameters name Attribute name Return value A boolean, true if the given attribute is set. hasAttributeNS() Check if the element for a given namespace have this attribute set. boolean hasAttributeNS( in DOMString namespaceURI, in DOMString localName ); Parameters namespaceURI Namespace URI localName Attribute name Return value A boolean, true if the given attribute is set. removeAttribute() Remove an attribute. void removeAttribute( in DOMString ...
nsIDOMEvent
void setTarget(in nsIDOMEventTarget aTarget); Native code only! void SetTrusted(in boolean aTrusted); Native code only! void stopImmediatePropagation(); void stopPropagation(); Attributes Attribute Type Description bubbles boolean Used to indicate whether or not an event is a bubbling event. If the event can bubble the value is true, else the value is false. Read only. cancelable boolean Used to indicate whether or not an event can have its default action prevented. If the default action can be prevented the value is true, else the value is false. Read only. currentTarget nsIDOMEventTarget Used to indicate the EventTarget whose EventListeners are currently being processed. This is particularly u...
nsIDOMEventGroup
ent Object Model. Inherits from: nsISupports Last changed in Gecko 1.7 Method overview boolean isSameEventGroup(in nsIDOMEventGroup other); Methods isSameEventGroup() Reports whether or not another event group is the same as this one. boolean isSameEventGroup( in nsIDOMEventGroup other ); Parameters other Instance of nsIDOMEventGroup object to compare against. Return value Returns true if the two objects are the same, otherwise false. See also Document Object Model (DOM) Level 3 Events Specification ...
nsIDOMGeoPositionOptions
OMGeoPositionOptions interface is used to specify options for geolocation operations. dom/interfaces/geolocation/nsIDOMGeoPositionOptions.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9.1 (Firefox 3.5 / Thunderbird 3.0 / SeaMonkey 2.0) Inherits from: nsISupports Attributes Attribute Type Description enableHighAccuracy boolean If true, high accuracy mode is used. timeout unsigned long Maximum time in milliseconds before giving up on an attempt to retrieve location information. ...
nsIDOMMouseScrollEvent
screenXArg The X coordinate at which the event occurred, in screen coordinates. screenYArg The Y coordinate at which the event occurred, in screen coordinates. clientXArg The X coordinate at which the event occurred, in client coordinates. clientYArg The Y coordinate at which the event occurred, in client coordinates. 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. buttonArg Indicates whic...
nsIDOMMozNetworkStatsManager
NetworkStatsGetOptions NetworkStatsGetOptions is a dictionary object used to filter a network statistics request made when calling getSamples(). It contains the following fields: appManifestURL A string used to filter network stats by app. serviceType A string used to filter network stats by system service. browsingTrafficOnly A boolean set to filter network stats by browsing traffic. If true, return only browsing traffic, which is generated from the mozbrowser iframe element within an app. If false or not set, the total traffic, which is generated from both the mozapp and mozbrowser iframe elements, is returned. For example, this object might be { appManifestURL : manifestURL }. ...
nsIDOMOfflineResourceList
rs uri The URI of the resource to add to the list. mozHasItem Returns a Boolean value indicating whether or not the specified URI represents a resource that's in the application cache's list. Note: This method has been deprecated. You should use the mozItems attribute instead. void mozHasItem( in DOMString uri ); Parameters uri The URI of the resource to check. Return value true if the resource is in the list, otherwise false. mozItem Returns the URI of the item at the specific offset into the list of cached resources. Note: This method is deprecated in Firefox 3.5; you should instead access the list directly using the items attribute. DOMString mozItem( in unsigned long index ); Parameters index The index of the cached item whose URI should be returned. ...
nsIDOMProgressEvent
ong loadedArg, in unsigned long long totalArg ); Parameters typeArg The type of event. Must be one of "abort", "error", "load", "loadstart", or "progress". canBubbleArg Specifies whether or not the created event will bubble. cancelableArg Specifies whether or not the created event can be canceled. lengthComputableArg If the size of the data to be transferred is known, this should be true. Otherwise, specify false. loadedArg The number of bytes already transferred. Must be a non-negative value. totalArg The total number of bytes to be transferred. If lengthComputable is false, this must be zero. See also Using XMLHttpRequest XMLHttpRequest nsIXMLHttpRequestEventTarget nsIXMLHttpRequest ...
nsIDOMStorageEventObsolete
main DOMString The domain of the storage area which changed, or "#session" if the event represents a change to session storage. Read only. Methods initStorageEvent() Initializes a storage event. void initStorageEvent( in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in DOMString domainArg ); Parameters typeArg The type argument. canBubbleArg true if the event is allowed to bubble, otherwise false. cancelableArg true if the event can be canceled, otherwise false. domainArg The domain to which the event belongs, or "#session" if the event is associated with session storage. See also Storage StorageEvent Structured client-side storage (HTML 5 specification) nsIDOMStorageItem ...
nsIDOMStorageItem
orage. This is for session storage. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Gecko 1.9.1 note Starting in Gecko 1.9.1 (Firefox 3.5), this is only used for session storage; previously, it was also used for global storage. Attributes Attribute Type Description secure boolean If true, the item was stored for an HTTPS page. Note: All items, regardless of whether they were stored for an HTTP page or an HTTPS page, are visible from HTTPS pages. However, HTTP pages can only see items stored from HTTP pages, and will not see items stored from HTTPS pages. As such, this attribute is irrelevant for storage that is bound to an origin. value DOMString The value associated with the i...
nsIDOMXPathResult
thEvaluator or document.evaluate Inherits from: nsISupports Last changed in Gecko 1.7 Method overview nsIDOMNode iterateNext(); nsIDOMNode snapshotItem(in unsigned long index); Attributes Attribute Type Description booleanValue boolean If resultType is BOOLEAN_TYPE, the boolean value. Read only. invalidIteratorState boolean true if the iterator state has become invalid. For example, modifying a node invalidates the iterator. Read only. numberValue double If resultType is NUMBER_TYPE, the numeric value of the XPath value. Read only. resultType unsigned short The type of result; can be any of the Type constants except ANY_TYPE. Read only. singleNodeValue nsIDOMNode If resultType...
nsIDataSignatureVerifier
...
nsIDictionary
etval, array, size_is(count)] out string keys); nsISupports getValue(in string key); void setValue(in string key, in nsISupports value); nsISupports deleteValue(in string key); void clear(); Methods hasKey() Check if a given key is present in the dictionary. boolean hasKey( in string key ); Parameters key Key to check for. Return value true if present, false if absent. getKeys() Retrieve all keys in the dictionary. void getKeys( out PRUint32 count, [retval, array, size_is(count)] out string keys ); Return value Array of all keys, unsorted. getValue() Find the value indicated by the key. nsISupports getValue( in string key ); Parameters key The lookup key indicating the value. Return value The value...
getFile
n and returns the appropriate nsIFile. nsIFile getFile( in string aName, out boolean aPersistent ); Parameters aName [in] The symbolic name for a file or directory location. See Symbolic names below for a list of accepted values. XPCOM File System Aliases aPersistent [out] This output parameter indicates to the caller whether or not the returned location is persistent. If true, this lets the Directory Service cache results to improve the performance of directory lookups. If false, then the Directory Service will not cache the results of this method. Symbolic names The list of symbolic names is subject to change, so be sure to take a look at the xpcom/io/nsDirectoryServiceDefs.h file for the version of Gecko you're working with for the latest list. Available on all pla...
nsIDirectoryServiceProvider
nged in Gecko 1.7 nsIDirectoryServiceProvider. Method overview nsIFile getFile(in string prop, out PRBool persistent); Methods getFile() The Directory Service calls this method when it gets the first request for a prop or on every request if the prop is not persistent. nsIFile getFile( in string prop, out PRBool persistent ); Parameters prop The symbolic name of the file. persistent true if the returned file will be cached by Directory Service. Subsequent requests for this prop will bypass the provider and use the cache. false if the provider will be asked for this prop each time it is requested. Return value The nsIFile represented by the property. Example This code creates a global, read-only string called currDir with the value of the current working directory. __defineGette...
nsIDownloadManagerUI
nterface. 1.0 66 Introduced Gecko 1.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. Read only. Constants Constant Value Description REASON_USER_INTERACTED 0 When opening the Download Manager user interface, this value indicates that it's being done at the user's request. REASON_NEW_DOWNLOAD 1 When opening the Download Manager user interface, this value indicates that the ...
nsIDragService
script] void dragMoved( in long aX, in long aY ); Parameters aX The X coordinate to which to move the popup being dragged. aY The Y coordinate to which to move the popup being dragged. endDragSession() Tells the Drag Service to end a drag session. This is called when an external drag occurs. void endDragSession( in PRBool aDoneDrag ); Parameters aDoneDrag If aDoneDrag is true, the drag has finished, otherwise the drag has just left the window. fireDragEventAtSource() Obsolete since Gecko 43 (Firefox 43 / Thunderbird 43 / SeaMonkey 2.40)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it. Fire a drag event at the source of the drag. This was changed in Gecko 43,...
nsIDragSession
Supported() Checks to see if any of the native data on the clipboard matches a given data flavor. If numDropItems is greater than one, there is no indication as to which of the items matches the data flavor. boolean isDataFlavorSupported( in string aDataFlavor ); Parameters aDataFlavor A string representing the MIME type of the data to be matched, such as "text/unicode". Return value true if the specified flavor matches any of the native data on the clipboard, otherwise false. ...
nsIDroppedLinkHandler
es if a link being dragged can be dropped. boolean canDropLink( in nsIDOMDragEvent aEvent, in PRBool aAllowSameDocument ); Parameters aEvent A dragenter or dragover event. aAllowSameDocument If false, drops are only allowed if the document of the source of the drag is different from the destination. This check includes any parent, sibling and child frames in the same content tree. If true, the source is not checked. Return value true if the link being dragged can be dropped. Exceptions thrown Missing Exception Missing Description dropLink() Given a drop event, determines the link being dragged. If a uri is returned the caller can, for instance, load it. If null is returned, there is no valid link to be dropped. AString dropLink( in nsIDOMDragEvent aEvent, out AStri...
nsIEditorDocShell
Read only. editor nsIEditor Gets or sets the editor for the content document. hasEditingSession boolean This docShell has an editing session. Read only. Methods makeEditable() Make this docShell editable, setting a flag that causes an editor to get created, either immediately, or after a url has been loaded. void makeEditable( in boolean inWaitForUriLoad ); Parameters inWaitForUriLoad true to wait for a URI before creating the editor. ...
nsIEnvironment
es not exist when getenv() returns NULL. For non-Unix/Linux platforms we have to fall back to a "portable" definition (which is incorrect for Unix/Linux!!!!) which simply checks whether the string returned by Get() is empty or not. boolean exists( in AString aName ); Parameters aName The variable name to probe. Return value If the variable has been set, the value returned is PR_TRUE. If the variable was not defined in the environment PR_FALSE will be returned. Examples Windows This example gets the path to the Porgram Files directory on Windows. Credit to morat from mozillazine. var nsIEnvironment = Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment); var pathToProgramFiles = nsIEnvironment.get("ProgramFiles"); //for me ...
nsIEventTarget
NS_ERROR_UNEXPECTED Indicates that the thread is shutting down and has finished processing events, so this event would never run and has not been dispatched. NS_ERROR_INVALID_ARG Indicates that event is null. isOnCurrentThread() Check to see if this event target is associated with the current thread. boolean isOnCurrentThread(); Parameters None. Return value Returns true if events dispatched to this event target will run on the current thread (that is, the thread calling this method). If events dispatched to this target will be processed on another thread, returns false. Native code only!postEvent Obsolete since Gecko 1.9 (Firefox 3)This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any tim...
nsIFactory
orted. lockFactory() This method provides the client a way to keep the component in memory until it is finished with it. Gecko 1.7 note As of Gecko 1.7, this method is unused. Most implementations do nothing interesting with this method. It exists primarily for binary compatibility with Microsoft COM's IClassFactory interface. void lockFactory( in PRBool lock ); Parameters lock true to lock the factory, and false to unlock the factory. Remarks On WIN32 systems, nsIFactory is ABI-compatible with Microsoft COM's IClassFactory interface. This interface was frozen for Gecko 0.9.5. See bug 99144 for details. From Gecko 2.0 interfaces are no longer frozen. See also nsISupports ...
nsIFaviconService
detect most invalid icons and it will resolve to the default icon, although without caching. For invalid chrome URIs, you'll get a broken image. isFailedFavicon() This method checks to see if this favicon is in the failed favicon cache. boolean isFailedFavicon( in nsIURI aFaviconURI ); Parameters aFaviconURI The URI of an icon in the favicon service. Can be null. Return value Returns true if the favicon is in the failed cache, meaning you probably shouldn't try to load it. A false return value means that it's worth trying to load it. This allows you to avoid trying to load "foo.com/favicon.ico" for every page on a site that doesn't have a favicon. removeFailedFavicon() This method removes the given favicon from the failed favicon cache. If the icon is not in the cache, this functi...
nsIFilePicker
This attribute has no effect if private browsing mode is in effect. defaultExtension AString The extension for the type of files you want to work with. On some platforms, this is automatically appended to filenam...
nsIFrameMessageListener
erview void receiveMessage(); Methods receiveMessage() Note: This method is for JavaScript only. Called to deliver a message to the frame handling process; called with one parameter, which has the following properties: name The name of the message. sync A boolean value indicating whether or not the message should be handled synchronously. If true, the response should be returned in the specified JSON object. json The JSON object in which to return the response if the message is being handled synchronously. objects Unimplemented An array of cpow, or null if sync is false. When the listener is called, the this value is the target of the message. void receiveMessage(); Parameters None. See also Content proces...
nsIGeolocationProvider
ocation provider. Method overview boolean isReady(); Obsolete since Gecko 1.9.2 void shutdown(); void startup(); void watch(in nsIGeolocationUpdate callback); Methods isReady() Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Reports whether or not the device is ready and has a position. boolean isReady(); Parameters None. Return value true if the device is ready and has a position available to return; otherwise false. shutdown() Shuts down the location device. void shutdown(); Parameters None. startup() Start up the provider. This is called before any other method and may be called multiple times. void startup(); Parameters None. watch() Attaches a callback listener to be notified when a location change is observed. void watch( ...
nsIGlobalHistory
...
nsIGlobalHistory2
nd view-source:. Embedders should consider filtering out these schemes and others, for example mailbox:, for the main nsIURI and the referrer. void addURI( in nsIURI aURI, in boolean aRedirect, in boolean aToplevel, in nsIURI aReferrer ); Parameters aURI The nsIURI of the page being added. aRedirect Whether the URI was redirected to another location; this is true for the original URI which is redirected. aToplevel Whether the URI is loaded in a top-level window. aReferrer The URI of the referring page. isVisited() Checks to see whether the given URI is in history. boolean isVisited( in nsIURI aURI ); Parameters aURI The nsIURI of the page. Return value true if a URI has been visited. setPageTitle() Set the ...
nsIGlobalHistory3
ddDocumentRedirect() Notifies the history system that the page loading via aOldChannel redirected to aNewChannel. Implementations should generally add the URI for aOldChannel to history for link coloring, but are advised not to expose it in the history user interface. This function is preferred if nsIGlobalHistory3 is available. Otherwise, nsIGlobalHistory2.addURI() should be called with redirect=true. This function is preferred to nsIGlobalHistory2.addURI() because it provides more information (including the redirect destination, channels involved, and redirect flags) to the history implementation. For implementors of nsIGlobalHistory3: The history implementation is responsible for sending NS_LINK_VISITED_EVENT_TOPIC to observers for redirect pages. This notification must be sent for history ...
nsIHttpActivityObserver
If this is false, the observeActivity() method should not be called. Read only. Note: This attribute is present only for compatibility and should not be used. Constants Activity type constants Constant Value Description ACTIVITY_TYPE_SOCKET_TRANSPORT 0x0001 Socket transport activity has occurred. ACTIVITY_T...
nsIHttpHeaderVisitor
rface is used to walk through the response headers and evaluate the MIME type. ...
nsIHttpServer
this.registerPrefixHandler("/", callback); } let host = "localhost"; if (typeof port === "string" && port.indexOf(':') != -1){ [host, port] = port.split(':'); port = parseInt(port); server.identity.add('http', host, port); } server.wrappedJSObject._start(port, host); return true; }, registerFile: function(path, filePath) { var file = Components.classes['@mozilla.org/file/local;1'] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath(filePath); return server.registerFile(path, file); }, registerDirectory : function(path, directoryPath) { var file...
nsIInstallLocation
Determines whether or not an item's resources are managed by the Extension System or by some other user or process. For example, items linked to by text links are managed by the user, and items linked to from Registry Install Locations are usually managed by other applications or installers. boolean itemIsManagedIndependently( in AString id ); Parameters id The GUID of the item. Return value true if the item's resources are managed independently of the Extension System, false otherwise. removeFile() Removes a file from the stage. This cleans up the stage if there is nothing else left after the remove operation. void removeFile( in nsIFile file ); Parameters file The file to remove. stageFile() Stages the specified file by copying it to some location from where it can be retrieved lat...
nsIJSID
lates the XPCOM interface guidelines void initialize(in string idString); string toString(); Attributes Attribute Type Description id nsIDPtr Read only. Native code only! Obsolete since Gecko 1.9 The internal nsID. name string Read only. The name of the JSID, if it was set. number string Read only. The string representation of the internal nsID. valid boolean Read only. Returns true if the JSID has been initialised. Methods equals() This method determines if this nsIJSID has the same nsID as another nsIJSID. boolean equals( in nsIJSID other ); Parameters other The other nsIJSID to compare to. Return value true if the nsIJSID's are valid and have the same nsID, otherwise false. Violates the XPCOM interface guidelines getID() const nsID* getID(); Parameters Non...
nsIJSON
ON format, writing it to a stream. void encodeToStream( in nsIOutputStream stream, in string charset, in boolean writeBOM in JSObject value ); Parameters stream The nsIOutputStream to which to write the JSON string. charset The string encoding to use. Only the five Unicode encodings "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE" and "UTF-32BE" are supported. writeBOM Specify true if you wish to write a byte-order mark (BOM) into the stream, otherwise specify false. value The JavaScript object to encode. legacyDecode() Decodes a JSON string. This method accepts slightly more than the exact JSON syntax; details of extra accepted syntax are deliberately not described. This method is intended for use only by code processing legacy data. When the original instance requ...
nsIJumpListItem
JUMPLIST_ITEM_LINK 2 Web link item. ...
nsILivemarkService
isn't known or identifies a folder that isn't a livemark container. NS_ERROR_MALFORMED_URI If the site URI annotation has somehow been corrupted (and can't be turned into an nsIURI) isLivemark() This method determines whether the folder with the given folder ID identifies a livemark container. boolean isLivemark( in long long folder ); Parameters folder A folder ID. Return value true if the given folder is a livemark folder, otherwise it returns false. Exceptions thrown NS_ERROR_INVALID_ARG If the folder ID isn't known. reloadAllLivemarks() This method reloads all livemark subscriptions, whether or not they have expired. void reloadAllLivemarks(); Parameters None. reloadLivemarkFolder() This method reloads the livemark with this folder ID, whether or not it's ex...
nsILoginManagerCrypto
2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview AString decrypt(in AString cipherText); AString encrypt(in AString plainText); Attributes Attribute Type Description isLoggedIn boolean Current login state of the token used for encryption. If the user is not logged in, performing a crypto operation will result in a master password prompt. Read only. uiBusy boolean true when a master password prompt is being displayed. Read only. Methods decrypt() Decrypts the specified string, returning the plain text value. Can throw if the user cancels entry of their master password, or if the cipherText value can not be successfully decrypted (for example, if it was encrypted with some other key). AString decrypt( in AString cipherText ); Parameters cipherText The str...
nsIMarkupDocumentViewer
ewer.idlScriptable Describes the properties of a content viewer for an HTML or XML markup document. Inherits from: nsISupports Last changed in Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) Method overview void scrollToNode(in nsIDOMNode node); void sizeToContent(); Attributes Attribute Type Description allowPlugins boolean If true, plugins are allowed within the doc shell. default = true. Obsolete since Gecko 1.8 authorStyleDisabled boolean Disable entire author style level (including HTML presentation hints) bidiCharacterSet octet Whether to force the user's character set 1 - use the document character set 2 - use the character set chosen by the user. Obsolete since Gecko 6.0 bidiCo...
nsIMemoryReporter
o allow a hierarchy of memory to be displayed in about:memory. As of Gecko 6.0, the path should start with "explicit/" if the memory report accounts for all memory reported under sub-paths. Read only. process ACString The name of the process containing this reporter. Each reporter starts with an empty string for this value, indicating that it applies to the current process; this is true even for reporters in a child process. When a reporter from a child process is copied into the main process, the copy's process field is set appropriately. Read only. units PRInt32 The units used by the amount attribute; this will be one of the Unit type constants. Read only. Constants Memory reporter kind constants These allocation kind constants describe the types of memo...
nsIMessageListener
an element owning the message manager, or the message manager itself if no element owns it. If the message was sent from a frame script using a nsIContentFrameMessageManager, then this property is the XUL <browser> element for the frame from which the message was sent. name The message name. This is the first argument passed into the message-sending function. sync True if the message was sent using sendSyncMessage, false otherwise. data A structured clone of the message payload: the second argument passed into the message-sending function. json Same as data. Deprecated. objects An object whose properties are any cross process object wrappers exposed by the sender as the third argument to the message-sending function. ...
nsIMessageListenerManager
ageListener(in AString messageName, in nsIMessageListener listener, [optional] in boolean listenWhenClosed); Parameters messageName A string indicating the name of the message to listen for. listener An nsIMessageListener to invoke when a message is received. See nsIMessageListener for details of the message syntax. 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. This parameter only has an effect for frame message managers in the main process. An alternative method to listen for death of frame script is to use a message-manager-disconnect observer; see Observer Notifications :: Message Manag...
nsIMicrosummary
maryObserver observer ); Parameters observer The microsummary observer to add. equals() Microsummary equivalence test. Microsummaries equal if they summarize the same page with the same microsummary-generator (see also nsIMicrosummaryGenerator.equals()). boolean equals( in nsIMicrosummary aOther ); Parameters aOther The microsummary to compare against. Return value Returns true if the microsummaries are equal. 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. void removeObserver( in nsIMicrosummaryObserver observer ); Parameters observer The microsummary observer to remove. update() Update the microsummary, first loading its generator and p...
nsIMimeConverter
pertyName, in unsigned long propertyVal); Parameters propertyName The name of the property to set. propertyVal The value of the property. EncoderDestroy() Marks this header as read. Thunderbird provides a utility function which performs this for the currently selected message: MarkCurrentMessageAsRead(). void markRead(in boolean read); Parameters read If true, mark as read. If false mark as undread. EncoderWrite() void markFlagged(in boolean flagged); Parameters flagged If true, mark as flagged. If false remove flag. ...
nsIModule
aCompMgr, in nsIFile aLocation, in string aLoaderStr); Methods canUnload() This method may be queried to determine whether or not the component module can be unloaded by XPCOM. boolean canUnload( in nsIComponentManager aCompMgr ); Parameters aCompMgr The global component manager. Return value Indicates to the caller whether or not the component module can be unloaded. Returning true is not a guarantee that the module will be unloaded. It constitues only willingness of the module to be unloaded. It is very important to ensure that no outstanding references to the module's code/data exist before returning true. Returning false guaratees that the module will not be unloaded. If the component module is native (that is, as part of a DLL), then this method may be called to determi...
Building an Account Manager Extension
t("resource://gre/modules/XPCOMUtils.jsm"); //class constructor function DevmoAccountManagerExtension() {}; // class definition DevmoAccountManagerExtension.prototype = { name : "devmo-account", chromePackageName : "example@mozilla.org", showPanel: function(server) { //this panel is only shown for imap accounts... if (server.type == \"imap\") 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. Therefore we add the following code to the previous. The JavaScript file has to be saved either in the exten...
nsIMsgAccountManagerExtension
ackage, where the files for the new panel are located. This is usually GUID of the ID of the addons which adds the new Panel. This attribute is readonly! Methods showPanel() Before displaying a panel in the Account Manager this method is triggered. boolean showPanel( in nsIMsgIncomingServer server ); Parameters server The account for which the panel should be displayed. 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. See also nsIMsgAccountManager Building an Account Manager Extension ...
nsIMsgCompFields
from AString hasRecipients PRBool readonly New in Thunderbird 23 Indicates whether something is filled in in the to, cc, or bcc attribute. (bug 68784) messageId char * needToCheckCharset PRBool Indicates whether we need to check if the current DocumentCharset can represent all the characters in the message body. It should be initialized to true and set to false when 'Send Anyway' is selected by a user. (bug 249530) newsgroups AString newshost char * newspostUrl char * organization AString otherRandomHeaders AString No longer exists - see https://groups.google.com/forum/#!topic/mozilla.dev.apps.thunderbird/s4oFmM8_B28 priority char * ...
nsIMsgDBHdr
ng propertyName, in unsigned long propertyVal); Parameters propertyName The name of the property to set. propertyVal The value of the property. markRead() Marks this header as read. Thunderbird provides a utility function which performs this for the currently selected message: MarkCurrentMessageAsRead(). void markRead(in boolean read); Parameters read If true, mark as read. If false mark as undread. markFlagged() void markFlagged(in boolean flagged); Parameters flagged If true, mark as flagged. If false remove flag. markHasAttachments() void markHasAttachments(in boolean hasAttachments); Parameters hasAttachments If true, mark as having attachments. If false mark as not having attachments. setPriorityString() void setPrioritySt...
nsIMsgFilterCustomAction
is filter action. * recommended form: ExtensionName@example.com#ActionName */ readonly attribute ACString id; /* action name to display in action list. This should be localized. */ readonly attribute AString name; /** * Is this custom action valid for a particular filter type? * * @param type the filter type * @param scope the search scope * * @return true if valid */ boolean isValidForType(in nsMsgFilterTypeType type, in nsMsgSearchScopeValue scope); /** * After the user inputs a particular action value for the action, determine * if that value is valid. * * @param actionValue The value entered. * @param actionFolder Folder in the filter list * @param filterType Filter Type (Manual, OfflineMail,...
nsIMsgFolder
lder properties and methods. parentMsgFolder nsIMsgFolder Readonly: Handy accessor when we want a msg folder. dBTransferInfo nsIDBFolderInfo subFolders nsISimpleEnumerator Readonly: Returns an enumerator containing a list of nsIMsgFolder items that are subfolders of the instance this is called on. hasSubFolders boolean Readonly: Returns true if this folder has sub folders. messages nsISimpleEnumerator Readonly: Returns a list of Components.interfaces.nsIMsgDBHdr. numSubFolders unsigned long Readonly: Returns the number of sub folders that this folder has. inVFEditSearchScope boolean readonly customIdentity nsIMsgIdentity Readonly: This allows a folder to have a special iden...
nsIMsgSearchSession
Methods addSearchTerm() void addSearchTerm(in nsMsgSearchAttribValue attrib, in nsMsgSearchOpValue op, in nsIMsgSearchValue value, in boolean BooleanAND, in string arbitraryHeader); Parameters attrib Attribute for this term. op Operator e.g. opContains value Value e.g. "Dogbert" BooleanAND Set to true if associated boolean operator is AND. arbitraryHeader User defined arbitrary header. Ignored unless attrib = attribOtherHeader. createTerm() nsIMsgSearchTerm createTerm(); appendTerm() void appendTerm(in nsIMsgSearchTerm term); Parameters term registerListener() Adds a listener to the search session. void registerListener(in nsIMsgSearchNotify listener); Parameters li...
nsIMsgSearchTerm
y); matchAge boolean matchAge(in PRTime days); matchSize boolean matchSize(in unsigned long size); matchLabel boolean matchLabel(in nsMsgLabelValue aLabelValue); matchJunkStatus boolean matchJunkStatus(in string aJunkScore); matchJunkPercent /* * Test search term match for junkpercent * * @param aJunkPercent junkpercent for message (0-100, 100 is junk) * @return true if matches */ boolean matchJunkPercent(in unsigned long aJunkPercent); matchJunkScoreOrigin /* * Test search term match for junkscoreorigin * @param aJunkScoreOrigin Who set junk score? Possible values: * plugin filter imapflag user whitelist * @return true if matches */ boolean matchJunkScoreOrigin(in string aJunkScoreOrigin); matchBody /*...
nsIMsgThread
removeChildAt(in long index); Parameters index The index to remove the message from removeChildHdr() void removeChildHdr(in nsIMsgDBHdr child, in nsIDBChangeAnnouncer announcer); Parameters child The message to remove announcer An nsIDBChangeAnnouncer to receive notification when the change is made. markChildRead() void markChildRead(in boolean bRead); Parameters bRead true if the messages should be marked read. false if unread. getFirstUnreadChild() nsIMsgDBHdr getFirstUnreadChild(); enumerateMessages() nsISimpleEnumerator enumerateMessages(in nsMsgKey parent); Parameters parent A key representing the message to start enumerating with. ...
nsINavBookmarkObserver
The property which changed. If this string is empty, all properties have been deleted. In this situation, you should not attempt to get any properties, since this will result in the automatic regeneration of properties that will then be leaked into the database, causing trouble later. aIsAnnotationProperty Indicates whether or not aProperty is the name of an item annotation. If this is true, aNewValue is always an empty string. aNewValue The items new value, if required by the property specified by aProperty. aLastModified The value to set the items last modified time to, or 0 if the value should remain unchanged. aItemType The type of the item that has been changed. This should be one of the nsINavBookmarksService.Type constants. aParentId The id ...
nsINavHistoryResultObserver
r events until the batch is completed, so that it won't handle the large number of updates that are about to be notified. This is especially useful when updating user interfaces, to avoid flicker or continuous selection changes, which may result in performance degradation (for example, if updating a view for each update). void batching( in boolean aToggleMode ); Parameters aToggleMode Specify true to start batch mode or false to finish the batch. containerClosed() Obsolete since Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8) Called when a container node's state changes from opened to closed. Note: This method was deprecated in Gecko 2.0 and removed in Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8). Implement the containerStateChanged()...
nsINavHistoryResultTreeViewer
em in the tree. This prevents you from seeing multiple entries for things when you have selected to get visits. When you sort by date, the multiple entries will then appear because they will be separated (unless you clicked reload a bunch of times in a row). If you know you'll only ever want one entry per site, you should ask for URIs back instead of visits so it will be more efficient. Default = true. Changing this value is somewhat heavyweight since it will force a tree refresh. Obsolete since Gecko 1.9 flatItemCount PRUint32 This tells you how many items are in the flattened list of results, that is how many rows are in this tree right now. The tree adaptor will also QI to nsITreeView, and this will be the same as nsITreeView.rowCount. This is only valid when a tree is attached, the resul...
nsINavHistoryResultViewObserver
instead of on the pane as a whole, always return false when the orientation isn't DROP_ON. Warning: Do not change the content of the observer list. boolean canDrop( in long index, in long orientation ); Parameters index The item over which the drag is currently located. orientation Whether the drag target is before, after, or on the indicated row. Return value Return true if the drop is permitted or false if it isn't. onDrop() Called when the user drops something onto the view being observed. void onDrop( in long row, in long orientation ); Parameters row The row at which the drop occurred. orientation DROP_BEFORE, DROP_ON, or DROP_AFTER, indicating whether the drop destination is before, on, or after the target row. onToggleOpenState() ...
nsIObserverService
regarding the specified topic. See nsIObserver for a JavaScript example. void addObserver( in nsIObserver anObserver, in string aTopic, in boolean ownsWeak ); Parameters anObserver The nsIObserver object which will receive notifications. aTopic The notification topic or subject. ownsWeak If set to false, the nsIObserverService will hold a strong reference to anObserver. If set to true and anObserver supports the nsISupportsWeakReference interface, a weak reference will be held. Otherwise an error will be returned. (In most cases, you should use false.) enumerateObservers() Called to enumerate all observers registered for a particular topic. nsISimpleEnumerator enumerateObservers( in string aTopic ); Parameters aTopic The notification topic or subject. Return valu...
nsIParserUtils
Return value The plain text conversion of the HTML specified in src. parseFragment() Parses markup into a sanitized document fragment. nsIDOMDocumentFragment parseFragment( in AString fragment, in unsigned long flags, in boolean isXML, in nsIURI baseURI, in nsIDOMElement element ); Parameters fragment The input markup. flags Sanitization option flags defined above. isXML true if |fragment| is XML and false if HTML. baseURI The base URL for this fragment. element The context node for the fragment parsing algorithm. Return value An nsIDOMDocumentFragment object for the resulting sanitized document fragment. sanitize() Parses a string into an HTML document, sanitizes the document, and returns the result serialized to a string. The sanitizer is designed to prote...
nsIPipe
ts nsISearchableInputStream. Read only. outputStream nsIAsyncOutputStream The pipe's output end. Read only. Methods init() initialize this pipe. void init( in boolean nonBlockingInput, in boolean nonBlockingOutput, in unsigned long segmentSize, in unsigned long segmentCount, in nsIMemory segmentAllocator ); Parameters nonBlockingInput true specifies non-blocking input stream behavior. nonBlockingOutput true specifies non-blocking output stream behavior. segmentSize Specifies the segment size in bytes (pass 0 to use default value) segmentCount Specifies the max number of segments (pass 0 to use default value). Passing PR_UINT32_MAX here causes the pipe to have "infinite" space. This mode can...
nsIPrefBranch2
omain, in nsIObserver aObserver, in boolean aHoldWeak ); Parameters aDomain The preference on which to listen for changes. This can be the name of an entire branch to observe. For example holding the "root" prefbranch and calling addObserver("foo.bar.", ...) will observe changes to foo.bar.baz and foo.bar.bzip. aObserver The object to be notified if the preference changes. aHoldWeak true holds a weak reference to aObserver. The object must implement the nsISupportsWeakReference interface or this will fail. false holds a strong reference to aObserver. removeObserver() Remove a preference change observer. Note: You must call removeObserver method on the same nsIPrefBranch2 instance on which you called addObserver() method in order to remove aObserver; otherwise, the observer wi...
nsIPrivateBrowsingService
llers should use the contract ID @mozilla.org/privatebrowsing-wrapper;1 instead. Method overview void removeDataFromDomain(in AUTF8String aDomain); Attributes Attribute Type Description autoStarted boolean Indicates whether or not private browsing was started automatically at application launch time. This is only ever true if privateBrowsingEnabled is also true. Read only. lastChangedByCommandLine boolean Indicates whether or not the last private browsing mode transition was performed on the command line (using either the -private or -private-toggle switches) rather than the user interface. Read only. privateBrowsingEnabled boolean Indicates whether or not pr...
nsIProcess2
array must have count entries. count The number of arguments passed in the args array. observer Optional An observer that will be notified when the process exits. The observer will receive this nsIProcess2 instance as the subject and "process-finished" or "process-failed" as the topic. The observer will be notified on the main thread. holdWeak Optional If true, a weak reference is used to hold the observer. See also nsIProcess nsIObserver ...
nsIProperties
macro NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY, which can be used to free aKeys when it is no longer needed. void getKeys( out PRUint32 count, [array, size_is(count), retval] out string keys ); Parameters count The length of the result array. keys The resulting array of keys. has() Tests if a property exists. boolean has( in string prop ); Parameters prop The property name. Return value true if the property exists, false if the property does not exist. set() Sets the XPCOM object associated with a particular name. void set( in string prop, in nsISupports value ); Parameters prop The property name. value The XPCOM object value to associate with prop. undefine() Undefines a property. void undefine( in string prop ); Parameters prop The property name. Remarks This interface ...
nsIPropertyBag2
...
nsIProtocolHandler
rt 25 (Simple Mail Transfer Protocol) is banned. When a URI containing this port number is encountered, this method is called to ask if the protocol handler wants to override the ban. boolean allowPort( in long port, in string scheme ); Parameters port The port for which an override is being requested. scheme The scheme for which an override is being requested. Return value Return true if the override is approved; otherwise, return false. newChannel() Constructs a new channel from the given URI for this protocol handler. nsIChannel newChannel( in nsIURI aURI ); Parameters aURI The URI for which to construct a channel. Return value Return the newly constructed channel. newURI() Makes a URI object that is suitable for loading by this protocol, where the URI string...
nsIPushService
bscription nsIPrincipal, as passed to nsIPushService.subscribe(). callback The callback to call when the nsIPushSubscription is dropped. Example pushService.unsubscribe( "chrome://my-module/push", scriptSecurityManager.getSystemPrincipal(), (code, ok) => { if (!Components.isSuccessCode(code)) { Cu.reportError("Error unsubscribing: " + code); return; } // `ok === true` if the subscription was removed, or `false` if the // `(scope, principal)` pair didn't have a subscription. } ); Receiving Push Messages Subscriptions created from privileged code use XPCOM observer notifications instead of service worker events. You can use the global nsIObserverService to listen for these notifications. Messages sent to system subscriptions are broadcasted to all pu...
nsIPushSubscription
key: String.fromCharCode.apply(null, btoa(subscription.getKey("p256dh"))), secret: String.fromCharCode.apply(null, btoa(subscription.getKey("auth"))), ...
nsISHEntry
ers x y Native code only!getViewerBounds Saved position and dimensions of the content viewer; we must adjust the root view's widget accordingly if this has changed when the presentation is restored. void getViewerBounds( in nsIntRect bounds ); Parameters bounds Violates the XPCOM interface guidelines hasDetachedEditor() boolean hasDetachedEditor(); Parameters None. Return value true if this shistory entry is storing a detached editor. hasDynamicallyAddedChild() boolean hasDynamicallyAddedChild(); Parameters None. Return value true if any of the child entries returns true when isDynamicallyAdded() is called on it. isDynamicallyAdded() Returns true if the related docshell was added because of dynamic addition of an iframe/frame. boolean isDynamicallyAdded(); Parameters None.
nsISSLErrorListener
See also nsISocketTransport ...
nsIScriptableInputStream
f the stream is at EOF. Exceptions thrown NS_ERROR_NOT_INITIALIZED If init() was not called. NS_BASE_STREAM_CLOSED If called after the stream has been closed. NS_BASE_STREAM_WOULD_BLOCK Indicates that reading from the input stream would block the calling thread for an indeterminate amount of time. This exception may only be thrown if nsIInputStream.isNonBlocking() returns true. readBytes() Read data from the stream, including null bytes. ACString readBytes( in unsigned long aCount ); Parameters aCount The maximum number of bytes to read. Return value The data from the stream, which will be an empty string if EOF has been reached. Exceptions thrown NS_ERROR_FAILURE If there are not enough bytes available to read aCount amount of data. NS_BASE_...
nsIScriptableUnescapeHTML
valent to calling nsIParserUtils::parseFragment(fragment, 0, isXML, baseURI, element). You should call nsIParserUtils::parseFragment() instead of calling this method. nsIDOMDocumentFragment parseFragment( in AString fragment, in PRBool isXML, in nsIURI baseURI, in nsIDOMElement element ); Parameters fragment A string of HTML or XML source to parse as a fragment. isXML Set this to true if the fragment is an XML string; otherwise set it to false. baseURI Pointer to the base URI against which to resolve any URIs included in the fragment. This parameter is ignored if isXML is false. element The nsIDOMElement to be used as the context node for the purposes of the fragment parsing algorithm. Return value An nsIDOMDocumentFragment of the element with the new text appended. Ex...
nsISearchEngine
e.g. where the search is triggered in the UI. Possible values depend on the application's installed search engines. Return value An nsISearchSubmission supportsResponseType() Determines whether the engine can return responses in the given MIME type. boolean supportsResponseType( in AString responseType ); Parameters responseType The MIME type to check for. Return value Returns true if the engine spec has a URL with the given responseType, false otherwise. See also nsISearchSubmission nsIBrowserSearchService ...
nsISelection2
the input range. scrollIntoView() Scrolls a region of the selection, so that it is visible in the scrolled view. void scrollIntoView( in short aRegion, in boolean aIsSynchronous, in short aVPercent, in short aHPercent ); Parameters aRegion The region inside the selection to scroll into view (see selection region constants defined in nsISelectionController). aIsSynchronous When true, scrolls the selection into view before returning. If false, posts a request which is processed at some point after the method returns. aVPercent How to align the frame vertically. A value of 0 means the frame's upper edge is aligned with the top edge of the visible area. A value of 100 means the frame's bottom edge is aligned with the bottom edge of the visible area. For values in between, the...
nsISelectionPrivate
tenerToRemove scrollIntoView() Scrolls a region of the selection, so that it is visible in the scrolled view. void scrollIntoView( in short aRegion, in boolean aIsSynchronous, in short aVPercent, in short aHPercent ); Parameters aRegion The region inside the selection to scroll into view (see selection region constants defined in nsISelectionController). aIsSynchronous When true, scrolls the selection into view before returning. If false, posts a request which is processed at some point after the method returns. aVPercent How to align the frame vertically. A value of 0 means the frame's upper edge is aligned with the top edge of the visible area. A value of 100 means the frame's bottom edge is aligned with the bottom edge of the visible area. For values in between, the...
nsIServerSocket
this is what you need. PRNetAddr getAddress(); Parameters None. Return value The network address to which the socket is bound. init() Initializes a server socket. void init( in long aPort, in boolean aLoopbackOnly, in long aBackLog ); Parameters aPort The port of the server socket. Pass -1 to indicate no preference, and a port will be selected automatically. aLoopbackOnly If true, the server socket will only respond to connections on the local loopback interface. Otherwise, it will accept connections from any interface. To specify a particular network interface, use initWithAddress(). aBackLog The maximum length to which the queue of pending connections may grow. This parameter may be silently limited by the operating system. Pass -1 to use the default value. The defaul...
nsISessionStartup
e will be displayed. RESUME_SESSION 2 The previous session should be restored at startup. DEFER_SESSION 3 The previous session is viable but shouldn't be restored without explicit action (with the exception of app tabs, which are always restored in this case). Methods doRestore() Determines whether or not there is a session to restore. boolean doRestore(); Parameters None. Return value true if the session should be restored, otherwise false. ...
nsISocketTransport
arameters aType The timeout type, who's associated value should be retrieved. Can be one of the constants TIMEOUT_CONNECT or TIMEOUT_READ_WRITE. Return value Returns the timeout in seconds for the given Type. A value of PR_UINT32_MAX is equivalent to no timeout. isAlive() Test if this socket transport is (still) connected. boolean isAlive(); Parameters None. Return value Returns true if the socket is connected. Otherwise false. setTimeout() Sets a Socket timeout. void setTimeout( in unsigned long aType, in unsigned long aValue ); Parameters aType The timeout type which should be set to aValue. Can be one of the constants TIMEOUT_CONNECT or TIMEOUT_READ_WRITE. aValue Defines the timeout in seconds, pass PR_UINT32_MAX to specify no timeout. The...
nsIStyleSheetService
); Parameters sheetURI URI of the stylesheet to load and register. type One of the type constants. sheetRegistered() Check if a stylesheet has been registered boolean sheetRegistered( in nsIURI sheetURI, in unsigned long type ); Parameters sheetURI URI of the stylesheet to check. type One of the type constants. Return value Returns true if a style sheet at sheetURI has previously been added to the list of style sheets specified by type. unregisterSheet() Remove the style sheet at sheetURI from the list of style sheets specified by type. The removal takes effect immediately, even for already-loaded documents. void unregisterSheet( in nsIURI sheetURI, in unsigned long type ); Parameters sheetURI URI of the styl...
nsISupports proxies
that you are interested in. In this case, just simply use it. In most cases, you will want the main UI thread (aka the primordial thread). If this is the case, you can simply pass nsnull as the event queue. You may also use the defined flags which are defined in xpcom/threads/nsIEventQueueService.h#44. There is also logic that will determine if the caller is on the destination thread. If this is true, I will not call via proxy, but rather invoke the method directly which is an optimization. This detection will only be used if you are using a proxy created with the PROXY_SYNC flag. Example usage nsresult rv = NS_OK; nsCOMPtr<nsIProxyObjectManager> pIProxyObjectManager(do_GetService("@mozilla.org/xpcomproxy;1", &rv)); if(NS_FAILED(rv)) return rv; nsCOMPtr<IFoo> pTestObj(do_CreateInstance(FO...
nsITXTToHTMLConv
nsIStreamConverterService interface. Method overview void preFormatHTML(in boolean value); void setTitle(in wstring text); Prior versions of the interface named the methods using the InitialCaps style instead of the interCaps style. Methods preFormatHTML() Specifies whether or not to wrap the resulting HTML in an <pre> block. void preFormatHTML( in boolean value ); Parameters value true to wrap the resulting HTML in a <pre> block. setTitle() Sets the title to use on the resulting HTML document. void setTitle( in wstring text ); Parameters text Title to set for the HTML document. ...
nsIThreadEventFilter
nterface guidelines acceptEvent() This method is called to determine whether or not an event may be accepted by a nested event queue. (see nsIThreadInternal.PushEventQueue()) Warning: This method must not make any calls on the thread object. boolean acceptEvent( in nsIRunnable event ); Parameters event The event being dispatched. Return value Implement this method to return true if the event is accepted, or false to reject it. See also The Thread Manager nsIThreadManager nsIThread nsIThreadPool nsIThreadObserver nsIThreadInternal ...
nsIThreadManager
de only! nsIThread newThread(in unsigned long creationFlags); Attributes Attribute Type Description currentThread nsIThread The currently executing thread. If the calling thread does not already have a nsIThread associated with it, one is created and associate with the current PRThread. Read only. isMainThread boolean This attribute is true if the calling thread is the main thread of the application process. Read only. mainThread nsIThread The main thread. Read only. Methods Native code only!getThreadFromPRThread Given a PRThread, this method returns the corresponding nsIThread. Returns null if there isn't a corresponding nsIThread. nsIThread getThreadFromPRThread( in PRThread prthread ); Parameters p...
nsIThreadObserver
method nsIThread.ProcessNextEvent() before an event is processed. This method is only called on the target thread. It is valid to change the thread\'s observer during a call to this method. void onProcessNextEvent( in nsIThreadInternal thread, in boolean mayWait, in unsigned long recursionDepth ); Parameters thread The nsIThread on which the event is going to be processed. mayWait true if the method is allowed to block the calling thread. This parameter will be false during thread shutdown. recursionDepth The number of calls to nsIThread.ProcessNextEvent() on the call stack in addition to the current call. Example It is possible to overlay processing events for a GUI toolkit on top of the events for a thread: var NativeQueue; Observer = { onDispatchedEvent(thread) { ...
nsITransactionListener
ion at the top of the undo stack. void didMerge( in nsITransactionManager aManager, in nsITransaction aTopTransaction, in nsITransaction aTransactionToMerge, in boolean aDidMerge, in nsresult aMergeResult ); Parameters aManager The nsITransactionManager ending a batch. aTopTransaction The transaction at the top of the undo stack. aTransactionToMerge The transaction to merge. aDidMerge true if transaction was merged, else false. aMergeResult The nsresult returned after the merge attempt. didRedo() Called after a nsITransactionManager calls the nsITransaction.Redo() method of a transaction. void didRedo( in nsITransactionManager aManager, in nsITransaction aTransaction, in nsresult aRedoResult ); Parameters aManager The nsITransactionManager redoing the transaction. aTransac...
nsITransferable
get the load context from the document like this: var loadContext = doc.defaultView.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIWebNavigation) .QueryInterface(Ci.nsILoadContext); In C++ callers, if you have the corresponding document, you can just call nsIDocument.GetLoadContext() to get to the load context object. isLargeDataSet() Returns true if the data is large. boolean isLargeDataSet(); Parameters None. Return value true if the data is large; otherwise, the result is false. removeDataFlavor() Removes the data flavor matching the given one (as determined by a string comparison), along with the corresponding data. void removeDataFlavor( in string aDataFlavor ); Parameters aDataFlavor The data flavor to remove. s...
nsITreeSelection
index Index of the row to check. Return value rangedSelect() Select the range specified by the indices. void rangedSelect( in long startIndex, in long endIndex, in boolean augment ); Parameters startIndex Index to start selecting at. endIndex Index to stop selecting at. This parameter is inclusive; to select one item, set endIndex == startIndex. augment If true, the range is added to the selection without clearing out anything else. If false, everything is cleared except for the specified range. select() Deselect all rows and select the row at the specified index. void select( in long index ); Parameters index Index of the row to select. selectAll() Selects all rows. void selectAll(); Parameters None. timedSelect() Perform a timed select.
nsIUTF8ConverterService
UTF-8. AUTF8String convertStringToUTF8( in ACString aString, in string aCharset, in boolean aSkipCheck, in boolean aAllowSubstitution ); Parameters aString A string to ensure its UTF8ness. aCharset The charset to convert from if aString is not in UTF-8. aSkipCheck Determines whether or not to skip 'ASCIIness' and 'UTF8ness' check. Set this to PR_TRUE only if you suspect that aString can be mistaken for ASCII / UTF-8 but is actually not in ASCII / UTF-8 so that aString has to go through the conversion. Skipping ASCIIness/UTF8ness check. The most common case is the input is in 7bit non-ASCII character sets like ISO-2022-JP, HZ or UTF-7 (in its original form or a modified form used in IMAP folder names). aAllowSubstitution when tru...
nsIUpdate
error occurred while writing the patched application. UNEXPECTED_ERROR (8) An unanticipate type of error occurred. extensionVersion AString The add-on version of this update. Used by the extension system to track compatibility of installed add-ons with this update. Obsolete since Gecko 2.0 installDate long long The date and time at which the update was installed. isCompleteUpdate boolean true if the update is a complete replacement of the existing installation; false if the update is a patch representing the difference between the new version and the existing version. isSecurityUpdate boolean true if the update is a security update. If the update is a security update, a more seriously-worded user interface message is used to present the update to the user. licenseURL AString The U...
nsIUpdateChecker
ing that all update checking should be stopped. This disables the update checking preferences. Methods checkForUpdates() Checks for available updates, notifying a listener of the results. void checkForUpdates( in nsIUpdateCheckListener listener, in boolean force ); Parameters listener An object implementing nsIUpdateCheckListener to be notified of the results of an update check. force If true, the update checker checks for updates, regardless of the current value of the user's update settings. This is used by any user interface that offers the user the opportunity to check for updates immediately. The force option doesn't work if the system administrator has locked the app.update.enabled preference. stopChecking() Ends any pending update check. void stopChecking( in unsigned short ...
nsIUpdatePatch
ent serialize(in nsIDOMDocument updates); Attributes Attribute Type Description finalURL AString The final URL this patch was being downloaded from. hashFunction AString The hash function to use when determining the integrity of the patch file. hashValue AString The value of the hash function named in hashFunction that should be computed if the file is not corrupt. selected boolean true if this patch is currently selected as the patch to be downloaded and installed for this update transaction. false if another update is selected. size unsigned long The size of the patch file in bytes. state AString The state of this patch. type AString The type of patch represented by the object: "partial" A binary difference between two application versions. "complete" A complete patch c...
nsIUploadChannel2
Parameters aStream The stream to be uploaded by this channel. aContentType This value will replace any existing Content-Type header on the HTTP request, regardless of whether or not its empty. aContentLength A value of -1 indicates that the length of the stream should be determined by calling the stream's available method. aMethod The HTTP request method to set on the stream. aStreamHasHeaders true if the stream already contains headers for the HTTP request. ...
nsIWebBrowser
The top-level DOM window. The embedder may walk the entire DOM starting from this value. Read only. isActive boolean Indicates whether this web browser is active. Active means that it's visible enough that we want to avoid certain optimizations like discarding decoded image data and throttling the refresh driver. In Firefox, this corresponds to the visible tab. Defaults to true. For optimal performance, set it to false when appropriate. parentURIContentListener nsIURIContentListener URI content listener parent. The embedder may set this property to their own implementation if they intend to override or prevent how certain kinds of content are loaded. Note: If this attribute is set to an object that implements nsISupportsWeakReference, the im...
nsIWebBrowserChrome
odalEventLoop() Exit a modal event loop if we're in one. The implementation should also exit out of the loop if the window is destroyed. void exitModalEventLoop( in nsresult aStatus ); Parameters aStatus The result code to return from showAsModal(). isWindowModal() Is the window modal (that is, currently executing a modal loop)? boolean isWindowModal(); Parameters None. Return value true if it's a modal window. setStatus() Called when the status text in the chrome needs to be updated. void setStatus( in unsigned long statusType, in wstring status ); Parameters statusType Indicates what is setting the text. status Status string. null is an acceptable value meaning no status. showAsModal() Shows the window as a modal window. void showAsModal(); Parameters No...
nsIWebBrowserFind
o match entire words only. Default is false. findBackwards boolean Whether to find backwards (towards the beginning of the document). Default is false (search forward). matchCase boolean Whether to match case (case sensitive) when searching. Default is false. searchFrames boolean Whether to search through all frames in the content area. Default is true. Note: That you can control whether the search propagates into child or parent frames explicitly using nsIWebBrowserFindInFrames, but if one, but not both, of searchSubframes and searchParentFrames are set, this returns false. searchString wstring The string to search for. This must be non-empty to search. wrapFind boolean Whether the search wraps around to the s...
nsIWebBrowserFindInFrames
o or contained within the rootSearchFrame. rootSearchFrame nsIDOMWindow Frame within which to confine the search (normally the content area frame). Set this to only search a subtree of the frame hierarchy. searchParentFrames boolean Whether to allow the search to propagate out of the currentSearchFrame into its parent frame(s). Search is always confined within the rootSearchFrame. Default is true. Setting nsIWebBrowserfind.searchFrames to true sets this to true. searchSubframes boolean Whether to recurse down into subframes while searching. Default is true. Setting nsIWebBrowserfind.searchFrames to true sets this to true. See also nsIWebBrowserFind ...
nsIWebNavigation
META-refreshes. STOP_CONTENT 2 This flag specifies that all content activity should be stopped. This includes animated images, plugins and pending Javascript timeouts. STOP_ALL 3 This flag specifies that all activity should be stopped. Attributes Attribute Type Description canGoBack PRBool Indicates if the object can go back. If true this indicates that there is back session history available for navigation. Read only. canGoForward PRBool Indicates if the object can go forward. If true this indicates that there is forward session history available for navigation. Read only. currentURI nsIURI The currently loaded URI or null. Read only. document nsIDOMDocument Retrieves the current...
nsIWebProgressListener
le here shows you how to detect what flags are popping up where. It puts the messages into the Browser Console. /** * This example assumes that it's being run within the context of a browser * window, and uses a frame script that will be loaded into every * browser tab. */ let mm = window.getGroupMessageManager("browsers"); mm.loadFrameScript("chrome://path/to/some/example-framescript.js", true); mm.addMessageListener("MyAddonMessage", (message) => { let data = message.data; let browser = message.target; let outerWindowID = data.outerWindowID; // browser is now the <xul:browser> that saw the web progress activity // occur. If you need to hold onto an identifier for whichever frame // (be it the top-level, or a subframe) was using the WebProgress, use // the outerWindowID. ...
nsIWebProgressListener2
ta http-equiv="refresh"> or an HTTP Refresh: header. boolean onRefreshAttempted( in nsIWebProgress aWebProgress, in nsIURI aRefreshURI, in long aMillis, in boolean aSameURI ); Parameters aWebProgress The nsIWebProgress instance that fired the notification. aRefreshURI The new URI that aWebProgress has requested redirecting to. aMillis The delay (in milliseconds) before refresh. aSameURI True if aWebProgress is requesting a refresh of the current URI. False if aWebProgress is requesting a redirection to a different URI. Return value True if the refresh may proceed. False if the refresh should be aborted. ...
nsIWebappsSupport
meters title The user-friendly name of the application. uri The uri of the web application. iconUri The uri of icon of the web application. iconData A base64 encoded representation of the application's icon. isApplicationInstalled() Checks is a web application is already installed. boolean isApplicationInstalled( in wstring uri ); Parameters uri The uri of the web application. Return value true if the web application is installed, false if it's not installed. ...
nsIWinAppHelper
a.org/xre/app-info;1"] .getService(Components.interfaces.nsIWinAppHelper); The nsIXULAppInfo and nsIXULRuntime interfaces are also implemented by "xre/app-info". Method overview void fixReg(); Obsolete since Gecko 1.9 void postUpdate(in nsILocalFile logFile); Obsolete since Gecko 1.9.2 Attributes Attribute Type Description userCanElevate boolean Read only. 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. Methods fixReg() Obsolete since Gecko 1.9 (Firefox 3) Invokes helper.exe with the /fixreg parameter. Note t...
nsIWinTaskbar
Read only. defaultGroupId AString The default application user model ID the application registers with the system. This ID is used by the taskbar for grouping windows and when associating pinned shortcuts with running instances and jump lists. Read only. ...
nsIXULTemplateResult
moved(); void ruleMatched(in nsISupports aQuery, in nsIDOMNode aRuleNode); Attributes Attribute Type Description id AString ID of the result. The DOM element created for this result, if any, will have its id attribute set to this value. The id must be unique for a query. isContainer boolean true if the result represents a container. Read only. isEmpty boolean true if the result represents an empty container. Read only. mayProcessChildren boolean true if the template builder may use this result as the reference point for additional recursive processing of the template. The template builder will reprocess the template using this resul...
nsIZipEntry
Firefox 3) Attributes Attribute Type Description compression unsigned short The type of compression used for the item. The possible values and their meanings are defined in the zip file specification at ZIP Application Note Support. Read only. CRC32 unsigned long The CRC-32 hash of the file in the entry. Read only. isDirectory boolean True if the name of the entry ends with '/' and false otherwise. Read only. isSynthetic boolean Use this attribute to determine whether this item is an actual zip entry or is one synthesized for part of a real entry's path. A synthesized entry represents a directory within the zip file which has no corresponding entry within the zip file. For example, the entry for the directory foo/ i...
NS_ASSERTION
In a debug build the failure text is written to console (stderr), into the NSPR debug log, and on Windows a dialog box is opened. The behavior of an assertion failure can be controlled using the XPCOM_DEBUG_BREAK environment variable. An assertion failure should be thrown on critical program errors only. A triggered assertion failure is equivalent to crashing in Tinderbox tests. Note on terminology: "assertion" is the condition to test. There is always an assertion in NS_ASSERTION; it is the first argument. Only if the assertion evaluates to false is there an "assertion failure", which is thrown. ...
NS ENSURE SUCCESS
Summary Macro Returns return-value if NS_FAILED(nsresult) evaluates to true, and shows a warning on stderr in that case. Syntax NS_ENSURE_SUCCESS(nsresult, return-value); Usage nsresult mozMyClass::MozStringMucking() { nsresult rv = NS_CStringCopy(mDestString, mSrcString); NS_ENSURE_SUCCESS(rv, rv); // this is the same as doing: nsresult rv = NS_CStringCopy(mDestString, mSrcString); if (NS_FAILED(rv)) return rv; return NS_OK; } ...
nsICookie2 MOZILLA 1 8 BRANCH
netwerk/cookie/public/nsICookie2.idlScriptable Please add a summary to this article. Last changed in Gecko 1.9 (Firefox 3) Inherits from: nsICookie2 Attributes Attribute Type Description isHttpOnly boolean Holds true if the cookie is an http only cookie. Read only. See also nsICookie2 ...
XPCOM reference
ocate memory, get access to services, and to instantiate interfaces.FoldersThe folder classes all implement the nsIMsgFolder interface. There are currently three folder classes - nsLocalMailFolder, nsImapMailFolder, and nsNewsFolder. They all inherit from nsMsgDBFolder, which implements a lot of the core functionality. 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). This macro is meant for critical errors; like assertions, NS_ERRORs should not be reachable.NS_IF_ADDREFMacroNS_IF_RELEASEMacroNS_RELEASE...
Status, Recent Changes, and Plans
unction result. bug 59414: making operator& private may help prevent some leaks caused by casting Move the factored nsCOMPtr routines into their own library, to reduce nsCOMPtr clients' dependency on the XPCOM library. Recent changes to this document Removed the statement that == and != between an nsCOMPtr and a raw pointer or literal 0 does not work on some compilers since it is no longer true. Added an entire section to the Getting Started Guide on nsCOMPtrs in function signatures Added references to recent bugs influencing the use of nsCOMPtr machinery: bug 59212, and bug 59414 Fixed comparisons 1 and 3, as per comments by Morten Welinder Updated examples to prefer direct initialization over copy initialization. ...
Using nsIDirectoryService
eturn an nsIFile }, } Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIDirectoryService).registerProvider(provider); When the callback is called, it will be passed the string key, and should return an nsIFile. The persistant flag allows you to specify if you want the nsDirectoryService to cache this value. In most cases you would set this to be true. The interfaces for this can be found here. Known Locations The nsIProperties strings for currently defined locations can be found in: nsDirectoryServiceDefs.h nsAppDirectoryServiceDefs.h nsXULAppAPI.h Content formerly at http://www.mozilla.org/projects/xpco...locations.html Background The way in which Mozilla components locate special files and directories has changed. In the past, this was...
Using the clipboard
Here are the steps to pasting: Create a clipboard object which refers to the system clipboard. Create a transferring object which implements the nsITransferable interface. Initialize the transferring object wi...
XPIDL Syntax
Mozilla › Tech › XPIDL › Syntax
xpr /= expr ("+" / "-") expr expr /= expr ("*" / "/" / "%") expr expr /= ["-" / "+" / "~"] (scoped_name / literal / "(" expr ")" ) ; Numeric literals: quite frankly, I'm sure you know how these kinds of ; literals work, and these are annoying to specify in ABNF. literal = octal_literal / decimal_literal / hex_literal / floating_literal literal /= string_literal / char_literal literal /= "TRUE" / "FALSE" ; In regex: /"[^"\n]*["\n]/. Yes, newline terminates. string_literal = 1*(%x22 *(any char except %x22 or %x0a) (%x22 / %x0a)) ; Same as above, but s/"/'/g char_literal = 1*(%x27 *(any char except %x27 or %x0a) (%x27 / %x0a)) type_spec = "float" / "double" / "string" / "wstring" type_spec /= ["unsigned"] ("short" / "long" / "long" "long") type_spec /= "char" / "wchar" / "bool...
Creating a gloda message query
the message must belong to one of the specified conversations. The conversation must be a GlodaConversation instance. You find these by first finding a message and then accessing its "conversation" attribute. query.tags(tag1, tag2, tag3, ...): Add the constraint that the message must have one of the provided nsIMsgTag tags applied. (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. query.bodyMatches(searchString): Perform a full-text search against plaintext message bodies. query.attachmentTypes(mimeType1, mimeType2, ...): Constrain to messages with attachments among the given mime types. In the...
MailNews fakeserver
s sent in pipelining mode and will present lines without any EOL characters. In addition, it uses UTF-8 as the transmission medium. The server presents the following API to the handler: <caption> Server API </caption> Name Arguments Returns Description closeSocket none nothing Closes the socket and stops the test. setMultiline the new value of multiline nothing The value is a boolean, with true invoking multiline mode. It is off by default. Extending a handler to provide different mechanisms is a process not defined here; please check the documentation of the corresponding handler for instructions. Using fakeserver in xpcshell tests Since there are three different components of fakeserver, a total of four objects need to be set up in a fakeserver test on top of other testing. The ou...
Adding items to the Folder Pane
This property is an array of folder-tree-items. Each item in this array satisfies the following interface: id (attribute) a unique string for this object. Must persist over sessions text (attribute) the text to display in the tree level (attribute) the level in the tree ...
Access Window
le, registering timer events and much more. The Window API will give you the complete details. Since window is a global variable you can use it directly from your JavaScript file. Check if the window is a tab or the root window window.addEventListener("load", function(e) { alert("Is root?: " + isRoot()); }, false); function isRoot() { if(window != window.top) 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. Register a timer window.setInterval( function() { alert('foobar'); }, 60000); //execute the function once very minute If you periodically need to perform a certain action then you can use the setInterval function, it will then call this function every x mil...
Use SQLite
nside your profile directory with a table called attachments. You can see the schema for the attachments table in the code. To double check the information you've inserted you can query the tbird.sqlite file using regular SQLite programs. const Cc = Components.classes; const Ci = Components.interfaces; var tbirdsqlite = { onLoad: function() { // initialization code this.initialized = true; this.dbInit(); }, dbConnection: null, dbSchema: { tables: { attachments:"id INTEGER PRIMARY KEY, \ name TEXT \ encoded TEXT NOT NULL" } }, dbInit: function() { var dirService = Cc["@mozilla.org/file/directory_service;1"]. getService(Ci.nsIProperties); var dbFile = dirService.get("ProfD"...
customDBHeaders Preference
o that we can extract the 'X-Superfluous' field var key = gDBView.getKeyAt(row); var hdr = gDBView.db.GetMsgHdrForKey(key); var retval = hdr.getStringProperty("x-superfluous"); dump("x-superfluous: " + retval + "\n"); return retval; }, getSortStringForRow: function(hdr) { return hdr.getStringProperty("x-superfluous"); }, isString: function() {return true;}, getCellProperties: function(row, col, props){}, getImageSrc: function(row, col) {return null;}, getSortLongForRow: function(hdr) {return 0;} } function addCustomColumnHandler() { gDBView.addColumnHandler("colSuperfluous",columnHandler); dump("column handler being added: " + columnHandler + "\n"); } var CreateDbObserver = { // Components.interfaces.nsIObserver obser...
Working with windows in chrome code
code. Example 5: Using nsIWindowWatcher for passing an arbritrary JavaScript object It is still possible to pass any JavaScript object using nsIWindowWatcher, it just takes a little more effort. In this example a single object is passed, though it is possible to pass multiple objects and primitives using a combination of this and the example above. // In the calling code var args = { param1: true, param2: 42 }; args.wrappedJSObject = args; var watcher = Components.classes["@mozilla.org/embedcomp/window-watcher;1"] .getService(Components.interfaces.nsIWindowWatcher); watcher.openWindow(null, url, windowName, features, args); // In the window code var args = window.arguments[0].wrappedJSObject; This uses the wrappedJSObject trick. By passing args to openW...
Using COM from js-ctypes
d until the speaking is done. If this code were used in a production add-on, then to avoid Firefox locking up, run this code from a ChromeWorker. ...
Using Objective-C from js-ctypes
1', [ { isa: ctypes.voidptr_t }, { flags: ctypes.int32_t }, { reserved: ctypes.int32_t }, { invoke: ctypes.voidptr_t }, { descriptor: Block_descriptor_1.ptr } ]); var BLOCK_CONST = { BLOCK_HAS_COPY_DISPOSE: 1 << 25, BLOCK_HAS_CTOR: 1 << 26, BLOCK_IS_GLOBAL: 1 << 28, BLOCK_HAS_STRET: 1 << 29, BLOCK_HAS_SIGNATURE: 1 << 30 }; // based on work from here: https://github.com/trueinteractions/tint2/blob/f6ce18b16ada165b98b07869314dad1d7bee0252/modules/Bridge/core.js#L370-L394 var bl = Block_literal_1(); // Set the class of the instance bl.isa = _NSConcreteGlobalBlock; // Global flags bl.flags = BLOCK_CONST.BLOCK_HAS_STRET; bl.reserved = 0; bl.invoke = aFuncTypePtr; // create descriptor var desc = Block_descriptor_1(); desc.reserved = 0; desc.size = Block_liter...
Declaring and Using Callbacks
ects. The return type of the javascript callback must match the return type declared, otherwise js-ctypes will throw an error saying "unexpected return type". Examples Example 1 This callback that returns bool and has two arguments. var myFuncTypeDeclaration = ctypes.FunctionType(ctypes.default_abi, ctypes.bool, [ctypes.int, ctypes.voidptr_t]); function myJSCallback(cInt, cPtr) { return true; // as the return of the FunctionType was ctypes.bool we must make our javascript callback return bool otherwise js-ctypes will throw error saying unexpected type return } var myCCallback = myFuncTypeDeclaration.ptr(myJSCallback); Example 2 This callback that returns void and no arguments. When void is the return type, the javascript callback must not return, or it should return undefined. v...
Declaring types
"); var anotherStruct = ctypes.StructType("anotherStruct", [ {field1: opaque.ptr} ]); someStructure.define([ { ptrToAnotherStruct: anotherStruct.ptr } ]); As you see here, the two structure types here contain pointers to each other; by making one of them opaque at first, you can declare the fields on the other one, then define the fields on the first one afterward. This works around the lack of true forward references in JavaScript. Structures with next field It is common to see structures with a "next" field that is a pointer to itself. In order to accomplish this you can either set the type of next to ctypes.voidptr_t, or to be more accurate, use the define technique: var struct = ctypes.StructType('struct'); struct.define([{ next: struct.ptr }]); Arrays To declare a new array type, y...
Standard OS Libraries
, typically version 2 is referred to as just GDK and version 3 is referred to as GDK3. Examples for both are found below. Documentation for GDK functions are found here: GNOME Developer :: GDK 2 Reference Manual. For GDK3 documentation is found here: GNOME Developer :: GDK 3 Reference Manual. Because GNOME is in the name of the websites don't get confused and think this only works on GNOME. It is true though that GDK was developed by the GNOME team. Example: gdk_window_get_pointer This example is fot the GDK 2.0 library. In GDK 3.0 the gdk_window_get_device_position function was deprecated, see below for GDK 3.0 example. Components.utils.import('resource://gre/modules/ctypes.jsm'); var gdk = ctypes.open('libgdk-x11-2.0.so.0'); // types var gint = ctypes.int; var GdkDevice = ctypes.StructT...
CData
attempts to do readString on it, if it errors then it tries to read it in another way, so this is an alternative to readStringReplaceMalformed, it is an attempt at readingMalformed function readAsChar8ThenAsChar16(stringPtr, known_len, jschar) { // when reading as jschar it assumes max length of 500 // stringPtr is either char or jschar, if you know its jschar for sure, pass 2nd arg as true // if known_len is passed, then assumption is not made, at the known_len position in array we will see a null char // i tried getting known_len from stringPtr but its not possible, it has be known, i tried this: //"stringPtr.contents.toString()" "95" //"stringPtr.toString()" "ctypes.unsigned_char.ptr(ctypes.UInt64("0x7f73d5c87650"))" // so as we see neither of thes...
PointerType
is will throw a TypeError exception if the value can't be converted. PointerType CData Method_overview bool isNull() Methods inherited from CData CData address() String toSource() String toString() PointerType CData Methods isNull() Determines whether or not the pointer's value is null. bool isNull(); Parameters None. Return value true if the pointer's value is null, otherwise false. See Also CType CData Type conversion ...
Initialization and Destruction - Plugins
array contains the attribute values. The browser ignores any nonstandard attributes in an embed element, so the web page author can use the arg parameters to specify private attributes defined for a particular plug-in. For example, the following embed element has the standard attributes src, height, and width and the private attribute loop: <embed src="movie.avi" height="100" width="100" loop="true"> With the embed element in the example, the browser passes the values in argv to the plug-in instance: argc = 4 argn = { "src", "height", "width", "loop" } argv = { "movie.avi", "100", "100", "true" } The saved parameter allows an instance of a plug-in to save its data and, when the instance is destroyed, pass the data to the next instance of the plug-in at the same URL. The data is saved in...
Streams - Plugins
rror NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream, NPBool seekable, uint16* stype); The instance parameter refers to the plug-in instance receiving the stream; the type parameter represents the stream's MIME type. The stream parameter is a pointer to the new stream, which is valid until the stream is destroyed. The seekable parameter specifies whether the stream is seekable (true) or not (false). Seekable streams support random access (for example, local files or HTTP servers that support byte-range requests). The plug-in can set the output parameter type to one of these transmission modes: NP_NORMAL: (Default): The plug-in can process the data progressively as it arrives from the network or file system through a series of calls to NPP_WriteReady and NPP_Write. NP_AS...
Color vision simulation - Firefox Developer Tools
f. Contrast sensitivity loss can be caused by cataracts, glaucoma, diabetic retinopathy, and other disorders of the retina; it can be age-related, congenital, or due to an injury. To enable this feature, you must have webrender enabled; it may be enabled by default, depending on your configuration of Firefox. In the Firefox Configuration Editor, make sure the gfx.webrender.all option is set to true. In the Simulate menu, you can choose one option at a time from the following list: None -- choose this to return to normal display Protanomaly (low red) Deuteranomaly (low green) Tritanomaly (low blue) Protanopia (no red) Deuteranopia (no green) Tritanopia (no blue) Contrast loss These simulations are not completely medically accurate. However, they can give you a sense of what yo...
DOM Inspector internals - Firefox Developer Tools
e the Inspect menus' ("Inspect Content Document" and "Inspect Chrome Document") popups from the File menu, and the "Document Viewer" and "Object Viewer" menus from the View menu. The preference menuitems in the View menu that affect only the DOM Nodes viewer ("Blink Selected Element", et cetera) are added by that viewer's popup overlay (resources/content/viewers/dom/popupOverlay.xul). The same is true for the Find menuitems and the "Select Element By Click" menuitem in the Edit menu, since no other viewers besides the DOM Nodes viewer support these features. The other Edit menu items are also used in several viewers' context menus. For that reason, only those menuitems' ids are referenced here, and the complete definitions are imported from editingOverlay.xul. Viewers which include one or mo...
Set a conditional breakpoint - Firefox Developer Tools
A normal breakpoint is just associated with a line: when the program reaches that line, the debugger pauses. A conditional breakpoint also has a condition associated with it, which is represented as an expression. When the program reaches the line, the debugger pauses only if the breakpoint's specified expression evaluates to true. This makes it possible to debug specific scenarios, such as bugs that only happen on odd entries in a list, or errors that occur the last time through a loop, for example. To set a conditional breakpoint, activate the context menu in the source pane, on the line where you want the breakpoint, and select "Add Conditional Breakpoint". You'll then see a textbox where you can enter the expression. Press Return to finish. Conditional breakpoints are shown as orange...
Index - Firefox Developer Tools
ools, Firefox, Guide, JavaScript debugging, Tools, WM, breakpoint A normal breakpoint is just associated with a line: when the program reaches that line, the debugger pauses. A conditional breakpoint also has a condition associated with it, which is represented as an expression. When the program reaches the line, the debugger pauses only if the breakpoint's specified expression evaluates to true. 130 Set watch expressions When debugging code, sometimes it's useful to watch expressions as executions are paused. The Debugger features a pane for entering expressions to be watched (watch expressions). As you step through code, the debugger will watch the expression and return any results. 131 Step through code Debugger, DevTools, JavaScript, Step through ...
JSON viewer - Firefox Developer Tools
From Firefox 53 onwards, the JSON viewer is also enabled by default in Beta and the normal release version of Firefox. Firefox includes a JSON viewer. ...
Network request details - Firefox Developer Tools
See https://en.wikipedia.org/wiki/Special:CentralAutoLogin/P3P for more info.\"" }, { "name": "server", "value": "mw1316.eqiad.wmnet" }, { "name": "server-timing", "value": "cache;desc=\"pass\"" }, { "name": "strict-transport-securit...
Network request list - Firefox Developer Tools
-Cookie header with a Domain attribute that matches the specified value. set-cookie-domain:.mozilla.org set-cookie-name Shows the resources that have a Set-Cookie header with a name that matches the specified value. set-cookie-name:_ga set-cookie-value Shows the resources that have a Set-Cookie header with a value that matches the specified value. set-cookie-value:true regexp Shows the resources having a URL that matches the given regular expression. regexp:\d{5} regexp:mdn|mozilla For example, to find all 404, not found, errors, you can type "404" into the search and auto-complete suggests "status-code:404" so you'll end up with something like this: Search in requests Use the Search panel to run a full-text search on headers and c...
Use the Inspector API - Firefox Developer Tools
.node - returns the actual element from the page .window - the window object of the frame the selection is in. ...
Animation inspector example: Web Animations API - Firefox Developer Tools
var noteKeyframeOptions = { duration: 500, fill: 'forwards', easing: 'ease-out', delay: 150 } var icon = document.getElementById("icon"); var note = document.getElementById("note"); var iconAnimation = icon.animate(iconKeyframeSet, iconKeyframeOptions); var noteAnimation = note.animate(noteKeyframeSet, noteKeyframeOptions); iconAnimation.pause(); noteAnimation.pause(); var firstTime = true; function animateChannel(e) { if (e.button != 0) { return; } if (e.target.id != "icon") { return; } if (firstTime) { iconAnimation.play(); noteAnimation.play(); firstTime = false; } else { iconAnimation.reverse(); noteAnimation.reverse(); } } document.addEventListener("click", animateChannel); ...
AbortSignal.aborted - Web APIs
Syntax var isAborted = abortSignal.aborted; Value A Boolean Examples In the following snippet, we create a new AbortController object, and get its AbortSignal (available in the signal property). Later on we check whether or not it the signal has been aborted using the aborted property, and send an appropriate log to the console. var controller = new AbortController(); var signal = controller.signal; // ... ...
AbortSignal - Web APIs
al interface represents a signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. Properties The AbortSignal interface also inherits properties from its parent interface, EventTarget. AbortSignal.aborted Read only A Boolean that indicates whether the request(s) the signal is communicating with is/are aborted (true) or not (false). Events Listen to this event using addEventListener() or by assigning an event listener to the oneventname property of this interface. abort Invoked when the DOM request(s) the signal is communicating with is/are aborted. Also available via the onabort property. Methods The AbortSignal interface inherits methods from its parent interface, EventTarget. Examples In the ...
AbstractRange.collapsed - Web APIs
A collapsed range is one in which the start and end positions are the same, resulting in a zero-character-long range.. Specifications Specification Status Comment DOMThe definition of 'collapsed' in that specification. ...
AbstractRange - Web APIs
A collapsed range is one whose start position and end position are the same, resulting in a zero-character-long range. endContainer Read only The DOM Node in which the end of the range, as specified by the endOffset property, is located. endOffset Read only An integer value indicating the offset, in characters, from the beginning of the node's contents to the begi...
AesCtrParams - Web APIs
and the rest is used for the nonce. For example, if length is set to 64, then the first half of counter is the nonce and the second half is used for the counter. length A Number -- the number of bits in the counter block that are used for the actual counter. The counter must be big enough that it doesn't wrap: if the message is n blocks and the counter is m bits long, then the following must be true: n <= 2m. The NIST SP800-38A standard, which defines CTR, suggests that the counter should occupy half of the counter block (see Appendix B.2), so for AES it would be 64. Examples See the examples for SubtleCrypto.encrypt() and SubtleCrypto.decrypt(). Specifications Specification Status Comment Web Cryptography APIThe definition of 'SubtleCrypto.AesCtrParams' in that ...
AnalyserNode.getFloatFrequencyData() - Web APIs
For more complete applied examples/information, check out our Voice-change-O-matic-float-data demo (see the source code too). <!doctype html> <body> <script> const audioCtx = new AudioContext(); //Create audio source //Here, we use an audio file, but this could also be e.g. ...
Animation.pending - Web APIs
Web › API › Animation › pending
The read-only Animation.pending property of the Web Animations API indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation. Syntax var pending = Animation.pending; Value true if the animation is pending, false otherwise. Specifications Specification Status Comment Web AnimationsThe definition of 'pending' in that specification. Working Draft ...
AnimationEvent.initAnimationEvent() - Web APIs
ng identifying the specific type of animation event that occurred. The following values are allowed: Value Meaning animationstart The animation has started. animationend The animation completed. animationiteration The current iteration just completed. 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). animationNameArg A DOMString containing the value of the animation-name CSS property associated with the transition. elapsedTimeArg A float indicating the amount of time the animation has been running, in seconds, as of the time the event was fired, excluding any tim...
AudioBufferSourceNode - Web APIs
ult value is 0 (meaning no detuning), and its nominal range is -? to ?. AudioBufferSourceNode.loop A Boolean attribute indicating if the audio asset must be replayed when the end of the AudioBuffer is reached. Its default value is false. AudioBufferSourceNode.loopStart Optional A floating-point value indicating the time, in seconds, at which playback of the AudioBuffer must begin when loop is true. Its default value is 0 (meaning that at the beginning of each loop, playback begins at the start of the audio buffer). AudioBufferSourceNode.loopEnd Optional A floating-point number indicating the time, in seconds, at which playback of the AudioBuffer stops and loops back to the time indicated by loopStart, if loop is true. The default value is 0. AudioBufferSourceNode.playbackRate An a-rate...
AudioContext() - Web APIs
vailable properties are as follows: latencyHint Optional The type of playback that the context will be used for, as a value from the AudioContextLatencyCategory enum or a double-precision floating-point value indicating the preferred maximum latency of the context in seconds. The user agent may or may not choose to meet this request; check the value of AudioContext.baseLatency to determine the true latency after creating the context. sampleRate Optional The sampleRate to be used by the AudioContext, specified in samples per second. The value may be any value supported by AudioBuffer. If not specified, the preferred sample rate for the context's output device is used by default. Return value The newly constructed AudioContext instance. Exceptions NotSupportedError The specified sa...
AudioContext.createMediaStreamSource() - Web APIs
'pre'); var video = document.querySelector('video'); var myScript = document.querySelector('script'); var range = document.querySelector('input'); // getUserMedia block - grab stream // put it into a MediaStreamAudioSourceNode // also output the visuals into a video element if (navigator.mediaDevices) { console.log('getUserMedia supported.'); navigator.mediaDevices.getUserMedia ({audio: true, video: true}) .then(function(stream) { video.srcObject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // Create a MediaStreamAudioSourceNode // Feed the HTMLMediaElement into it var audioCtx = new AudioContext(); var source = audioCtx.createMediaStreamSource(stream); ...
AudioContextOptions - Web APIs
Context() constructor. Properties latencyHint Optional The type of playback that the context will be used for, as a value from the AudioContextLatencyCategory enum or a double-precision floating-point value indicating the preferred maximum latency of the context in seconds. The user agent may or may not choose to meet this request; check the value of AudioContext.baseLatency to determine the true latency after creating the context. sampleRate Optional The sampleRate to be used by the AudioContext, specified in samples per second. The value may be any value supported by AudioBuffer. If not specified, the preferred sample rate for the context's output device is used by default. Constants Standard values for latencyHint The latencyHint property can be number specifying a preferred maxi...
AudioNode.context - Web APIs
Web › API › AudioNode › context
used to construct this AudioNode. Example const AudioContext = window.AudioContext || window.webkitAudioContext; const audioCtx = new AudioContext(); const oscillator = audioCtx.createOscillator(); const gainNode = audioCtx.createGain(); oscillator.connect(gainNode).connect(audioCtx.destination); console.log(oscillator.context); // AudioContext console.log(oscillator.context === audioCtx); // true Specifications Specification Status Comment Web Audio APIThe definition of 'context' in that specification. Working Draft ...
AudioParam.defaultValue - Web APIs
s the initial value of the attributes as defined by the specific AudioNode creating the AudioParam. Syntax var defaultVal = audioParam.defaultValue; Value A floating-point Number. Example const audioCtx = new AudioContext(); const gainNode = audioCtx.createGain(); const defaultVal = gainNode.gain.defaultValue; console.log(defaultVal); // 1 console.log(defaultVal === gainNode.gain.value); // true Specifications Specification Status Comment Web Audio APIThe definition of 'defaultValue' in that specification. Working Draft ...
AudioParam.value - Web APIs
Web › API › AudioParam › value
yields 5.300000190734863. One solution is to use the Math.fround() method, which returns the single-precision value equivalent to the 64-bit JavaScript value specified--when setting value, like this: const source = new AudioBufferSourceNode(...); const rate = Math.fround(5.3); source.playbackRate.value = rate; console.log(source.playbackRate.value === rate); In this case, the log output will be true. Value of a property which is changing over time The value of an AudioParam can either be fixed or can vary over time. This is reflected by the value getter, which returns the value of the parameter as of the audio rendering engine's most recent render quantum, or moment at which audio buffers are processed and updated. In addition to processing audio buffers, each render quantum updates the va...
AudioParamDescriptor - Web APIs
h.random() * 2 - 1) * (parameters['customGain'].length > 1 ? parameters['customGain'][i] : parameters['customGain'][0]) // note: a parameter contains an array of 128 values (one value for each of 128 samples), // however it may contain a single value which is to be used for all 128 samples // if no automation is scheduled for the moment. } }) return true } } registerProcessor('white-noise-processor', WhiteNoiseProcessor) Next, in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing it the name of the processor, and connect the node to an audio graph. const audioContext = new AudioContext() await audioContext.audioWorklet.addModule('white-noise-processor.js') const whiteNoiseNode = new AudioWorkletNo...
AudioProcessingEvent - Web APIs
new AudioContext(); source = audioCtx.createBufferSource(); // Create a ScriptProcessorNode with a bufferSize of 4096 and a single input and output channel var scriptNode = audioCtx.createScriptProcessor(4096, 1, 1); console.log(scriptNode.bufferSize); // load in an audio track via XHR and decodeAudioData function getData() { request = new XMLHttpRequest(); request.open('GET', 'viper.ogg', true); request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { myBuffer = buffer; source.buffer = myBuffer; }, function(e){"Error with decoding audio data" + e.err}); } request.send(); } // Give the node a function to process audio events scriptNode.onaudioprocess = f...
AudioScheduledSourceNode.onended - Web APIs
he node. This event is sent to the node when the concrete interface (such as AudioBufferSourceNode, OscillatorNode, or ConstantSourceNode) determines that it has stopped playing. The ended event is only sent to a node configured to loop automatically when the node is stopped using its stop() method. This is the case, for example, when using an AudioBufferSourceNode with its loop property set to true. Syntax AudioScheduledSourceNode.onended = EventHandler; Value A function which is called by the browser when the ended event occurs on the AudioScheduledSourceNode. The function receives as input a single parameter, which is an object of type Event describing the event that occurred. Examples In this simple example, an event listener for the ended event is set up to enable a "Start" butt...
AudioTrack.enabled - Web APIs
The AudioTrack property enabled specifies whether or not the described audio track is currently enabled for use. 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. Example This example switches between the main and commentary audio tracks of a media element. function swapCommentaryMain() { var videoElem = document.getElementById("main-video"); var audioTrackMain; var audioTrackCommentary; ...
AudioTrack - Web APIs
or functions such as forEach(). This first example gets the first audio track on the media: var firstTrack = tracks[0]; The next example scans through all of the media's audio tracks, enabling any that are in the user's preferred language (taken from a variable userLanguage) and disabling any others. tracks.forEach(function(track) { if (track.language === userLanguage) { track.enabled = true; } else { track.enabled = false; } }); The language is in standard (RFC 5646) format. For US English, this would be "en-US", for example. Example This example returns an array of track kinds and labels for potential use in a user interface to select audio tracks for a specified media element. The list is filtered to only allow certain track kinds through. function getTrackList(el) { ...
AudioWorkletGlobalScope.registerProcessor - Web APIs
n't return an array of AudioParamDescriptor-based objects. Examples In this example we create a custom AudioWorkletNode that outputs silence. First, we need to define a custom AudioWorkletProcessor and register it. Note that this should be done in a separate file. // test-processor.js class TestProcessor extends AudioWorkletProcessor { process (inputs, outputs, parameters) { return true } } registerProcessor('test-processor', TestProcessor) Next, in our main script file we'll load the processor, create an instance of AudioWorkletNode -- passing it the processor name that we used when calling registerProcessor -- and connect it to an audio graph. const audioContext = new AudioContext() await audioContext.audioWorklet.addModule('test-processor.js') const node = new AudioWork...
AudioWorkletGlobalScope - Web APIs
{ constructor () { super() // current sample-frame and time at the moment of instantiation // to see values change, you can put these two lines in process method console.log(currentFrame) console.log(currentTime) } // the process method is required - simply output silence, // which the outputs are already filled with process (inputs, outputs, parameters) { return true } } // the sample rate is not going to change ever, // because it's a read-only property of a BaseAudioContext // and is set only during its instantiation console.log(sampleRate) // you can declare any variables and use them in your processors // for example it may be an ArrayBuffer with a wavetable const usefulVariable = 42 console.log(usefulVariable) registerProcessor('test-processor', Tes...
AudioWorkletNode.parameters - Web APIs
h.random() * 2 - 1) * (parameters['customGain'].length > 1 ? parameters['customGain'][i] : parameters['customGain'][0]) // note: a parameter contains an array of 128 values (one value for each of 128 samples), // however it may contain a single value which is to be used for all 128 samples // if no automation is scheduled for the moment. } }) return true } } registerProcessor('white-noise-processor', WhiteNoiseProcessor) Next, in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing it the name of the processor, and connect the node to an audio graph. const audioContext = new AudioContext() await audioContext.audioWorklet.addModule('white-noise-processor.js') const whiteNoiseNode = new AudioWorkletNo...
AudioWorkletNode.port - Web APIs
define a custom AudioWorkletProcessor, and register it. Note that that this should be done in a separate file. // ping-pong-processor.js class PingPongProcessor extends AudioWorkletProcessor { constructor (...args) { super(...args) this.port.onmessage = (e) => { console.log(e.data) this.port.postMessage('pong') } } process (inputs, outputs, parameters) { return true } } registerProcessor('ping-pong-processor', PingPongProcessor) Now in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing the name of the processor, and connect the node to an audio graph. const audioContext = new AudioContext() await audioContext.audioWorklet.addModule('ping-pong-processor.js') const pingPongNode = new AudioWorkletNode(audioConte...
AudioWorkletNode - Web APIs
ill output white noise, and register it. Note that this should be done in a separate file. // white-noise-processor.js class WhiteNoiseProcessor extends AudioWorkletProcessor { process (inputs, outputs, parameters) { const output = outputs[0] output.forEach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = Math.random() * 2 - 1 } }) return true } } registerProcessor('white-noise-processor', WhiteNoiseProcessor) Next, in our main script file we'll load the processor, create an instance of AudioWorkletNode passing it the name of the processor, and connect the node to an audio graph. const audioContext = new AudioContext() await audioContext.audioWorklet.addModule('white-noise-processor.js') const whiteNoiseNode = new AudioWorkletNod...
AudioWorkletProcessor() - Web APIs
ctor. First, we need to define a custom AudioWorkletProcessor and register it. Note that this should be done in a separate file. // test-processor.js class TestProcessor extends AudioWorkletProcessor { constructor (options) { super() console.log(options.numberOfInputs) console.log(options.processorOptions.someUsefulVariable) } process (inputs, outputs, parameters) { return true } } registerProcessor('test-processor', TestProcessor) Next, in our main script file we'll load the processor, create an instance of AudioWorkletNode passing it the name of the processor and options object. In the options object we pass processorOptions with a Map instance under someUsefulVariable key. We don't pass numberOfInputs and see how it gets its default value. const audioContext =...
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
h.random() * 2 - 1) * (parameters['customGain'].length > 1 ? parameters['customGain'][i] : parameters['customGain'][0]) // note: a parameter contains an array of 128 values (one value for each of 128 samples), // however it may contain a single value which is to be used for all 128 samples // if no automation is scheduled for the moment. } }) return true } } registerProcessor('white-noise-processor', WhiteNoiseProcessor) Next, in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing it the name of the processor, and connect the node to an audio graph. const audioContext = new AudioContext() await audioContext.audioWorklet.addModule('white-noise-processor.js') const whiteNoiseNode = new AudioWorkletNo...
AudioWorkletProcessor.port - Web APIs
define a custom AudioWorkletProcessor, and register it. Note that that this should be done in a separate file. // ping-pong-processor.js class PingPongProcessor extends AudioWorkletProcessor { constructor (...args) { super(...args) this.port.onmessage = (e) => { console.log(e.data) this.port.postMessage('pong') } } process (inputs, outputs, parameters) { return true } } registerProcessor('ping-pong-processor', PingPongProcessor) Now in our main scripts file we'll load the processor, create an instance of AudioWorkletNode passing the name of the processor, and connect the node to an audio graph. const audioContext = new AudioContext() await audioContext.audioWorklet.addModule('ping-pong-processor.js') const pingPongNode = new AudioWorkletNode(audioConte...
AudioWorkletProcessor - Web APIs
ill output white noise, and register it. Note that this should be done in a separate file. // white-noise-processor.js class WhiteNoiseProcessor extends AudioWorkletProcessor { process (inputs, outputs, parameters) { const output = outputs[0] output.forEach(channel => { for (let i = 0; i < channel.length; i++) { channel[i] = Math.random() * 2 - 1 } }) return true } } registerProcessor('white-noise-processor', WhiteNoiseProcessor) Next, in our main script file we'll load the processor, create an instance of AudioWorkletNode, passing it the name of the processor, then connect the node to an audio graph. const audioContext = new AudioContext() await audioContext.audioWorklet.addModule('white-noise-processor.js') const whiteNoiseNode = new AudioWorkletN...
BaseAudioContext.createConvolver() - Web APIs
For applied examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var convolver = audioCtx.createConvolver(); ... ...
BaseAudioContext.createDelay() - Web APIs
ll be introduced, so the looping sounds don't start playing for a short amount of time. var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext(); var synthDelay = audioCtx.createDelay(5.0); ... var synthSource; playSynth.onclick = function() { synthSource = audioCtx.createBufferSource(); synthSource.buffer = buffers[2]; synthSource.loop = true; synthSource.start(); synthSource.connect(synthDelay); synthDelay.connect(destination); this.setAttribute('disabled', 'disabled'); } stopSynth.onclick = function() { synthSource.disconnect(synthDelay); synthDelay.disconnect(destination); synthSource.stop(); playSynth.removeAttribute('disabled'); } ... var delay1; rangeSynth.oninput = function() { delay1 = rangeSynth.value; ...
BaseAudioContext.createDynamicsCompressor() - Web APIs
eAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML = 'Add compression'; source.disconnect(compressor); compressor.disconnect(audioCtx.destination); source.connect(...
BaseAudioContext.createGain() - Web APIs
mute.onclick = voiceMut...
BaseAudioContext.createScriptProcessor() - Web APIs
new AudioContext(); source = audioCtx.createBufferSource(); // Create a ScriptProcessorNode with a bufferSize of 4096 and a single input and output channel var scriptNode = audioCtx.createScriptProcessor(4096, 1, 1); console.log(scriptNode.bufferSize); // load in an audio track via XHR and decodeAudioData function getData() { request = new XMLHttpRequest(); request.open('GET', 'viper.ogg', true); request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { myBuffer = buffer; source.buffer = myBuffer; }, function(e){"Error with decoding audio data" + e.err}); } request.send(); } // Give the node a function to process audio events scriptNode.onaudioprocess = f...
BatteryManager.charging - Web APIs
Otherwise, the value is false. ...
Using the Beacon API - Web APIs
or an overview. Navigator.sendBeacon() The Beacon API's Navigator.sendBeacon() method sends a beacon request to the server in the global browsing context. The method takes two arguments: the URL and the data to send. The data argument is optional and its type may be an ArrayBufferView, Blob, DOMString, or FormData. If the browser successfully queues the request for delivery, the method returns true and returns false otherwise. The following example specifies a handler for the load and beforeunload events. The handler calls sendBeacon() with the current URL. window.onload = window.onunload = function analytics(event) { if (!navigator.sendBeacon) return; var url = "https://example.com/analytics"; // Create the data to send var data = "state=" + event.type + "&location=" + location.
BeforeInstallPromptEvent.prompt() - Web APIs
The prompt() method of the BeforeInstallPromptEvent interface allows a developer to show the install prompt at a time of their own choosing. Syntax BeforeInstallPromptEvent.prompt() Parameters None. Returns An empty Promise. Example var isTooSoon = true; window.addEventListener("beforeinstallprompt", function(e) { if (isTooSoon) { e.preventDefault(); // Prevents prompt display // Prompt later instead: setTimeout(function() { isTooSoon = false; e.prompt(); // Throws if called more than once or default not prevented }, 10000); } // The event was re-dispatched in response to our request // ... }); ...
Bluetooth.requestDevice() - Web APIs
y of BluetoothServiceUUIDs, a name parameter, and a namePrefix parameter. optionalServices[]: An array of BluetoothServiceUUIDs. acceptAllDevices: A Boolean indicating that the requesting script can accept all Bluetooth devices. The default is false. Exceptions TypeError The provided options do not makes sense. For example, options.filters is present and options.acceptAllDevices is true, or if options.filters is not present and options.acceptAllDevices is false. Or options.filters is []. NotFoundError There is no Bluetooth device that matches the specified options. SecurityError This operation is not permitted in this context due to security concerns. For example, it is called from insecure origin. Example // Discovery options match any devices advertising: // . The stand...
BluetoothCharacteristicProperties.authenticatedSignedWrites - Web APIs
Syntax var aBoolean = BluetoothCharacteristicProperties.authenticatedSignedWrites; Value A Boolean. ...
BluetoothCharacteristicProperties.broadcast - Web APIs
Syntax var aBoolean = BluetoothCharacteristicProperties.broadcast; Value A Boolean. ...
BluetoothCharacteristicProperties.indicate - Web APIs
Syntax var aBoolean = BluetoothCharacteristicProperties.indicate; Value A Boolean. ...
BluetoothCharacteristicProperties.notify - Web APIs
Syntax var aBoolean = BluetoothCharacteristicProperties.notify; Value A Boolean. ...
BluetoothCharacteristicProperties.read - Web APIs
Syntax var aBoolean = BluetoothCharacteristicProperties.read; Value A Boolean. ...
BluetoothCharacteristicProperties.reliableWrite - Web APIs
The reliableWrite read-only property of the BluetoothCharacteristicProperties interface returns a boolean that is true if reliable writes to the characteristic is permitted. Syntax var aBoolean = BluetoothCharacteristicProperties.reliableWrite; Value A Boolean Specifications Specification Status Comment Web BluetoothThe definition of 'reliableWrite' in that specification. Draft Initial definition. ...
BluetoothCharacteristicProperties.writableAuxiliaries - Web APIs
Syntax var aBoolean = BluetoothCharacteristicProperties.writableAuxiliaries; Value A Boolean. ...
BluetoothCharacteristicProperties.write - Web APIs
Syntax var aBoolean = BluetoothCharacteristicProperties.write; Value A Boolean. ...
BluetoothCharacteristicProperties.writeWithoutResponse - Web APIs
Syntax var aBoolean = BluetoothCharacteristicProperties.writeWithoutResponse; Value A Boolean. ...
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. BluetoothRemoteGATTServer.deviceRead only A reference to the BluetoothDevice running the server. Methods BluetoothRemoteGATTServer.connect() Causes the script execution environment to connect to this.device. BluetoothRemoteGATTServer.disconnect() Causes the...
Body.bodyUsed - Web APIs
Web › API › Body › bodyUsed
he Request() constructor, then use it to fetch a JPG. When the fetch is successful, we read a Blob out of the response using blob(), put it into an object URL using URL.createObjectURL, and then set that URL as the source of an <img> element to display the image. Notice that we log response.bodyUsed to the console once before the response.blob() call and once after. This returns false before and true afterwards, as at that point the body has been read. HTML Content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> JS Content var myImage = document.querySelector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg').then(function(response) { console.log(response.bodyUsed); var res = response.blob(); console...
CSS.registerProperty() - Web APIs
CSS.registerProperty(PropertyDefinition); Parameters A PropertyDefinition dictionary object, which can contain the following members: name A DOMString indicating the name of the property being defined. syntax Optional A DOMString representing the expected syntax of the defined property. Defaults to "*". inherits A boolean value defining whether the defined property should be inherited (true), or not (false). Defaults to false. initialValue Optional A DOMString representing the initial value of the defined property. Return value undefined. Exceptions InvalidModificationError The given name has already been registered. SyntaxError The given name isn't a valid custom property name (starts with two dashes, e.g. --foo). TypeError The required name and/or inherits diction...
CSSNumericValue - Web APIs
supplied number to the CSSNumericValue. CSSNumericValue.sub Subtracts a supplied number from the CSSNumericValue. CSSNumericValue.mul Multiplies the CSSNumericValue by the supplied value. CSSNumericValue.div Divides the CSSNumericValue by the supplied value. CSSNumericValue.min Returns the minimum value passed CSSNumericValue.max Returns the maximum value passed CSSNumericValue.equals True if all the values are the exact same type and value, in the same order. Otherwise, false. CSSNumericValue.to Converts value into another one with the specified unit. CSSNumericValue.toSum TBD CSSNumericValue.type TBD CSSNumericValue.parse Allows a CSSNumericValue to be constructed directly from a string containing CSS. Specifications Specification Status Comment ...
CSSPseudoElement.element - Web APIs
representing the pseudo-element's originating element. ...
CSSPseudoElement.type - Web APIs
Working Draft Initial definition. ...
CSS Painting API - Web APIs
paintWorklet addModule() method, then include the image we created using the CSS paint() function. ...
CSS Typed Object Model API - Web APIs
cValue. CSSNumericValue.sub - Subtracts supplied numbers to the CSSNumericValue. CSSNumericValue.mul - Multiplies supplied numbers to the CSSNumericValue. CSSNumericValue.div - Divides a supplied number by other numbers, throwing an error if 0. CSSNumericValue.min - Returns the minimum value passed CSSNumericValue.max - Returns the maximum value passed CSSNumericValue.equals - Returns true if all the values are the exact same type and value, in the same order. Otherwise, false CSSNumericValue.to - Converts value into another one with the specified unit. CSSNumericValue.toSum CSSNumericValue.type CSSNumericValue.parse - Returns a number parsed from a CSS string CSSPositionValue Represents values for properties that take a position, for example object-position. CSSTran...
Cache - Web APIs
Web › API › Cache
ch(), then using put() to add the results to the cache. Cache.addAll(requests) Takes an array of URLs, retrieves them, and adds the resulting response objects to the given cache. Cache.put(request, response) Takes both a request and its response and adds it to the given cache. Cache.delete(request, options) Finds the Cache entry whose key is the request, returning a Promise that resolves to true if a matching Cache entry is found and deleted. If no Cache entry is found, the promise resolves to false. Cache.keys(request, options) Returns a Promise that resolves to an array of Cache keys. Examples This code snippet is from the service worker selective caching sample. (see selective caching live) The code uses CacheStorage.open() to open any Cache objects with a Content-Type header tha...
CacheStorage.delete() - Web APIs
The delete() method of the CacheStorage interface finds the Cache object matching the cacheName, and if found, deletes the Cache object and returns a Promise that resolves to true. If no Cache object is found, it resolves to false. You can access CacheStorage through the global caches property. Syntax caches.delete(cacheName).then(function(boolean) { // your cache is now deleted }); Parameters cacheName The name of the cache you want to delete. Return value a Promise that resolves to true if the Cache object is found and deleted, and false otherwise. Examples In this code snippet we wait for an activate event, and then run a waitUntil() block that clears up any old, unused caches before a new service worker is activated. Here we have an array of cache names we want to keep (ca...
CacheStorage - Web APIs
by returning an array of cache names from CacheStorage.keys(), opening each cache with CacheStorage.open(), and matching the one you want with Cache.match(). Methods CacheStorage.match() Checks if a given Request is a key in any of the Cache objects that the CacheStorage object tracks, and returns a Promise that resolves to that match. CacheStorage.has() Returns a Promise that resolves to true if a Cache object matching the cacheName exists. CacheStorage.open() Returns a Promise that resolves to the Cache object matching the cacheName (a new cache is created if it doesn't already exist.) CacheStorage.delete() Finds the Cache object matching the cacheName, and if found, deletes the Cache object and returns a Promise that resolves to true. If no Cache object is found, it resolves to ...
CanvasRenderingContext2D.arc() - Web APIs
kwise). Parameters x The horizontal coordinate of the arc's center. y The vertical coordinate of the arc's center. radius The arc's radius. Must be positive. startAngle The angle at which the arc starts in radians, measured from the positive x-axis. endAngle The angle at which the arc ends in radians, measured from the positive x-axis. anticlockwise Optional An optional Boolean. If true, draws the arc counter-clockwise between the start and end angles. The default is false (clockwise). Examples Drawing a full circle This example draws a complete circle with the arc() method. HTML <canvas></canvas> JavaScript The arc is given an x-coordinate of 100, a y-coordinate of 75, and a radius of 50. To make a full circle, the arc begins at an angle of 0 radians (0?), and ends at ...
CanvasRenderingContext2D.drawImage() - Web APIs
on canvas. This allows scaling of the drawn image. If not specified, the image is not scaled in height when drawn. Exceptions thrown INDEX_SIZE_ERR If the canvas or source rectangle width or height is zero. INVALID_STATE_ERR The image has no image data. TYPE_MISMATCH_ERR The specified source element isn't supported. NS_ERROR_NOT_AVAILABLE The image is not loaded yet. Use .complete === true and .onload to determine when it is ready. Examples Drawing an image to the canvas This example draws an image to the canvas using the drawImage() method. HTML <canvas id="canvas"></canvas> <div style="display:none;"> <img id="source" src="https://udn.realityripple.com/samples/db/f374e9c6fc.jpg" width="300" height="227"> </div> JavaScript The source image is taken from th...
CanvasRenderingContext2D.globalAlpha - Web APIs
Living Standard ...
CanvasRenderingContext2D.imageSmoothingQuality - Web APIs
Syntax ctx.imageSmoothingQuality = "low" || "medium" || "high" Options Possible values: "low" Low quality. "medium" Medium quality. "high" High quality. Example Setting image smoothing quality This example uses the imageSmoothingQuality property with a scaled image. ...
CanvasRenderingContext2D.isPointInPath() - Web APIs
check, unaffected by the current transformation of the context. fillRule The algorithm by which to determine if a point is inside or outside the path. Possible values: "nonzero": The non-zero winding rule. Default rule. "evenodd": The even-odd winding rule. path A Path2D path to check against. If unspecified, the current path is used. Return value Boolean A Boolean, which is true if the specified point is contained in the current or specified path, otherwise false. Examples Checking a point in the current path This example uses the isPointInPath() method to check if a point is within the current path. HTML <canvas id="canvas"></canvas> <p>In path: <code id="result">false</code></p> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.ge...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
hether or not the specified point is inside the area contained by the stroking of a path. Syntax ctx.isPointInStroke(x, y); ctx.isPointInStroke(path, x, y); Parameters x The x-axis coordinate of the point to check. y The y-axis coordinate of the point to check. path A Path2D path to check against. If unspecified, the current path is used. Return value Boolean A Boolean, which is true if the point is inside the area contained by the stroking of a path, otherwise false. Examples Checking a point in the current path This example uses the isPointInStroke() method to check if a point is within the area of the current path's stroke. HTML <canvas id="canvas"></canvas> <p>In stroke: <code id="result">false</code></p> JavaScript const canvas = document.getElementById('canvas'...
CanvasRenderingContext2D.strokeStyle - Web APIs
Living Standard ...
CanvasRenderingContext2D - Web APIs
() and CanvasRenderingContext2D.setLineDash() instead. CanvasRenderingContext2D.webkitLineDashOffset Use CanvasRenderingContext2D.lineDashOffset instead. CanvasRenderingContext2D.webkitImageSmoothingEnabled Use CanvasRenderingContext2D.imageSmoothingEnabled instead. Blink only CanvasRenderingContext2D.isContextLost() Inspired by the same WebGLRenderingContext method it returns true if the Canvas context has been lost, or false if not. WebKit only CanvasRenderingContext2D.webkitBackingStorePixelRatio The backing store size in relation to the canvas element. See High DPI Canvas. CanvasRenderingContext2D.webkitGetImageDataHD Intended for HD backing stores, but removed from canvas specifications. CanvasRenderingContext2D.webkitPutImageDataHD Intended for H...
Manipulating video using canvas - Web APIs
Canvas c1 is used to display t...
Basic animations - Web APIs
ctx.lineWidth = 10; ctx.beginPath(); ctx.moveTo(-28, 0); ctx.lineTo(112, 0); ctx.stroke(); ctx.restore(); // Write seconds ctx.save(); ctx.rotate(sec * Math.PI / 30); ctx.strokeStyle = '#D40000'; ctx.fillStyle = '#D40000'; ctx.lineWidth = 6; ctx.beginPath(); ctx.moveTo(-30, 0); ctx.lineTo(83, 0); ctx.stroke(); ctx.beginPath(); ctx.arc(0, 0, 10, 0, Math.PI * 2, true); ctx.fill(); ctx.beginPath(); ctx.arc(95, 0, 10, 0, Math.PI * 2, true); ctx.stroke(); ctx.fillStyle = 'rgba(0, 0, 0, 0)'; ctx.arc(0, 0, 3, 0, Math.PI * 2, true); ctx.fill(); ctx.restore(); ctx.beginPath(); ctx.lineWidth = 14; ctx.strokeStyle = '#325FA2'; ctx.arc(0, 0, 142, 0, Math.PI * 2, true); ctx.stroke(); ctx.restore(); window.requestAnimationFrame(clock); } ...
Compositing and clipping - Web APIs
rds, no clipping occurs. A clip example In this example, we'll use a circular clipping path to restrict the drawing of a set of random stars to a particular region. ...
Using images - Web APIs
rame ctx.drawImage(document.getElementById('frame'), 0, 0); } } } Controlling image scaling behavior As mentioned previously, scaling images can result in fuzzy or blocky artifacts due to the scaling process. You can use the drawing context's imageSmoothingEnabled property to control the use of image smoothing algorithms when scaling images within your context. By default, this is true, meaning images will be smoothed when scaled. You can disable this feature like this: ctx.mozImageSmoothingEnabled = false; ctx.webkitImageSmoothingEnabled = false; ctx.msImageSmoothingEnabled = false; ctx.imageSmoothingEnabled = false; << PreviousNext >> ...
Clients.matchAll() - Web APIs
Web › API › Clients › matchAll
options are not included, the method returns only the service worker clients controlled by the service worker. Syntax self.clients.matchAll(options).then(function(clients) { // do something with your clients list }); Parameters options Optional An options object allowing you to set options for the matching operation. Available options are: includeUncontrolled: A Boolean -- if set to true, the matching operation will return all service worker clients who share the same origin as the current service worker. Otherwise, it returns only the service worker clients controlled by the current service worker. The default is false. type: Sets the type of clients you want matched. Available values are "window", "worker", "sharedworker", and "all". The default is "all". Return value ...
Clients.openWindow() - Web APIs
if (!hadWindowToFocus) clients.openWindow(e.notification.data.url).then(windowClient => windowClient ? windowClient.focus() : null); })); }); Specifications Specification Status Comment Service WorkersThe definition of 'Clients: openWindow' in that specification. Working Draft In...
Clients - Web APIs
Web › API › Clients
Clients.claim() Allows an active service worker to set itself as the controller for all clients within its scope. Examples The following example shows an existing chat window or creates a new one when the user clicks a notification. ...
console.assert() - Web APIs
Web › API › Console › assert
Note: This feature is available in Web Workers. Syntax console.assert(assertion, obj1 [, obj2, ..., objN]); console.assert(assertion, msg [, subst1, ..., substN]); // C-like message formatting Parameters assertion Any boolean expression. If the assertion is false, the message is written to the console. obj1 ... objN A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output. msg A JavaScript string containing zero or more substitution strings. ...
ConstrainBoolean - Web APIs
applied. Properties exact A Boolean which indicates a value the property must have. ideal A Boolean value indicating the ideal, but not required, value the property should ideally have. If possible, this value will be used, but the user agent will use the other value if it needs to in order to come up with a workable configuration. 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. Specifications Specification Status Comment Media Capture and StreamsThe definition of 'ConstrainBoolean' in that specification. Candidate Recommendation Initial definition Technically, ConstrainBoo...
ConvolverNode.buffer - Web APIs
convolver = audioCtx.createConvolver(); convolver.buffer = myAudioBuffer; Value An AudioBuffer. Example var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var convolver = audioCtx.createConvolver(); ... ...
CryptoKey - Web APIs
Web › API › CryptoKey
: "secret": This key is a secret key for use with a symmetric algorithm. "private": This key is the private half of an asymmetric algorithm's CryptoKeyPair. "public": This key is the public half of an asymmetric algorithm's CryptoKeyPair. CryptoKey.extractable Boolean indicating whether or not the key may be extracted using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey(). true: The key may be extracted. false The key may not be extracted. exportKey() or wrapKey() will throw an exception if used to extract this key. CryptoKey.algorithm An object describing the algorithm for which this key can be used and any associated extra parameters. AesKeyGenParams if the algorithm is any of the AES variants. RsaHashedKeyGenParams if the algorithm is any of the RSA ...
CustomElementRegistry.get() - Web APIs
or undefined if there is no custom element definition with that name. Examples customElements.define('my-paragraph', class extends HTMLElement { constructor() { super(); let template = document.getElementById('my-paragraph'); let templateContent = template.content; const shadowRoot = this.attachShadow({mode: 'open'}) .appendChild(templateContent.cloneNode(true)); } }) // Return a reference to the my-paragraph constructor let ctor = customElements.get('my-paragraph'); Specifications Specification Status Comment HTML Living StandardThe definition of 'customElements.get()' in that specification. Living Standard Initial definition. ...
CustomEvent() - Web APIs
dictionary. Return value A new CustomEvent object of the specified type, with any other properties configured according to the CustomEventInit dictionary (if one was provided). Example // add an appropriate event listener obj.addEventListener("cat", function(e) { process(e.detail) }); // create and dispatch the event var event = new CustomEvent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchEvent(event); Additional examples can be found at Creating and triggering events. Specifications Specification Status Comment DOMThe definition of 'CustomEvent()' in that specification. Living Standard Initial definition. ...
CustomEvent.detail - Web APIs
itializing the event. Note: This feature is available in Web Workers. Syntax let myDetail = customEventInstance.detail; Return value Whatever data the event was initialized with. Example // add an appropriate event listener obj.addEventListener("cat", function(e) { process(e.detail) }); // create and dispatch the event let event = new CustomEvent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchEvent(event); // Will return an object contaning the hazcheeseburger property let myDetail = event.detail; Specifications Specification Status Comment DOMThe definition of 'detail' in that specification. Living Standard Initial definition. ...
CustomEvent - Web APIs
Constructor CustomEvent() Creates a CustomEvent. Properties CustomEvent.detail Read only Any data passed when initializing the event. This interface inherits properties from its parent, Event: Event.bubbles Read only A boolean indicating whether or not the event bubbles up through the DOM. Event.cancelBubble A historical alias to Event.stopPropagation(). Setting its value to true before returning from an event handler prevents propagation of the event. Event.cancelable Read only A boolean indicating whether the event is cancelable. Event.composed Read only A boolean indicating whether or not the event can bubble across the boundary between the shadow DOM and the regular DOM. Event.currentTarget Read only A reference to the currently registered target for the even...
DOMImplementation.createHTMLDocument() - Web APIs
Line 4 uses createHTMLDocument() to construct a new HTML document whose <title> is "New Document". Lines 5 and 6 create a new paragraph element with some simple content, and then lines 8-12 handle inserting the new paragraph in...
DOMImplementation - Web APIs
turns an XMLDocument. DOMImplementation.createDocumentType() Creates and returns a DocumentType. DOMImplementation.createHTMLDocument() Creates and returns an HTML Document. DOMImplementation.hasFeature() Returns a Boolean indicating if a given feature is supported or not. This function is unreliable and kept for compatibility purpose alone: except for SVG-related queries, it always returns true. Old browsers are very inconsistent in their behavior. Specifications Specification Status Comment DOMThe definition of 'DOMImplementation' in that specification. Living Standard Removed the getFeature() method. Added the createHTMLDocument() method. Modified the return type of createDocument() from Document to XMLDocument. Document Object Model (...
DOMMatrix - Web APIs
Web › API › DOMMatrix
sion of the DOMMatrixReadOnly interface. This interface should be available inside web workers, though some implementations don't allow it yet. Constructor DOMMatrix() Creates and returns a new DOMMatrix object. Properties This interface inherits properties from DOMMatrixReadOnly, though some of these properties are altered to be mutable. is2D Read only A Boolean flag whose value is true if the matrix was initialized as a 2D matrix. If false, the matrix is 3D. isIdentity Read only A Boolean whose value is true if the matrix is the identity matrix. The identity matrix is one in which every value is 0 except those on the main diagonal from top-left to bottom-right corner (in other words, where the offsets in each direction are equal). m11, m12, m13, m14, m21, m22, m23, m24, m31...
DOMMatrixReadOnly - Web APIs
e--which is based upon DOMMatrixReadOnly--adds mutability, allowing you to alter the matrix after creating it. A 4x4 matrix is suitable to describe any rotation and translation in 3D. This interface should be available inside web workers, though some implementations doesn't allow it yet. Properties This interface doesn't inherit any properties. is2D Read only A Boolean flag whose value is true if the matrix was initialized as a 2D matrix. If false, the matrix is 3D. isIdentity Read only A Boolean whose value is true if the matrix is the identity matrix. The identity matrix is one in which every value is 0 except those on the main diagonal from top-left to bottom-right corner (in other words, where the offsets in each direction are equal). m11, m12, m13, m14, m21, m22, m23, m24, m31...
DataTransfer.dropEffect - Web APIs
e An item is moved to a new location. link A link is established to the source at the new location. none The item may not be dropped. Assigning any other value to dropEffect has no effect and the old value is retained. Example This example shows the use of the dropEffect and effectAllowed properties. HTML Content <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element. </p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div> CSS Content div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } JavaScript Content function ...
DataTransfer.effectAllowed - Web APIs
Living Standa...
DataTransfer.getData() - Web APIs
availability The HTML5 Drag and Drop Specification dictates a drag data store mode. This may result in unexpected behavior, being DataTransfer.getData() not returning an expected value. Example This example shows the use of the DataTransfer object's getData() and setData() methods. ...
DataTransfer.items - Web APIs
d + " ; type = " + ev.dataTransfer.items[i].type); } } } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } </script> <body> <h1>Examples of <code>DataTransfer</code>.{<code>types</code>, <code>items</code>} properties</h1> <ul> <li id="i1" ondragstart="dragstart_handler(event);" draggable="true">Drag Item 1 to the Drop Zone</li> <li id="i2" ondragstart="dragstart_handler(event);" draggable="true">Drag Item 2 to the Drop Zone</li> </ul> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div> </body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'items' in that specific...
DataTransfer.setData() - Web APIs
Living Standard ...
DataTransfer.setDragImage() - Web APIs
Living Stand...
DataTransfer.types - Web APIs
d + " ; type = " + ev.dataTransfer.items[i].type); } } } function dragover_handler(ev) { console.log("dragOver"); ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } </script> <body> <h1>Examples of <code>DataTransfer</code>.{<code>types</code>, <code>items</code>} properties</h1> <ul> <li id="i1" ondragstart="dragstart_handler(event);" draggable="true">Drag Item 1 to the Drop Zone</li> <li id="i2" ondragstart="dragstart_handler(event);" draggable="true">Drag Item 2 to the Drop Zone</li> </ul> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div> </body> </html> Specifications Specification Status Comment HTML Living StandardThe definition of 'types' in that specific...
DataTransfer - Web APIs
r's state. This is primarily used to control the cursor during tab drags. DataTransfer.mozSourceNode Read only The Node over which the mouse cursor was located when the button was pressed to initiate the drag operation. This value is null for external drags or if the caller can't access the node. DataTransfer.mozUserCancelled Read only This property applies only to the dragend event, and is true if the user canceled the drag operation by pressing escape. 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. Deprecated properties DataTransfer.mozItemCount Read only Gives the number of items in the drag operation. Removed in Firefox 71. Methods Standard methods DataTransfer.clearData() Re...
DataTransferItemList.DataTransferItem() - Web APIs
) { console.log("dragOver"); ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } function dragend_handler(ev) { console.log("dragEnd"); var dataList = ev.dataTransfer.items; // Clear any remaining drag data dataList.clear(); } HTML <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div> CSS div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } Result Drag and Drop demo link Spec...
DataTransferItemList.add() - Web APIs
), null is returned. Exceptions NotSupportedError A string data parameter was provided, and the list already contains an item whose kind is "Plain Unicode string" and whose type is equal to the specified type parameter. Example This example shows the use of the add() method. ...
DataTransferItemList.clear() - Web APIs
art event. While handling drop, the drag data store is in read-only mode, and this method silently does nothing. No exception is thrown. Syntax DataTransferItemList.clear(); Parameters None. Return value undefined Example This example shows the use of the clear() method. ...
DataTransferItemList.length - Web APIs
) { console.log("dragOver"); ev.preventDefault(); // Set the dropEffect to move ev.dataTransfer.dropEffect = "move" } function dragend_handler(ev) { console.log("dragEnd"); var dataList = ev.dataTransfer.items; // Clear any remaining drag data dataList.clear(); } HTML <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div> CSS div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } Result Drag and Drop demo link Spec...
DataTransferItemList.remove() - Web APIs
{ console.log("dragEnd"); var dataList = ev.dataTransfer.items; for (var i = 0; i < dataList.length; i++) { dataList.remove(i); } // Clear any remaining drag data dataList.clear(); } HTML <h1>Example uses of <code>DataTransferItemList</code> methods and property</h1> <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div> CSS div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } Specifications...
DelayNode.delayTime - Web APIs
ll be introduced, so the looping sounds don't start playing for a short amount of time. var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext(); var synthDelay = audioCtx.createDelay(5.0); ... var synthSource; playSynth.onclick = function() { synthSource = audioCtx.createBufferSource(); synthSource.buffer = buffers[2]; synthSource.loop = true; synthSource.start(); synthSource.connect(synthDelay); synthDelay.connect(destination); this.setAttribute('disabled', 'disabled'); } stopSynth.onclick = function() { synthSource.disconnect(synthDelay); synthDelay.disconnect(destination); synthSource.stop(); playSynth.removeAttribute('disabled'); } ... var delay1; rangeSynth.oninput = function() { delay1 = rangeSynth.value; ...
DelayNode - Web APIs
Web › API › DelayNode
ll be introduced, so the looping sounds don't start playing for a short amount of time. var AudioContext = window.AudioContext || window.webkitAudioContext; var audioCtx = new AudioContext(); var synthDelay = audioCtx.createDelay(5.0); ... var synthSource; playSynth.onclick = function() { synthSource = audioCtx.createBufferSource(); synthSource.buffer = buffers[2]; synthSource.loop = true; synthSource.start(); synthSource.connect(synthDelay); synthDelay.connect(destination); this.setAttribute('disabled', 'disabled'); } stopSynth.onclick = function() { synthSource.disconnect(synthDelay); synthDelay.disconnect(destination); synthSource.stop(); playSynth.removeAttribute('disabled'); } ... var delay1; rangeSynth.oninput = function() { delay1 = rangeSynth.value; ...
DeprecationReportBody - Web APIs
e deprecated feature was used, if known, or null otherwise. columnNumber A number representing the column in the source file in which the deprecated feature was used, if known, or null otherwise. ...
DeviceOrientationEvent.DeviceOrientationEvent() - Web APIs
options Optional Options are as follows: alpha: A number representing the motion of the device around the z axis, express in degrees with values ranging from 0 to 360. ...
DeviceOrientationEvent.absolute - Web APIs
Indicates whether or not the device is providing orientation data absolutely (that is, in reference to the Earth's coordinate frame) or using some arbitrary frame determined by the device. See Orientation and motion data explained for details. 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. Specifications Specification Status Comment DeviceOrientation Event Specification Editor's Draft Initial specification. ...
DisplayMediaStreamConstraints - Web APIs
n, this value simply indicates whether or not to include an audio track in the MediaStream returned by getDisplayMedia(). If a MediaTrackConstraints object is provided here, an audio track is included in the stream, but the audio is processed to match the specified constraints after being retrieved from the hardware but before being added to the MediaStream. The default value is false. video If true (the default), the display contents are included in a MediaStreamTrack within the stream provided by getDisplayMedia(). Optionally, a MediaTrackConstraints object may be given, providing options specifying processing to be performed on the video data before adding it to the stream. A value of false is not permitted, and results in a TypeError being thrown. Specifications Specification...
Document: DOMContentLoaded event - Web APIs
-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } JS const log = document.querySelector('.event-log-contents'); const reload = document.querySelector('#reload'); reload.addEventListener('click', () => { log.textContent =''; window.setTimeout(() => { window.location.reload(true); }, 200); }); window.addEventListener('load', (event) => { log.textContent = log.textContent + 'load\n'; }); document.addEventListener('readystatechange', (event) => { log.textContent = log.textContent + `readystate: ${document.readyState}\n`; }); document.addEventListener('DOMContentLoaded', (event) => { log.textContent = log.textContent + `DOMContentLoaded\n`; }); Result ...
Document.cookie - Web APIs
Web › API › Document › cookie
()">Show cookie value</button> Example #3: Do something only once In order to use the following code, please replace all occurrences of the word doSomethingOnlyOnce (the name of the cookie) with a custom name. ...
Document.createEvent() - Web APIs
document.createEvent(type); event is the created Event object. type is a string that represents the type of event to be created. Possible event types include "UIEvents", "MouseEvents", "MutationEvents", and "HTMLEvents". See Notes section for details. Example // Create the event. var event = document.createEvent('Event'); // Define that the event name is 'build'. event.initEvent('build', true, true); // Listen for the event. elem.addEventListener('build', function (e) { // e.target matches elem }, false); // Target can be any Element or other EventTarget. elem.dispatchEvent(event); Notes Event type strings suitable for passing to createEvent() are listed in the DOM standard -- see the table in step 2. Bear in mind that most event objects now have constructors, which are the ...
Document.createProcessingInstruction() - Web APIs
cessingInstruction node. target is a string containing the first part of the processing instruction (i.e., <?target ... ?>) data is a string containing any information the processing instruction should carry, after the target. The data is up to you, but it can't contain ?>, since that closes the processing instruction. Exceptions DOM_INVALID_CHARACTER Throws if either of the following are true: The processing instruction target is invalid -- it should be a valid XML name that doesn't contain "xml", "XML", or any case combination of the two, other than standardized ones such as <?xml-stylesheet ?>. The closing processing instruction sequence (?>) is part of the data. Example var doc = new DOMParser().parseFromString('<foo />', 'application/xml'); var pi = doc.createProcessi...
Document: drag event - Web APIs
iseconds as an element or text selection is being dragged by the user. Bubbles Yes Cancelable Yes Default action Continue the drag & drop operation. Interface DragEvent Event handler property ondrag Examples See this code in a JSFiddle demo or interact with it below. ...
Document.fonts - Web APIs
Web › API › Document › fonts
To change preferences in Firefox, visit about:config.IE No support NoOpera Full support 47Safari Full support 10WebView Android Full support 60Chrome Android Full support 6...
Document.fullscreenEnabled - Web APIs
at has no windowed plug-ins in any of its documents, and if all <iframe> elements which contain the document have their allowfullscreen attribute set. Although this property is read-only, it will not throw if it is modified (even in strict mode); the setter is a no-operation and it will be ignored. Syntax var isFullscreenAvailable = document.fullscreenEnabled; Value A Boolean value which is true if the document and the elements within can be placed into full-screen mode by calling Element.requestFullscreen(). If full-screen mode isn't available, this value is false. Example In this example, before attempting to request full-screen mode for a <video> element, the value of fullscreenEnabled is checked, in order to avoid making the attempt when not available. function requestFullScreen()...
Document.hasFocus() - Web APIs
Web › API › Document › hasFocus
lement in a document has focus. When viewing a document, an element with focus is always the active element in the document, but an active element does not necessarily have focus. For example, an active element within a popup window that is not the foreground doesn't have focus. Syntax var focused = document.hasFocus(); Return value false if the active element in the document has no focus; true if the active element in the document has focus. Example This example checks whether the document has focus every 300 milliseconds. To test the functionality of hasFocus(), click on the button to open a new window, and try switching between the two pages. HTML <p id="log">Awaiting focus check.</p> <button onclick="openWindow()">Open a new window</button> JavaScript function checkPageFocus()...
Document.head - Web APIs
Web › API › Document › head
ument interface returns the <head> element of the current document. Syntax var objRef = document.head; Value An HTMLHeadElement. Example <!doctype html> <head id="my-document-head"> <title>Example: using document.head</title> </head> <script> var theHead = document.head; console.log(theHead.id); // "my-document-head"; console.log( theHead === document.querySelector("head") ); // true </script> Notes document.head is read-only. Trying to assign a value to this property will fail silently or, in Strict Mode, throws a TypeError . Specifications Specification Status Comment HTML 5.1The definition of 'Document.head' in that specification. Recommendation HTML5The definition of 'Document.head' in that specification. Recommendation...
Document.implementation - Web APIs
The Document.implementation property returns a DOMImplementation object associated with the current document. Syntax DOMImpObj = document.implementation; Example var modName = "HTML"; var modVer = "2.0"; var conformTest = document.implementation.hasFeature( modName, modVer ); alert( "DOM " + modName + " " + modVer + " supported?: " + conformTest ); // alerts with: "DOM HTML 2.0 supported?: true" if DOM Level 2 HTML module is supported. A list of module names (e.g., Core, HTML, XML, etc.) is available in the DOM Level 2 Conformance Section. Notes The W3C's DOM Level 1 Recommendation only specified the hasFeature method, which is one way to determine if a DOM module is supported by a browser (see example above and What does your user agent claim to support?). If available, other DOMIm...
Document.mozSyntheticDocument - Web APIs
The Document.mozSyntheticDocument property indicates whether or not the document is a synthetic one; that is, a document representing a standalone image, video, audio, or the like. Syntax var isSynthetic = document.mozSyntheticDocument; On return, isSynthetic is true if the document is a synthetic one; otherwise it's false. Example This can be useful if you have a contextual menu item you only want to display for synthetic documents (or, conversely, for documents that aren't synthetic). var isSynthetic = document.mozSyntheticDocument; if (isSynthetic) { /* insert your menu item here */ } Specifications Not part of any specification. ...
Document.onafterscriptexecute - Web APIs
dynamically, such as with appendChild(). ...
Document.onbeforescriptexecute - Web APIs
added dynamically, eg with appendChild(). ...
Document.ononline - Web APIs
Web › API › Document › ononline
The Document.online event is fired on the <body> of each page when the browser switches between online and offline mode. Additionally, the events bubble up from document.body, to document, ending at window. Both events are non-cancellable (you can't prevent the user from coming online, or going offline). window.navigator.onLine returns boolean true if the browser is online and false if it is definitely offline (disconnected from the network). The online and offline events are fired when the value of this attribute changes. It is important to note that this event and attribute are inherently unreliable. A computer can be connected to a network without having Internet access. You can register listeners for these events in a few familiar ways: Using addEventListener on the window, docume...
Document.open() - Web APIs
Web › API › Document › open
ing wrappedJSObject. See Security check basics for more about principals. Three-argument document.open() There is a lesser-known and little-used three-argument version of document.open() , which is an alias of Window.open() (see its page for full details). This call, for example opens github.com in a new window, with its opener set to null: document.open('https://www.github.com','', 'noopener=true') Two-argument document.open() Browsers used to support a two-argument document.open(), with the following signature: document.open(type, replace) Where type specified the MIME type of the data you are writing (e.g. text/html) and replace if set (i.e. a string of "replace") specified that the history entry for the new document would replace the current history entry of the document being writ...
Document.queryCommandEnabled() - Web APIs
The Document.queryCommandEnabled() method reports whether or not the specified editor command is enabled by the browser. Syntax isEnabled = document.queryCommandEnabled(command); Parameters command The command for which to determine support. Return value Returns a Boolean which is true if the command is enabled and false if the command isn't. Notes For 'cut' and 'copy' commands the method only returns true when called from a user-initiated thread. The 'paste' command return false not only if the feature is unavailable, but also if the script calling it has insufficient privileges to perform the action. Example var flg = document.queryCommandEnabled("SelectAll"); if(flg) { document.execCommand("SelectAll", false, null); // command is enabled, run it } Specificatio...
Document.queryCommandSupported() - Web APIs
The Document.queryCommandSupported() method reports whether or not the specified editor command is supported by the browser. Syntax isSupported = document.queryCommandSupported(command); Parameters command The command for which to determine support. Return value Returns a Boolean which is true if the command is supported and false if the command isn't. Notes The 'paste' command return false not only if the feature is unavailable, but also if the script calling it has insufficient privileges to perform the action [1] Example var flg = document.queryCommandSupported("SelectAll"); if(flg) { // ...Do something } Specifications Specification Status Comment execCommand ...
Document: readystatechange event - Web APIs
-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } JS const log = document.querySelector('.event-log-contents'); const reload = document.querySelector('#reload'); reload.addEventListener('click', () => { log.textContent =''; window.setTimeout(() => { window.location.reload(true); }, 200); }); window.addEventListener('load', (event) => { log.textContent = log.textContent + 'load\n'; }); document.addEventListener('readystatechange', (event) => { log.textContent = log.textContent + `readystate: ${document.readyState}\n`; }); document.addEventListener('DOMContentLoaded', (event) => { log.textContent = log.textContent + `DOMContentLoaded\n`; }); Result ...
Document: scroll event - Web APIs
Specifications Specification Status CSS Object Model (CSSOM) View Module Working Draft ...
DocumentOrShadowRoot.fullscreenElement - Web APIs
full-screen mode; if full-screen mode isn't currently in use by the document>, the returned value is null. Example This example presents a function, isVideoInFullscreen(), which looks at the value returned by fullscreenElement; if the document is in full-screen mode (fullscreenElement isn't null) and the full-screen element's nodeName is VIDEO, indicating a <video> element, the function returns true, indicating that the video is in full-screen mode. function isVideoInFullscreen() { if (document.fullscreenElement && document.fullscreenElement.nodeName == 'VIDEO') { return true; } return false; } Specifications Specification Status Comment Fullscreen APIThe definition of 'Document.fullscreenElement' in that specification. Living Standard Initial d...
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
" LF \u000A * "\r" CR \u000D * " " SPC \u0020 * * This does not use Javascript's "\s" because that includes non-breaking * spaces (and also some other characters). */ /** * Determine whether a node's text content is entirely whitespace. * * @param nod A node implementing the |CharacterData| interface (i.e., * a |Text|, |Comment|, or |CDATASection| node * @return True if all of the text content of |nod| is whitespace, * otherwise false. */ function is_all_ws( nod ) { // Use ECMA-262 Edition 3 String and RegExp features return !(/[^\t\n\r ]/.test(nod.textContent)); } /** * Determine if a node should be ignored by the iterator functions. * * @param nod An object implementing the DOM1 |Node| interface. * @return true if the node is: ...
DynamicsCompressorNode.attack - Web APIs
eAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML = 'Add compression'; source.disconnect(compressor); compressor.disconnect(audioCtx.destination); source.connect(...
DynamicsCompressorNode.knee - Web APIs
eAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML = 'Add compression'; source.disconnect(compressor); compressor.disconnect(audioCtx.destination); source.connect(...
DynamicsCompressorNode.ratio - Web APIs
eAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML = 'Add compression'; source.disconnect(compressor); compressor.disconnect(audioCtx.destination); source.connect(...
DynamicsCompressorNode.release - Web APIs
eAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML = 'Add compression'; source.disconnect(compressor); compressor.disconnect(audioCtx.destination); source.connect(...
DynamicsCompressorNode.threshold - Web APIs
eAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML = 'Add compression'; source.disconnect(compressor); compressor.disconnect(audioCtx.destination); source.connect(...
DynamicsCompressorNode - Web APIs
eAtTime(12, audioCtx.currentTime); compressor.attack.setValueAtTime(0, audioCtx.currentTime); compressor.release.setValueAtTime(0.25, audioCtx.currentTime); // connect the AudioBufferSourceNode to the destination source.connect(audioCtx.destination); button.onclick = function() { var active = button.getAttribute('data-active'); if(active == 'false') { button.setAttribute('data-active', 'true'); button.innerHTML = 'Remove compression'; source.disconnect(audioCtx.destination); source.connect(compressor); compressor.connect(audioCtx.destination); } else if(active == 'true') { button.setAttribute('data-active', 'false'); button.innerHTML = 'Add compression'; source.disconnect(compressor); compressor.disconnect(audioCtx.destination); source.connect(...
EXT_disjoint_timer_query - Web APIs
s available. ext.TIME_ELAPSED_EXT Elapsed time (in nanoseconds). ext.TIMESTAMP_EXT The current time. ext.GPU_DISJOINT_EXT A GLboolean indicating whether or not the GPU performed any disjoint operation. Methods This extension exposes eight new methods. ext.createQueryEXT() Creates a new WebGLQuery. ext.deleteQueryEXT() Deletes a given WebGLQuery. ext.isQueryEXT() Returns true if a given object is a WebGLQuery. ext.beginQueryEXT() The timer starts when all commands prior to beginQueryEXT have been fully executed. ext.endQueryEXT() The timer stops when all commands prior to endQueryEXT have been fully executed. ext.queryCounterEXT() Records the current time into the corresponding query object. ext.getQueryEXT() Returns information about a query target. ex...
Element.attachShadow() - Web APIs
When a non-focusable part of the shadow DOM is clicked, the first focusable part is given focus, and the shadow host is given any available :focus styling. Return value Returns a ShadowRoot object. Exceptions Exception Explanation InvalidStateError The element you are trying to attac...
Element.getBoundingClientRect() - Web APIs
ce from the relevant edge of the viewport to that side of the element, in each case. Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'Element.getBoundingClientRect()' in that specification. Working Draft Initial definition Notes The returned DOMRect object can be modified in modern browsers. This was not true with older versions which effectively returned DOMRectReadOnly. With IE and Edge, not being able to add missing properties to their returned ClientRect, object prevents backfilling x and y. Due to compatibility problems (see below), it is safest to rely on only properties left, top, right, and bottom. Properties in the returned DOMRect object are not own properties. While the in operator and fo...
Element.getElementsByClassName() - Web APIs
meaning that it always reflects the current state of the DOM tree rooted at the element on which the function was called. As new elements that match names are added to the subtree, they immediately appear in the collection. Similarly, if an existing element that doesn't match names has its set of classes adjusted so that it matches, it immediately appears in the collection. The opposite is also true; as elements no longer match the set of names, they are immediately removed from the collection. In quirks mode, the class names are compared in a case-insensitive fashion. Otherwise, they're case sensitive. Examples Matching a single class To look for elements that include among their classes a single specified class, we just provide that class name when calling getElementsByClassName(): ...
Element.hasAttribute() - Web APIs
name is a string representing the name of the attribute. ...
Element.hasAttributeNS() - Web APIs
namespace is a string specifying the namespace of the attribute. localName is the name of the attribute. ...
Element.hasAttributes() - Web APIs
The hasAttributes() method of the Element interface returns a Boolean indicating whether the current element has any attributes or not. Syntax var result = element.hasAttributes(); Return value result holds the return value true or false. Examples let foo = document.getElementById('foo'); if (foo.hasAttributes()) { // Do something with 'foo.attributes' } Polyfill ;(function(prototype) { prototype.hasAttributes = prototype.hasAttributes || function() { return (this.attributes.length > 0); } })(Element.prototype); Specifications Specification Status Comment DOMThe definition of 'Element.hasAttributes()' in that specification. Living Standard Moved from the Node interface to the more specialized Element interface. Document Obje...
Element.hasPointerCapture() - Web APIs
The hasPointerCapture() method of the Element interface sets whether the element on which it is invoked has pointer capture for the pointer identified by the given pointer ID. Syntax targetElement.hasPointerCapture(pointerId); Parameters pointerId The pointerId of a PointerEvent object. Return value A Boolean value -- true if the element does have pointer capture, false if it doesn't. Examples <html> <script> function downHandler(ev) { const el = document.getElementById("target"); // Element 'target' will receive/capture further events el.setPointerCapture(ev.pointerId); /* ... */ // Check whether element still has pointer capture let pointerCap = el.hasPointerCapture(ev.pointerId); if(pointerCap) { // We've still got point...
Element.scrollHeight - Web APIs
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. padding-bottom Left Top Right Bottom margin-top margin-bottom border-top border-bottom Problems and solutions Determine if an element has been totally scrolled The following equivalence returns true if an element is at the end of its scroll, false if it isn't. element.scrollHeight - element.scrollTop === element.clientHeight When the container does not scroll, but has overflowing children, these checks determine if the container can scroll: window.getComputedStyle(element).overflowY === 'visible' window.getComputedStyle(element).overflowY !== 'hidden' scrollHeight Demo Associated with...
Element.scrollIntoView() - Web APIs
Corresponds to scrollIntoViewOptions: {block: "start", inline: "nearest"}. This is the default value. If false, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "end", inline: "nearest"}. scrollIntoVi...
Element: scroll event - Web APIs
Specifications Specification Status CSS Object Model (CSSOM) View Module Working Draft ...
Element.setAttributeNode() - Web APIs
ent. replacedAttr is the replaced attribute node, if any, returned by this function. Example This example copies the align attribute from one element to another. HTML <div id="one" align="left">one</div> <div id="two">two</div> JavaScript let d1 = document.getElementById('one'); let d2 = document.getElementById('two'); let a = d1.getAttributeNode('align'); d2.setAttributeNode(a.cloneNode(true)); // Returns: 'left' alert(d2.attributes[1].value); Notes If the attribute named already exists on the element, that attribute is replaced with the new one and the replaced one is returned. This method is seldom used, with Element.setAttribute() usually being used to change element's attributes. DOM methods dealing with element's attributes: Not namespace-aware, most commonly used metho...
Element.setAttributeNodeNS() - Web APIs
n Attr node. Example // <div id="one" xmlns:myNS="http://www.mozilla.org/ns/specialspace" // myNS:special-align="utterleft">one</div> // <div id="two">two</div> var myns = "http://www.mozilla.org/ns/specialspace"; var d1 = document.getElementById("one"); var d2 = document.getElementById("two"); var a = d1.getAttributeNodeNS(myns, "special-align"); d2.setAttributeNodeNS(a.cloneNode(true)); alert(d2.attributes[1].value) // returns: `utterleft' Notes If the specified attribute already exists on the element, then that attribute is replaced with the new one and the replaced one is returned. Note that if you try to set without cloning the node, Mozilla gives an NS_ERROR_DOM_INUSE_ATTRIBUTE_ERR "Attribute already in use" error, as the DOM requires cloning for Attr to be reused (un...
Element.setCapture() - Web APIs
is method during the handling of a mousedown event to retarget all mouse events to this element until the mouse button is released or document.releaseCapture() is called. Warning: This interface never had much cross-browser support and you probably looking for element.setPointerCapture instead, from the Pointer Events API. 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. Example In this example, the current mouse coordinates are drawn while you mouse around after clicking and holding down on an element. <html> <head> <title>Mouse Capture Example</title> <style type="text/css"> #myButton { border: solid black 1px; color: black; ...
Element.tabStop - Web APIs
Web › API › Element › tabStop
dd tab functionality for Custom Elements. While with the existing tabIndex property, it is required to specify an order for the element to become tabbable. The tabStop property would decouple the tabbable property from the tab index. After feedback, this property was removed from the design doc and replaced by ShadowRoot.delegatesFocus. Syntax var isTabStop = element.tabStop; element.tabStop = (true|false); Example // TBD ...
Event() - Web APIs
Web › API › Event › Event
false. cancelable Optional A Boolean indicating whether the event can be cancelled. The default is false. composed Optional A Boolean indicating whether the event will trigger listeners outside of a shadow root (see Event.composed for more details). 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. Living Standard Initial definition ...
Event.bubbles - Web APIs
Web › API › Event › bubbles
The bubbles read-only property of the Event interface indicates whether the event bubbles up through the DOM or not. Note: See Event bubbling and capture for more information on bubbling. Syntax var doesItBubble = event.bubbles; Value A Boolean, which is true if the event bubbles up through the DOM. Example function handleInput(e) { // Checks whether the event bubbles and ... if (!e.bubbles) { // ... passes the event along if does not passItOn(e); } // Already bubbling doOutput(e); } Note: Only certain events can bubble. Events that do bubble have this property set to true. You can use this property to check if an event is allowed to bubble or not. Specifications Specification Status Comment DOMThe definition of 'Event.bubbles' in ...
Event.cancelBubble - Web APIs
The cancelBubble property of the Event interface is a historical alias to Event.stopPropagation(). Setting its value to true before returning from an event handler prevents propagation of the event. In later implementations, setting this to false does nothing. See Browser compatibility for details. Syntax event.cancelBubble = bool; var bool = event.cancelBubble; Value A Boolean. Example elem.onclick = function(event) { // Do cool things here event.cancelBubble = true; } Specifications Specification Status Comment DOMThe definition of 'cancelBubble' in that specification. Living Standard ...
Event.cancelable - Web APIs
Web › API › Event › cancelable
result from the user interacting with the page. Canceling the click, scroll, or beforeunload events would prevent the user from clicking on something, scrolling the page, or navigating away from the page, respectively. Custom events created by other JavaScript code control if they can be canceled when they are created. Syntax bool = event.cancelable; Value The result is a Boolean, which is true if the event can be canceled. Example For example, browser vendors are proposing that the wheel event can only be canceled the first time the listener is called -- any following wheel events cannot be canceled. function preventScrollWheel(event) { if (typeof event.cancelable !== 'boolean' || event.cancelable) { // The event can be canceled, so we do so. event.preventDefault(); } el...
Event.composedPath() - Web APIs
shadow text="I have a closed shadow root"></closed-shadow> Then include a click event listener on the <html> element: document.querySelector('html').addEventListener('click',function(e) { console.log(e.composed); console.log(e.composedPath()); }); When you click on the <open-shadow> element and then the <closed-shadow> element, you'll notice two things. First, the composed property returns true beause the click event is always able to propagate across shadow boundaries. Second, you'll notice a difference in the value of composedPath for the two elements. The <open-shadow> element's composed path is this: Array [ p, ShadowRoot, open-shadow, body, html, HTMLDocument https://mdn.github.io/web-components-examples/composed-composed-path/, Window ] Whereas the <closed-shadow> element's comp...
Event.defaultPrevented - Web APIs
The defaultPrevented read-only property of the Event interface returns a Boolean indicating whether or not the call to Event.preventDefault() canceled the event. Note: You should use this instead of the non-standard, deprecated getPreventDefault() method (see bug 691151). 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. Example This example logs attempts to visit links from two <a> elements. JavaScript is used to prevent the second link from working. HTML <p><a id="link1" href="#link1">Visit link 1</a></p> <p><a id="link2" href="#link2">Try to visit link 2</a> (you can't)</p> <p id="log"></p> JavaScript function stopLink(event) { event.preventDefaul...
Event.initEvent() - Web APIs
Web › API › Event › initEvent
he event chain or not. Once set, the read-only property Event.bubbles will give its value. cancelable Is a Boolean defining whether the event can be canceled. Once set, the read-only property Event.cancelable will give its value. Example // Create the event. 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. Living Standard From Document Object Model (DOM) Level 2 Events Specification, deprecated it, superseded by eve...
Event.isTrusted - Web APIs
Web › API › Event › isTrusted
Syntax var eventIsTrusted = event.isTrusted; Value Boolean Example if (e.isTrusted) { /* The event is trusted */ } else { /* The event is not trusted */ } Specification Specification Status Comment DOMThe definition of 'Event.isTrusted' in that specification. Living Standard Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'Trusted events' in that specification. ...
Event.preventDefault() - Web APIs
ts default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once. As noted below, calling preventDefault() for a non-cancelable event, such as one dispatched via EventTarget.dispatchEvent(), without specifying cancelable: true has no effect. Syntax event.preventDefault(); Examples Blocking default click handling Toggling a checkbox is the default action of clicking on a checkbox. This example demonstrates how to prevent that from happening: JavaScript document.querySelector("#id-checkbox").addEventListener("click", function(event) { document.getElementById("output-box").innerHTML += "Sorry! <code>preve...
Event.returnValue - Web APIs
Web › API › Event › returnValue
The Event property returnValue indicates whether the default action for this event has been prevented or not. It is set to true by default, allowing the default action to occur. Setting this property to false prevents the default action. Note: While returnValue has been adopted into the DOM standard, it is present primarily to support existing code. You should use preventDefault(), and defaultPrevented instead of this historical property. Syntax event.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. The value returned by returnValue is the opposite of the value returned by defaultPrevented. Usage notes returnValue...
Event - Web APIs
Web › API › Event
nt TimeEvent TouchEvent TrackEvent TransitionEvent UIEvent UserProximityEvent WebGLContextEvent WheelEvent Constructor Event() Creates an Event object, returning it to the caller. Properties Event.bubbles Read only A boolean indicating whether or not the event bubbles up through the DOM. Event.cancelBubble A historical alias to Event.stopPropagation(). Setting its value to true before returning from an event handler prevents propagation of the event. Event.cancelable Read only A boolean indicating whether the event is cancelable. Event.composed Read only A boolean indicating whether or not the event can bubble across the boundary between the shadow DOM and the regular DOM. Event.currentTarget Read only A reference to the currently registered target for the even...
EventSource.withCredentials - Web APIs
The withCredentials read-only property of the EventSource interface returns a Boolean indicating whether the EventSource object was instantiated with CORS credentials set. 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). Examples var evtSource = new EventSource('sse.php'); console.log(evtSource.withCredentials); Note: You can find a full example on GitHub -- see Simple SSE demo using PHP. Specifications Specification Status Comment HTML Living StandardThe definition of 'withCredentials' in that specification. Living Standard Initial definition ...
EventSource - Web APIs
parent, EventTarget. EventSource.readyState Read only A number representing the state of the connection. Possible values are CONNECTING (0), OPEN (1), or CLOSED (2). EventSource.url Read only A DOMString representing the URL of the source. 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). Event handlers EventSource.onerror Is an EventHandler called when an error occurs and the error event is dispatched on an EventSource object. EventSource.onmessage Is an EventHandler called when a message event is received, that is when a message is coming from the source. EventSource.onopen Is an EventHandler called when an open event is received, that is...
EventTarget.dispatchEvent() - Web APIs
dispatchEvent(). Syntax cancelled = !target.dispatchEvent(event) Parameter event is the Event object to be dispatched. target is used to initialize the Event.target and determine which event listeners to invoke. Return Value The return value is false if event is cancelable and at least one of the event handlers which received event called Event.preventDefault(). Otherwise it returns true. The dispatchEvent() method throws UNSPECIFIED_EVENT_TYPE_ERR if the event's type was not specified by initializing the event before the method was called, or if the event's type is null or an empty string. Exceptions Exceptions thrown by event handlers are reported as uncaught exceptions. The event handlers run on a nested callstack; they block the caller until they complete, but exceptions ...
EventTarget - Web APIs
Living Standard No change. Document Object Model (DOM) Level 3 Events Sp...
FeaturePolicy.allowsFeature() - Web APIs
The allowsFeature() method of the FeaturePolicy interface enables introspection of individual directives of the Feature Policy it is run on. It returns a Boolean that is true if and only if the specified feature is allowed in the specified context (or the default context if no context is specified). Syntax const allowed = FeaturePolicy.allowsFeature(<feature>) or const allowed = FeaturePolicy.allowsFeature(<feature>, <origin>) Parameters Feature name A specific feature name must be specified. Origin name Optional An origin URL to check the feature on. If it is omitted the default origin is used. Return value A Boolean that is true if and only if the feature is allowed. Example The following example queries whether or not the document is allowed to use camera API by the...
FetchEvent() - Web APIs
presents. This is always fetch for Fetch events. init Optional An object conforming to the FetchEventInit dictionary, containing options to apply to the event object. Options are as follows: clientId Read only The Client that the current service worker is controlling. isReload Read only A Boolean that signifies whether the page was reloaded or not when the event was dispatched. true if yes, and false if not. Typically, pressing the refresh button in a browser is a reload, while clicking a link and pressing the back button is not. If not present, it defaults to false. preloadResponse Read only A Promise which returns a previously-loaded response to the client. replacesClientId Read only A DOMString which identifies the client which is being replaced by resultingClie...
FetchEvent.isReload - Web APIs
Pressing the refresh button is a reload while clicking a link and pressing the back button is not. Syntax var reloaded = FetchEvent.isReload Value A Boolean. ...
Using files from web applications - Web APIs
} }; fd.append('myFile', file); // Initiate a multipart/form-data upload xhr.send(fd); } window.onload = function() { const d...
FileException - Web APIs
of using WebWorkers with this API makes debugging even more challenging. To simplify things a bit, wrap your worker code in a try/catch. When errors occur, forward them to the main app using postMessage() as in the following: function onError(e) { postMEssage('ERROR:' + e.toString()); } try { //Error is thrown if "log.txt" already exists. var fileEntry = fs.root.getFile('log.txt', {create: true, exclusive:true}0; } catch (e) { onErrror(e); } The sample code was borrowed from HTML5Rocks Attribute Attribute Type Description code unsigned short The most appropriate error code for the condition. Constants Note: Do not rely on the numeric values of the constants, which might change as the specifications continue to change. Use the constant name...
FileList - Web APIs
Web › API › FileList
ype="file"> element. It's also used for a list of files dropped into web content when using the drag and drop API; see the DataTransfer object for details on this usage. Note: Prior to Gecko 1.9.2, the input element only supported a single file being selected at a time, meaning that the FileList would contain only one file. Starting with Gecko 1.9.2, if the input element's multiple attribute is true, the FileList may contain multiple files. Using the file list All <input> element nodes have a files attribute of type FileList on them which allows access to the items in this list. For example, if the HTML includes the following file input: <input id="fileItem" type="file"> The following line of code fetches the first file in the node's file list as a File object: var file = document.get...
FileSystemEntry.fullPath - Web APIs
"/" prepended to it to make it absolute. Syntax var fullPath = FileSystemEntry.fullPath; Value A USVString indicating the entry's full path. Example This example shows a function which is called with a file system; it then gets a FileSystemFileEntry for a file named data.json and returns its full path. function gotFileSystem(fs) { let path = ""; fs.root.getFile("data.json", { create: true, exclusive: true }, function(entry) { path = fullPath; }, handleError(error)); return path; } Obviously, this is somewhat contrived, since we know that the file's full path is "/data.json", having just looked it up ourselves, but the concept holds up for scenarios in which you don't know it. Specifications Specification Status Comment File and Directory En...
FileSystemEntry.isDirectory - Web APIs
You can also use isFile to determine if the entry is a file. You should not assume that any entry which isn't a directory is a file or vice-versa. There are other types of file descriptors on many operating systems. Be sure to use both isDirectory and isFile as needed to ensure that the entry is something you know how to work with. Syntax var isDirectory = FileSystemEntry.isDirectory; Value A Boolean indicating whether or not the FileSystemEntry is a directory. ...
FileSystemEntry.isFile - Web APIs
You can also use isDirectory to determine if the entry is a directory. You should not assume that any entry which isn't a file is a directory or vice-versa. There are other types of file descriptors on many operating systems. Be sure to use both isDirectory and isFile as needed to ensure that the entry is something you know how to work with. Syntax var isFile = FileSystemEntry.isFile; Value A Boolean indicating whether or not the FileSystemEntry is a file. ...
FileSystemEntry.name - Web APIs
e read-only name property of the FileSystemEntry interface returns a USVString specifying the entry's name; this is the entry within its parent directory (the last component of the path as indicated by the fullPath property). Syntax var name = FileSystemEntry.name; Value A USVString indicating the entry's name. Example This example shows a function called isFileWithExtension() which returns true if the specified FileSystemEntry is both a file and the file's name ends with a given extension. function isFileWithExtension(entry, extension) { return (entry.isFile && entry.name.endsWith("." + extension)); } Specifications Specification Status Comment File and Directory Entries APIThe definition of 'name' in that specification. Draft Initial specification...
FileSystemEntry - Web APIs
lowing properties. filesystem Read only A FileSystem object representing the file system in which the entry is located. fullPath Read only A USVString object which provides the full, absolute path from the file system's root to the entry; it can also be thought of as a path which is relative to the root directory, prepended with a "/" character. isDirectory Read only A Boolean which is true if the entry represents a directory; otherwise, it's false. isFile Read only A Boolean which is true if the entry represents a file. If it's not a file, this value is false. name Read only A USVString containing the name of the entry (the final part of the path, after the last "/" character). Methods This interface defines the following methods. copyTo() Copies the file or directory ...
FileSystemEntrySync - Web APIs
rent(); Attributes Attribute Type Description filesystem readonly FileSystemSync The file system where the entry resides. fullpath readonly DOMString The full absolute path from the root to the entry. An absolute path is a relative path from the root directory, prepended with a '/'. isDirectory readonly boolean True if FileSystemEntrySync is a directory. isFile readonly boolean True if the FileSystemEntrySync is a file. name readonly DOMString The name of the entry, excluding the path leading to it. Methods getMetadata() Look up metadata about this entry. [ todo: specify what kind of metadata ] Metadata getMetada () raises (FileException); Parameter None Return...
FileSystemFileEntry - Web APIs
following code creates an empty file called "log.txt" (if it doesn't exist) and fills it with the text "Meow". Inside the success callback, event handlers are set up to handle the error error and writeend events. The text data is written to the file by creating a blob, appending text to it, and passing the blob to FileWriter.write(). function onInitFs(fs) { fs.root.getFile('log.txt', {create: true}, function(fileEntry) { // Create a FileWriter object for our FileSystemFileEntry (log.txt). fileEntry.createWriter(function(fileWriter) { fileWriter.onwriteend = function(e) { console.log('Write completed.'); }; fileWriter.onerror = function(e) { console.log('Write failed: ' + e.toString()); }; // Create a new Blob and write it to log.txt.
File and Directory Entries API - Web APIs
the FileSystemEntry for a dropped item. If the result isn't null, then it's a dropped file or directory, and you can use file system calls to work with it. The HTMLInputElement.webkitEntries property lets you access the FileSystemFileEntry objects for the currently selected files, but only if they are dragged-and-dropped onto the file chooser (bug 1326031). If HTMLInputElement.webkitdirectory is true, the <input> element is instead a directory picker, and you get FileSystemDirectoryEntry objects for each selected directory. Asynchronous API The asynchronous API should be used for most operations, to prevent file system accesses from blocking the entire browser if used on the main thread. It includes the following interfaces: FileSystem Represents a file system. FileSystemEntry The ba...
FontFaceSet.check() - Web APIs
Web › API › FontFaceSet › check
The check() method of the FontFaceSet returns whether all fonts in the given font list have been loaded and are available. Syntax bool = aFontFaceSet.check(font); bool = aFontFaceSet.check(font, text); Returns A Boolean that is true if the font list is available Parameters font: a font specification using the CSS value syntax, e.g. "italic bold 16px Roboto" text: limit the font faces to those whose Unicode range contains at least one of the characters in text. This does not check for individual glyph coverage. Examples document.fonts.check("12px courier"); // returns true if the font courier is available at 12px document.fonts.check("12px MyFont", "ss"); // returns true if the font 'MyFont' has a ss character. Specifications Specification Status Comment ...
Using FormData Objects - Web APIs
tash the file!" /> </form> <div></div> Then you can send it using code like the following: var form = document.forms.namedItem("fileinfo"); form.addEventListener('submit', function(ev) { var oOutput = document.querySelector("div"), oData = new FormData(form); oData.append("CustomField", "This is some extra data"); var oReq = new XMLHttpRequest(); oReq.open("POST", "stash.php", true); oReq.onload = function(oEvent) { if (oReq.status == 200) { oOutput.innerHTML = "Uploaded!"; } else { oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>"; } }; oReq.send(oData); ev.preventDefault(); }, false); Note: If you pass in a reference to the form, the request method specified in the form will be used over th...
FormData.append() - Web APIs
Web › API › FormData › append
to the name): formData.append('userpic[]', myFileInput.files[0], 'chris1.jpg'); formData.append('userpic[]', myFileInput.files[1], 'chris2.jpg'); This technique makes it simpler to process multi-file uploads because the resultant data structure is more conducive to looping. If the sent value is different than String or Blob it will be automatically converted to String: formData.append('name', true); formData.append('name', 74); formData.append('name', 'John'); formData.getAll('name'); // ["true", "74", "John"] Specifications Specification Status Comment XMLHttpRequestThe definition of 'append()' in that specification. Living Standard Initial definition ...
FormData.has() - Web APIs
Web › API › FormData › has
oolean. 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. Living Standard ...
GainNode.gain - Web APIs
Web › API › GainNode › gain
mute.onclick = voiceMut...
GainNode - Web APIs
Web › API › GainNode
mute.onclick = voiceMut...
Gamepad.connected - Web APIs
Web › API › Gamepad › connected
Syntax readonly attribute boolean connected; Example var gp = navigator.getGamepads()[0]; console.log(gp.connected); Value A boolean. ...
GamepadButton.pressed - Web APIs
The GamepadButton.pressed property of the GamepadButton interface returns a boolean indicating whether the button is currently pressed (true) or unpressed (false). Syntax var isPressed = navigator.getGamepads()[0].pressed; Example var gp = navigator.getGamepads()[0]; // Get the first gamepad object if(gp.buttons[0].pressed == true) { // respond to button being pressed } Value A boolean. Specifications Specification Status Comment GamepadThe definition of 'GamepadButton.pressed' in that specification. Working Draft Initial definition ...
GamepadHapticActuator.pulse() - Web APIs
A double representing the intensity of the pulse. This can vary depending on the hardware type, but generally takes a value between 0.0 (no intensity) and 1.0 (full intensity). duration A double representing the duration of the pulse, in milliseconds. Note: Repeated calls to pulse() override the previous calls if they are still ongoing. Return value A promise that resolves with a value of true when the pulse has successfully completed. Examples TBC Specifications Specification Status Comment Gamepad ExtensionsThe definition of 'pulse()' in that specification. Editor's Draft Initial definition ...
GeolocationCoordinates - Web APIs
xpressed in meters. GeolocationCoordinates.altitudeAccuracy Read only Secure context Returns a double representing the accuracy of the altitude expressed in meters. This value can be null. GeolocationCoordinates.heading Read only Secure context Returns a double representing the direction towards which the device is facing. This value, specified in degrees, indicates how far off from heading true north the device is. 0 degrees represents true north, and the direction is determined clockwise (which means that east is 90 degrees and west is 270 degrees). If speed is 0, heading is NaN. If the device is unable to provide heading information, this value is null. GeolocationCoordinates.speed Read only Secure context Returns a double representing the velocity of the device in meters per secon...
Using the Geolocation API - Web APIs
l request fresh position data), and a timeout value that dictates how long the browser should attempt to get the position data for, before it times out. A call to watchPosition could look like: function success(position) { doSomething(position.coords.latitude, position.coords.longitude); } function error() { alert('Sorry, no position available.'); } const options = { enableHighAccuracy: true, maximumAge: 30000, timeout: 27000 }; const watchID = navigator.geolocation.watchPosition(success, error, options); Describing a position The user's location is described using a GeolocationPosition object instance, which itself contains a GeolocationCoordinates object instance. The GeolocationPosition instance contains only two things, a coords property that contains the GeolocationCoord...
GlobalEventHandlers.ondrag - Web APIs
Living Standard ...
GlobalEventHandlers.ondragend - Web APIs
Living Standard ...
GlobalEventHandlers.ondragenter - Web APIs
Living Standard...
GlobalEventHandlers.ondragexit - Web APIs
Living Standard...
GlobalEventHandlers.ondragleave - Web APIs
Living Standar...
GlobalEventHandlers.ondragover - Web APIs
Living Standard ...
GlobalEventHandlers.ondragstart - Web APIs
Living Standard...
GlobalEventHandlers.ondrop - Web APIs
Living Standard ...
HTMLAreaElement - Web APIs
ng a valid URL of a linked resource. HTMLAreaElement.hreflang Is a DOMString containing that reflects the hreflang HTML attribute, indicating the language of the linked resource. HTMLAreaElement.media Is a DOMString containing that reflects the media HTML attribute, indicating target media of the linked resource. HTMLAreaElement.noHref Is a Boolean flag indicating if the area is inactive (true) or active (false). HTMLHyperlinkElementUtils.password Is a USVString containing the password specified before the domain name. HTMLHyperlinkElementUtils.origin Read only Returns a USVString containing the origin of the URL, that is its scheme, its domain and its port. HTMLHyperlinkElementUtils.pathname Is a USVString containing the path name component, if any, of the referenced URL. HTML...
msAudioCategory - Web APIs
Yes Communications For streaming communication audio such as the following: VOIP Real time chat or other type of phone calls Should not be used in non-real-time or non-communication scenarios, such as audio and/or video playback, as playback startup latency is affected. *Note that if msAudioCategory is set to Communications, msRealtime is automatically set to true. Yes ForeGroundOnlyMedia Games or other sounds designed only to work in the foreground, but will mute existing background media sounds. Game audio needed for the game experience (dancing games, music games) Feature films (designed to pause when they go to the background) No GameEffects Game sound effects designed to mix with e...
HTMLButtonElement - Web APIs
sets the form. button: The button does nothing. menu: The button displays a menu. HTMLButtonElement.willValidate Read only Is a Boolean indicating whether the button is a candidate for constraint validation. 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. HTMLButtonElement.validationMessage Read only Is a DOMString representing the localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints. HTMLButtonElement.validity Read only Is a ValidityState r...
HTMLCollection - Web APIs
s. Currently HTMLCollections does not recognize purely numeric IDs, which would cause conflict with the array-style access, though HTML5 does permit these. For example, assuming there is one <form> element in the document and its id is myForm: var elem1, elem2; // document.forms is an HTMLCollection elem1 = document.forms[0]; elem2 = document.forms.item(0); alert(elem1 === elem2); // shows: "true" elem1 = document.forms.myForm; elem2 = document.forms.namedItem("myForm"); alert(elem1 === elem2); // shows: "true" elem1 = document.forms["named.item.with.periods"]; Specifications Specification Status Comment DOMThe definition of 'HTMLCollection' in that specification. Living Standard ...
HTMLElement.contentEditable - Web APIs
The contentEditable property of the HTMLElement interface specifies whether or not the element is editable. This enumerated attribute can have the following values: 'true' indicates that the element is contenteditable. 'false' indicates that the element cannot be edited. 'inherit' indicates that the element inherits its parent's editable status. You can use the HTMLElement.isContentEditable property to test the computed Boolean value of this property. Syntax editable = element.contentEditable element.contentEditable = 'true' Specifications Specification Status Comment HTML Living StandardThe definition of 'contenteditable' in that specification. Living Standard Initial definition ...
HTMLElement - Web APIs
nts those from DocumentAndElementEventHandlers, ElementCSSInlineStyle, GlobalEventHandlers, HTMLOrForeignElement and TouchEventHandlers. HTMLElement.accessKey Is a DOMString representing the access key assigned to the element. HTMLElement.accessKeyLabel Read only Returns a DOMString containing the element's assigned access key. HTMLElement.contentEditable Is a DOMString, where a value of true means the element is editable and a value of false means it isn't. HTMLElement.isContentEditable Read only Returns a Boolean that indicates whether or not the content of the element can be edited. HTMLElement.contextMenu Is a HTMLMenuElement representing the contextual menu associated with the element. It may be null. HTMLOrForeignElement.dataset Read only Returns a DOMStringMap with wh...
HTMLFieldSetElement - Web APIs
llValidate is false), or it satisfies its constraints. HTMLFieldSetElement.validity A ValidityState representing the validity states that this element is in. HTMLFieldSetElement.willValidate A Boolean false, because <fieldset> objects are never candidates for constraint validation. Methods Inherits methods from its parent, HTMLElement. HTMLFieldSetElement.checkValidity() Always returns true because <fieldset> objects are never candidates for constraint validation. HTMLFieldSetElement.reportValidity() Always returns true because <fieldset> objects are never candidates for constraint validation. HTMLFieldSetElement.setCustomValidity() Sets a custom validity message for the field set. If this message is not the empty string, then the field set is suffering from a custom validity er...
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. ...
HTMLIFrameElement.setNfcFocus() - Web APIs
The setNfcFocus() method of the HTMLIFrameElement interface sets whether an <iframe> can receive an NFC event. Syntax myIFrame.setNfcFocus(true); Returns Void. Parameters A Boolean indicating whether the <iframe> can receive an NFC event. Default is false; set to true to allow it to receive NFC events. Specifications Not part of any specification. ...
HTMLImageElement.isMap - Web APIs
The HTMLImageElement proeprty isMap is a Boolean value which indicates that the image is to be used by a server-side image map. This may only be used on images located within an <a> element. Note: For accessibility reasons, you should generally avoid using server-side image maps, as they require the use of a mouse. Use a client-side image map instead. 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. Usage notes When an image marked as being part of a server-side image map is clicked, the browser constructs the string "?x,y", where x and y indicate the coordinates at which the mouse was clicked as offsets from the top-left corner of...
HTMLImageElement - Web APIs
hen called without parameters, new Image() is equivalent to calling document.createElement("img"). Properties Inherits properties from its parent, HTMLElement. HTMLImageElement.alt A DOMString that reflects the alt HTML attribute, thus indicating the alternate fallback content to be displayed if the image has not been loaded. HTMLImageElement.complete Read only Returns a Boolean that is true if the browser has finished fetching the image, whether successful or not. That means this value is also true if the image has no src value indicating an image to load. HTMLImageElement.crossOrigin A DOMString specifying the CORS setting for this image element. See CORS settings attributes for further details. This may be null if CORS is not used. HTMLImageElement.currentSrc Read only Return...
HTMLInputElement.multiple - Web APIs
The HTMLInputElement.multiple property indicates if an input can have more than one value. Firefox currently only supports multiple for <input type="file">. ...
HTMLInputElement.webkitEntries - Web APIs
ment interface contains an array of file system entries (as objects based on FileSystemEntry) representing files and/or directories selected by the user using an <input> element of type file, but only if that selection was made using drag-and-drop: selecting a file in the dialog will leave the property empty (bug 1326031). The array can only contain directories if the webkitdirectory property is true. This means the <input> element was configured to let the user choose directories. This property is called webkitEntries in the specification due to its origins as a Google Chrome-specific API. It's likely to be renamed someday. Syntax var entries = HTMLInputElement.webkitEntries; Value An array of objects based on FileSystemEntry, each representing one file which is selected in the <input...
HTMLInputElement.webkitdirectory - Web APIs
rectory HTML attribute and indicates that the <input> element should let the user select directories instead of files. When a directory is selected, the directory and its entire hierarchy of contents are included in the set of selected items. The selected file system entries can be obtained using the webkitEntries property. 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. Understanding the results After the user makes a selection, each File object in files has its File.webkitRelativePath property set to the relative path within the selected directory at which the file is located. For example, consider this file system: PhotoAlbums Birthdays ...
HTMLKeygenElement - Web APIs
on (willValidate is false), or it satisfies its constraints. validity Read only Is a ValidityState representing the validity states that this element is in. willValidate Is a Boolean that is always false because keygen objects are never candidates for constraint validation. Methods Name & Arguments Return Description checkValidity() Boolean Always returns true because keygen objects are never candidates for constraint validation. setCustomValidity(in DOMString error) void Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. ...
HTMLMarqueeElement - Web APIs
the default value is -1, which means the marquee will scroll continuously. HTMLMarqueeElement.scrollAmount Sets the amount of scrolling at each interval in pixels. The default value is 6. HTMLMarqueeElement.scrollDelay Sets the interval between each scroll movement in milliseconds. The default value is 85. Note that any value smaller than 60 is ignored and the value 60 is used instead, unless trueSpeed is true. HTMLMarqueeElement.trueSpeed By default, scrollDelay values lower than 60 are ignored. If trueSpeed is true, then those values are not ignored. HTMLMarqueeElement.vspace Sets the vertical margin. HTMLMarqueeElement.width Sets the width in pixels or percentage value. Event handlers HTMLMarqueeElement.onbounce Fires when the marquee has reached the end of its scroll positi...
HTMLMediaElement.controls - Web APIs
The HTMLMediaElement.controls property reflects the controls HTML attribute, which controls whether user interface controls for playing the media item will be displayed. Syntax var ctrls = video.controls; audio.controls = true; Value A Boolean. A value of true means controls will be displayed. Example var obj = document.createElement('video'); obj.controls = true; Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.controls' in that specification. Living Standard No change from HTML5 HTML5The definition of 'HTMLMediaElement.controls' in that specification. Recommendation Initial definition. ...
HTMLMediaElement.defaultMuted - Web APIs
The HTMLMediaElement.defaultMuted property reflects the muted HTML attribute, which indicates whether the media element's audio output should be muted by default. This property has no dynamic effect. To mute and unmute the audio output, use the muted property. Syntax var dMuted = video.defaultMuted; audio.defaultMuted = true; Value A Boolean. A value of true means that the audio output will be muted by default. Example var videoEle = document.createElement('video'); videoEle.defaultMuted = true; console.log(videoEle.outerHTML); // <video muted=""></video> Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.defaultMuted' in that specification. Living Standard No change from HTML5 HTML5The definitio...
HTMLMediaElement.disableRemotePlayback - Web APIs
disableRemotePlayback property determines whether the media element is allowed to have a remote playback UI. Syntax var remotePlaybackDisabled = element.disableRemotePlayback; Value A Boolean indicating whether the media element may have a remote playback UI. (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. Candidate Recommendation Initial definition. ...
HTMLMediaElement.ended - Web APIs
The HTMLMediaElement.ended indicates whether the media element has ended playback. Syntax var isEnded = HTMLMediaElement.ended Value A Boolean which is true if the media contained in the element has finished playing. If the source of the media is a MediaStream, this value is true if the value of the stream's active property is false. 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. Living Standard HTML5The definition of 'HTMLMediaElement.ended' in that specification. Recommendation ...
HTMLMediaElement.loop - Web APIs
The HTMLMediaElement.loop property reflects the loop HTML attribute, which controls whether the media element should start over when it reaches the end. Syntax var loop = video.loop; audio.loop = true; Value A Boolean. Example var obj = document.createElement('video'); obj.loop = true; // true Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.loop' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.loop' in that specification. Recommendation ...
HTMLMediaElement.msInsertAudioEffect() - Web APIs
nsertAudioEffect() method inserts the specified audio effect into the media pipeline. This proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax HTMLMediaElement.msInsertAudioEffect(activatableClassId: DOMString, effectRequired: boolean, config); Parameters activatableClassId A DOMString defining the audio effects class. effectRequired A Boolean which if set to true requires an audio effect to be defined. configOptional An optional Object to help with defining any additional configuration needed. Return value This method does not return a value. See also HTMLMediaElement Microsoft API extensions ...
HTMLMediaElement.muted - Web APIs
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. ...
HTMLMediaElement.paused - Web APIs
The read-only HTMLMediaElement.paused property tells whether the media element is paused. Syntax var isPaused = audioOrVideo.paused Value A Boolean. true is paused and false is not paused. Example var obj = document.createElement('video'); console.log(obj.paused); // true Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLMediaElement.paused' in that specification. Living Standard HTML5The definition of 'HTMLMediaElement.paused' in that specification. Recommendation ...
HTMLMediaElement: play event - Web APIs
Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onplay Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's play event, then post a message when that event handler has reacted to the event firing. Using addEventListener(): const video = document.querySelector('video'); video.addEventListener('play', (event) => { console.log('The Boolean paused property is now false. ...
HTMLMediaElement: seeking event - Web APIs
Bubbles No Cancelable No Interface Event Target Element Default Action None Event handler property GlobalEventHandlers.onseeking Specification HTML5 media Examples These examples add an event listener for the HTMLMediaElement's seeking event, then post a message when that event handler has reacted to the event firing. ...
HTMLOListElement - Web APIs
as,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLOListElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, HTMLElement. 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). HTMLOListElement.start Is a long value reflecting the start and defining the value of the first number of the first element of the list. HTMLOListElement.type Is a DOMString value reflecting the type and defining the kind of marker to be used to display. It can have the following values: '1' meaning that decimal numbers are used: 1, 2, 3, 4, 5, ... 'a' meaning tha...
HTMLObjectElement.checkValidity - Web APIs
The checkValidity() method of the HTMLObjectElement interface returns a Boolean that always is true, because object objects are never candidates for constraint validation. Syntax const valid = HTMLObjectElement.checkValidity(); Parameters None. Return value true Exceptions None. Specifications Specification Status Comment HTML Living StandardThe definition of 'checkValidity' in that specification. Living Standard Initial definition. ...
HTMLObjectElement - Web APIs
the width HTML attribute, specifying the displayed width of the resource in CSS pixels. HTMLObjectElement.willValidate Read only Returns a Boolean that indicates whether the element is a candidate for constraint validation. Always false for HTMLObjectElement objects. Methods Inherits methods from its parent, HTMLElement. HTMLObjectElement.checkValidity() Retuns a Boolean that always is true, because object objects are never candidates for constraint validation. HTMLObjectElement.setCustomValidity() Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLO...
HTMLOptGroupElement - Web APIs
amily="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">HTMLOptGroupElement</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties Inherits properties from its parent, HTMLElement. HTMLOptGroupElement.disabled Is a boolean representing whether or not the whole list of children <option> is disabled (true) or not (false). HTMLOptGroupElement.label Is a DOMString representing the label for the group. Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLOptgroupElement' in that specification. Living Standard HTML5The definition of 'HTMLOptGroupE...
HTMLOrForeignElement.dataset - Web APIs
Living Standard No change from latest snapshot, HTML 5.1 HTML 5.1The definition of 'HTMLElement.dataset' in that specification. Recommendation Snapshot of HTML Living Standard, no change from HTML5 HTML5The defi...
HTMLOutputElement - Web APIs
ds from its parent, HTMLElement. HTMLOutputElement.checkValidity() Checks the validity of the element and returns a Boolean holding the check result. HTMLOutputElement.reportValidity() This method reports the problems with the constraints on the element, if any, to the user. If there are problems, fires an invalid event at the element, and returns false; if there are no problems, it returns true. When the problem is reported, the user agent may focus the element and change the scrolling position of the document or perform some other action that brings the element to the user's attention. User agents may report more than one constraint violation if this element suffers from multiple problems at once. If the element is not rendered, then the user agent may report the error for the running...
HTMLScriptElement - Web APIs
l Text nodes inside the <script> element (ignoring other nodes like comments) in tree order. On setting, it acts the same way as the textContent IDL attribute. Note: When inserted using the document.write() method, <script> elements execute (typically synchronously), but when inserted using innerHTML or outerHTML, they do not execute at all. HTMLScriptElement.noModule Is a Boolean that if true, stops the script's execution in browsers that support ES2015 modules -- used to run fallback scripts in older browsers that do not support JavaScript modules. HTMLScriptElement.referrerPolicy Is a DOMString that reflects the referrerpolicy HTML attribute indicating which referrer to use when fetching the script, and fetches done by that script. Methods No specific methods; inherits methods...
HTMLSelectElement.disabled - Web APIs
Living Standard HTML5The definition of 'HTMLSelectElement' in that specification. Recommendation Initial definition, snapshot of HTML Living Standard. ...
HTMLSlotElement - Web APIs
The HTMLSlotElement interface of the Shadow DOM API enables access to the name and assigned nodes of an HTML <slot> element. Properties HTMLSlotElement.name DOMString: Can be used to get and set the slot's name. Methods HTMLSlotElement.assignedNodes() Returns a sequence of the nodes assigned to this slot, and if the flatten option is set to true, the assigned nodes of any other slots that are descendants of this slot. If no assigned nodes are found, it returns the slot's fallback content. HTMLSlotElement.assignedElements() Returns a sequence of the elements assigned to this slot (and no other nodes). If the flatten option is set to true, it also returns the assigned elements of any other slots that are descendants of this slot. If no assigned nodes are found, it returns the slot'...
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). By default it contains the value of the scoped content attribute. Syntax value = style.scoped; style.scoped = true; ...
HTMLStyleElement - Web APIs
erties Inherits properties from its parent, HTMLElement, and implements LinkStyle. HTMLStyleElement.media Is a DOMString representing the intended destination medium for style information. HTMLStyleElement.type Is a DOMString representing the type of style being applied by this statement. HTMLStyleElement.disabled Is a Boolean value representing whether or not the stylesheet is disabled (true) or not (false). LinkStyle.sheet Read only 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). Methods No specific method; inherits properties from its parent, HTMLElement, and LinkStyle. Specificatio...
HTMLTableElement.createTFoot() - Web APIs
Note: If no footer exists, createTFoot() inserts a new footer directly into the table. The footer does not need to be added separately as would be the case if Document.createElement() had been used to create the new <tfoot> element. Syntax HTMLTableSectionElement = table.createTFoot(); Return value HTMLTableSectionElement Example let myfoot = mytable.createTFoot(); // Now this should be true: myfoot == mytable.tFoot Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement: createTFoot' in that specification. Living Standard ...
HTMLTableElement.createTHead() - Web APIs
Note: If no header exists, createTHead() inserts a new header directly into the table. The header does not need to be added separately as would be the case if Document.createElement() had been used to create the new <thead> element. Syntax HTMLTableSectionElement = table.createTHead(); Return value HTMLTableSectionElement Example let myhead = mytable.createTHead(); // Now this should be true: myhead == mytable.tHead Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTableElement: createTHead' in that specification. Living Standard ...
HTMLTemplateElement.content - Web APIs
The HTMLTemplateElement.content property returns a <template> element's template contents (a DocumentFragment). Syntax var documentFragment = templateElement.content Example var templateElement = document.querySelector("#foo"); var documentFragment = templateElement.content.cloneNode(true); Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLTemplateElement interface' in that specification. Living Standard HTML5The definition of 'HTMLTemplateElement interface' in that specification. Recommendation Initial definition ...
HTMLVideoElement.msFrameStep() - Web APIs
er. There may also be large incompatibilities between implementations and the behavior may change in the future. The HTMLVideoElement.msFrameStep() method steps the video by one frame forward or one frame backward. This proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax HTMLVideoElement.msFrameStep(forward); Parameters forward A Boolean which if set to true steps the video forward by one frame, if false steps the video backwards by one frame. Return value This method does not return a value. See also HTMLMediaElement Microsoft API extensions ...
HTMLVideoElement.msIsStereo3D - Web APIs
msIsStereo3D is a read-only property which determines whether the system considers the loaded video source to be stereo 3-D or not. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax HTMLVideoElement.msIsStereo3D: boolean; Value Boolean value set to true indicates that the video source is stereo 3D. This uses metadata set in MP4 or MPEG-2 file containers and H.264 Supplemental enhancement information (SEI) messages to determine the stereo capability of the source. ...
HTMLVideoElement.videoHeight - Web APIs
h the intrinsic size of its contents. 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. This avoids applying invalid changes when there's no true information available yet for dimensions. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLVideoElement.videoHeight' in that specification. Living Standard HTML5The definition of 'HTMLVideoElement.videoHeight' in that specification. Recommendation Initial definition. ...
HTMLVideoElement.videoWidth - Web APIs
h the intrinsic size of its contents. 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. This avoids applying invalid changes when there's no true information available yet for dimensions. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLVideoElement.videoWidth' in that specification. Living Standard HTML5The definition of 'HTMLVideoElement.videoWidth' in that specification. Recommendation Initial definition. ...
HTMLVideoElement - Web APIs
horizontally in the display. HTMLVideoElement.msInsertVideoEffect() Inserts the specified video effect into the media pipeline. HTMLVideoElement.msIsLayoutOptimalForPlayback Read only Indicates whether the video can be rendered more efficiently. HTMLVideoElement.msIsStereo3D Read only Determines whether the system considers the loaded video source to be stereo 3-D or not. Value set to true indicates source is stereo 3D. HTMLVideoElement.msZoom Controls whether the video frame is trimmed to fit the video display. Methods Inherits methods from its parent, HTMLMediaElement, and from its ancestor HTMLElement. HTMLVideoElement.getVideoPlaybackQuality() Returns a VideoPlaybackQuality object that contains the current playback metrics. This information includes things like the...
Headers.has() - Web APIs
Web › API › Headers › has
the given name is not a valid HTTP header name, this method throws a TypeError. Returns A Boolean. Example Creating an empty Headers object is simple: var myHeaders = new Headers(); // Currently empty You could add a header to this using Headers.append, then test for the existence of it using has(): myHeaders.append('Content-Type', 'image/jpeg'); myHeaders.has('Content-Type'); // Returns true myHeaders.has('Accept-Encoding'); // Returns false Specifications Specification Status Comment FetchThe definition of 'has()' in that specification. Living Standard ...
IDBCursorSync - Web APIs
his cursor does not include duplicates, and its direction is monotonically decreasing in the order of keys. Methods continue() Advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. If no key is specified, advance to the immediate next position. Returns false if the cursor has reached the end of its range; otherwise returns true. bool continue ( in optional any key ); Parameters key The key to which to move the cursor's position. remove() Deletes the record at the cursor's position, without changing the cursor's position void delete ( ) raises (DatabaseException); Exceptions This method can raise an IDBDatabaseException with the following code: NOT_ALLOWED_ERR If the underlying index or object store d...
IDBDatabase.transaction() - Web APIs
nsure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see IDBDatabase.transaction.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config. details Optional Dictionary of other settings, supported only by Chrome: Return value An IDBTransaction object. Exceptions This method may raise a DOMException of one of the following types: Exception Description InvalidStateError The close() method has previously been called on this IDBDatabase instance. NotFoundError ...
IDBDatabaseSync - Web APIs
cted database. IDBObjectStoreSync createObjectStore( in DOMString name, in DOMString keypath, in optional boolean autoIncrement ) raises (IDBDatabaseException); Parameters name The name of a new object store. keypath The key path used by the new object store. If a null path is specified, then the object store does not have a key path, and uses out-of-line keys. autoIncrement If true, the object store uses a key generator; if false, it does not use one. Returns IDBObjectStoreSync An object to access the newly created object store. Exceptions This method can raise an IDBDatabaseException with the following code: CONSTRAINT_ERR If an object store with the same name (based on case-sensitive comparison) already exists in the connected database. openObjectStore() O...
IDBIndex.multiEntry - Web APIs
The multiEntry read-only property of the IDBIndex interface returns a boolean value that affects how the index behaves when the result of evaluating the index's key path yields an array. This is decided when the index is created, using the IDBObjectStore.createIndex method. This method takes an optional options parameter whose multiEntry property is set to true/false. Note: This feature is available in Web Workers. Syntax var isMultiEntry = myIndex.multiEntry; Value A Boolean: Value Effect true There is one record in the index for each item in an array of keys. false There is one record for each key that is an array. Example In the following example we open a transaction and an object store, then get the index lName from a simple contacts d...
IDBIndex.unique - Web APIs
Web › API › IDBIndex › unique
The unique read-only property returns a boolean that states whether the index allows duplicate keys. This is decided when the index is created, using the IDBObjectStore.createIndex method. This method takes an optional parameter, unique, which if set to true means that the index will not be able to accept duplicate entries. Note: This feature is available in Web Workers. Syntax var isUnique = IDBIndex.unique; Value A Boolean: Value Effect true The current index does not allow duplicate values for a key. false The current index allows duplicate key values. Example In the following example we open a transaction and an object store, then get the index lName from a simple contacts database. We then open a basic cursor on the index using ID...
IDBIndex - Web APIs
Web › API › IDBIndex
reateIndex()'s optionalParameters.) IDBIndex.name The name of this index. IDBIndex.objectStore Read only The name of the object store referenced by this index. IDBIndex.keyPath Read only The key path of this index. If null, this index is not auto-populated. IDBIndex.multiEntry Read only Affects how the index behaves when the result of evaluating the index's key path yields an array. If true, there is one record in the index for each item in an array of keys. If false, then there is one record for each key that is an array. IDBIndex.unique Read only If true, this index does not allow duplicate values for a key. Methods Inherits from: EventTarget IDBIndex.count() Returns an IDBRequest object, and in a separate thread, returns the number of records within a key range. IDBInd...
IDBIndexSync - Web APIs
abaseException); Attributes Attribute Type Description keyPath readonly DOMString The key path of this index. If this attribute is null, this index is not auto-populated. name readonly DOMString The name of this index. storeName readonly DOMString This index's referenced object store. unique readonly boolean If true, a key can have only one value within the index; if false, a key can have duplicate values. Methods add() Stores the given value into this index, optionally with the specified key. If a record already exists with the given key, an exception is raised. any add( in any value, in optional any key ) raises (IDBDatabaseException); Parameters Returns Exceptions This method can raise ...
IDBKeyRange.bound() - Web APIs
Web › API › IDBKeyRange › bound
F". We open a transaction (using IDBTransaction) and an object store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. This means that the cursor will only retrieve records with keys inside that range. This range includes the values "A" and "F", as we haven't declared that they should be open bounds. If we used IDBKeyRange.bound("A", "F", true, true);, then the range would not include "A" and "F", only the values between them. Note: For a more complete example allowing you to experiment with key range, have a look at the idbkeyrange directory in the indexeddb-examples repo (view the example live too.) function displayData() { var keyRangeValue = IDBKeyRange.bound("A", "F"); var transaction = db.transaction(['fThings'], 'readon...
IDBKeyRange.lowerBound() - Web APIs
und("F", false); -- a range that includes the value "F" and everthing after it. We open a transaction (using IDBTransaction) and an object store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. This means that the cursor will only retrieve the record with the key value "F" and all that come after it. If we used IDBKeyRange.lowerBound("F", true);, then the range would not include "F"; only the values after it. Note: For a more complete example allowing you to experiment with key range, have a look at our IDBKeyRange-example repo (view the example live too.) function displayData() { var keyRangeValue = IDBKeyRange.lowerBound("F"); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transaction.objectSt...
IDBKeyRange.upperBound() - Web APIs
example illustrates how you'd use an upper bound key range. Here we declare keyRangeValue = IDBKeyRange.upperBound("F"); -- a range that includes the value "F" and everything before it. We open a transaction (using IDBTransaction) and an object store, and open a Cursor with IDBObjectStore.openCursor, declaring keyRangeValue as its optional key range value. If we used IDBKeyRange.upperBound("F", true);, then the range excludes "F"; and instead only includes the values before it. Note: For a more complete example allowing you to experiment with key range, have a look at our IDBKeyRange-example repo (view the example live too.) function displayData() { var keyRangeValue = IDBKeyRange.upperBound("F"); var transaction = db.transaction(['fThings'], 'readonly'); var objectStore = transac...
IDBObjectStore.autoIncrement - Web APIs
The autoIncrement read-only property of the IDBObjectStore interface returns the value of the auto increment flag for this object store. Note that every object store has its own separate auto increment counter. Note: This feature is available in Web Workers. Syntax var myAutoIncrement = objectStore.autoIncrement; Value A Boolean: Value Meaning true The object store auto increments. false The object store does not auto increment. Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store using add(). After the object store has been created, we log objectStore.autoIncrement to the console. For a full working example, see our To-do Notifications app (view example live.
IDBOpenDBRequest.onupgradeneeded - Web APIs
ne above. request.onupgradeneeded = function(event) { db = request.result; db.onerror = function(errorEvent) { note.innerHTML += '<li>Error loading database.</li>'; }; if (event.oldVersion < 1) { // Version 1 is the first version of the database. var store = db.createObjectStore("books", {keyPath: "isbn"}); var titleIndex = store.createIndex("by_title", "title", {unique: true}); var authorIndex = store.createIndex("by_author", "author"); } if (event.oldVersion < 2) { // Version 2 introduces a new index of books by year. var bookStore = request.transaction.objectStore("books"); var yearIndex = bookStore.createIndex("by_year", "year"); } if (event.oldVersion < 3) { // Version 3 introduces a new object store for magazines with two indexes. ...
IDBTransaction.oncomplete - Web APIs
nsure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see IDBDatabase.transaction.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config. Syntax transaction.oncomplete = function(event) { ... }; Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. Note the transaction.oncomplete = function(...
IDBTransactionSync - Web APIs
ew void abort() raises (IDBDatabaseException); void commit() raises (IDBDatabaseException); IDBObjectStoreSync objectStore(in DOMString name) raises (IDBDatabaseException); Attributes Attribute Type Description db IDBDatabaseSync The database connection that this transaction is associated with. static boolean If true, this transaction is static; if false, this transaction is dynamic. Methods abort() Call this method to signal a need to cancel the effects of the operations performed by this transaction. When this method is called, the browser ignores all the changes performed to the objects of this database since this transaction was created. void abort( ) raises (IDBDatabaseException); Exceptions ...
IdleDeadline.timeRemaining() - Web APIs
d return control to the user agent's event loop. Syntax timeRemaining = IdleDeadline.timeRemaining(); Return value A DOMHighResTimeStamp value (which is a floating-point number) representing the number of milliseconds the user agent estimates are left in the current idle period. The value is ideally accurate to within about 5 microseconds. If the IdleDeadline object's didTimeout property is true, this method returns zero. Example See our complete example in the article Cooperative Scheduling of Background Tasks API. Specifications Specification Status Comment Cooperative Scheduling of Background Tasks Proposed Recommendation ...
IdleDeadline - Web APIs
timeRemaining(), which lets you determine how much longer the user agent estimates it will remain idle and a property, didTimeout, which lets you determine if your callback is executing because its timeout duration expired. To learn more about how request callbacks work, see Collaborative Scheduling of Background Tasks. Properties IdleDeadline.didTimeout Read only A Boolean whose value is true if the callback is being executed because the timeout specified when the idle callback was installed has expired. Methods IdleDeadline.timeRemaining() Returns a DOMHighResTimeStamp, which is a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period. If the idle period is over, the value is 0. Your callback can call this repeatedly to see...
ImageCapture() constructor - Web APIs
stream of a video conference, a playing movie, or the stream from a webcam. Return value A new ImageCapture object which can be used to capture still frames from the specified video track. Example The following example shows how to use a call to MediaDevices.getUserMedia() to retrieve the MediaStreamTrack needed by the ImageCapture() constructor. navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream const track = mediaStream.getVideoTracks()[0]; imageCapture = new ImageCapture(track); }) .catch(error => console.log(error)); Specifications Specification Status Comment MediaStream Image CaptureThe definition of 'ImageCapture' in that specification. Working Draft In...
ImageCapture.getPhotoCapabilities() - Web APIs
tracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoCapabilities() to modify the size of an input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
ImageCapture.getPhotoSettings() - Web APIs
e, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoSettings() to modify the size of an input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
ImageCapture - Web APIs
ther words a camera). This example shows, roughly, a MediaStreamTrack extracted from a device's MediaStream. The track is then used to create an ImageCapture object so that takePhoto() and grabFrame() can be called. Finally, it shows how to apply the results of these calls to a canvas object. ...
Basic concepts - Web APIs
nsure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see IDBDatabase.transaction.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config. object store The mechanism by which data is stored in the database. The object store persistently holds records, which are key-value pairs. Records within an object store are sorted according to the keys in an ascending order. Every object store must have a name that is unique within its database. The object store can optionally have a key generator and a key path. If t...
InputDeviceCapabilities - Web APIs
For example, two mice with the same capabilities in a system may appear as a single InputDeviceCapabilities instance. ...
InputEvent.dataTransfer - Web APIs
eved via the InputEvent.dataTransfer.getData() method and reported in the paragraph below the input. Try copying and pasting some of the content provided to see the effects. ...
InputEvent.inputType - Web APIs
taining the type of input that was made. There are many possible values, such as insertText, deleteContentBackward, insertFromPaste, and formatBold. For a complete list of the available input types, see the Attributes section of the Input Events Level 1 spec. Examples This example logs the inputType for input events on an editable <div>. HTML <p id="log">Input type: </p> <div contenteditable="true" style="margin: 20px;padding: 20px;border:2px dashed red;"> <p>Some sample text. Try inserting line breaks, or deleting text in different ways, or pasting different content in.</p> <hr> <ul> <li>A sample</li> <li>bulleted</li> <li>list.</li> </ul> <p>Another paragraph.</p> </div> JavaScript const log = document.getElementById('log'); const editable = document.querySelector...
enabled - Web APIs
The method reflects the value of the Software Installation preference in the user interface, and of the xpinstall.enabled preference in pref.js. ...
install - Web APIs
l method has the following parameters: XPIlist An array of files to be installed (see example below). callBackFunc An optional callback function invoked when the installation is complete (see example below). Firefox 3 note In Firefox 3 the callback is no longer invoked unless the website performing the installation is whitelisted. 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. To surface detail about the status of the installation, use the optional callback function and its status parameter, as in the example below. Description In the example below, a special JavaScript object constructor is used to create an object that can b...
installChrome - Web APIs
TYPE can be InstallTrigger.SKIN or InstallTrigger.LOCALE. url url is a string containing a full or relative URL to download name name is displayed in the dialog, but is also used to *select* the theme somust match exactly the name in the internal manifest.rdf file. Returns A boolean value indicating False if the software install feature has been turned off, and True if it's on. Note that this return value does not indicate anything about the success of the installation. Description installChrome is a special method for installing new chrome in Netscape 6 and Mozilla. The method performs a simplified installation of language packs or Netscape 6/Mozilla skins, and saves you the trouble of writing separate installation scripts in the XPI files or using the more...
startSoftwareUpdate - Web APIs
Summary Triggers the downloading and installation of the software at the specified URL. Method of InstallTrigger object Syntax Boolean startSoftwareUpdate ( String url); Parameters The startSoftwareUpdate method has the following parameter: url A uniform resource locator specifying the location of the XPI file containing the software. Returns True. Description The startSoftwareUpdate method triggers a software download and install from the specified URL. This method has been largely superseded by newer install method, which is more flexible and allows you to install more than one XPI. Note also that XPIs installed with this method must have their own install.js files in which the full installation is defined. ...
IntersectionObserverEntry.intersectionRatio - Web APIs
er between 0.0 and 1.0 which indicates how much of the target element is actually visible within the root's intersection rectangle. More precisely, this value is the ratio of the area of the intersection rectangle (intersectionRect) to the area of the target's bounds rectangle (boundingClientRect). If the area of the target's bounds rectangle is zero, the returned value is 1 if isIntersecting is true or 0 if not. Example In this simple example, an intersection callback sets each target element's opacity to the intersection ratio of that element with the root. function intersectionCallback(entries) { entries.forEach(function(entry) { entry.target.style.opacity = entry.intersectionRatio; }); } To see a more concrete example, take a look at Handling intersection changes in Timing ele...
IntersectionObserverEntry.isIntersecting - Web APIs
The IntersectionObserverEntry interface's read-only isIntersecting property is a Boolean value which is true if the target element intersects with the intersection observer's root. If this is true, then, the IntersectionObserverEntry describes a transition into a state of intersection; if it's false, then you know the transition is from intersecting to not-intersecting. Syntax var isIntersecting = IntersectionObserverEntry.isIntersecting; Value A Boolean value which indicates whether the target element has transitioned into a state of intersection (true) or out of a state of intersection (false). Example In this simple example, an intersection callback is used to update a counter of how many targeted elements are currently intersecting with the intersection root. function intersection...
IntersectionObserverEntry - Web APIs
d as described in the documentation for Element.getBoundingClientRect(). IntersectionObserverEntry.intersectionRatio Read only Returns the ratio of the intersectionRect to the boundingClientRect. IntersectionObserverEntry.intersectionRect Read only Returns a DOMRectReadOnly representing the target's visible area. IntersectionObserverEntry.isIntersecting Read only A Boolean value which is true if the target element intersects with the intersection observer's root. If this is true, then, the IntersectionObserverEntry describes a transition into a state of intersection; if it's false, then you know the transition is from intersecting to not-intersecting. IntersectionObserverEntry.rootBounds Read only Returns a DOMRectReadOnly for the intersection observer's root. IntersectionObserver...
InterventionReportBody - Web APIs
ource file where the intervention occurred, if known, or null otherwise. lineNumber A number representing the line in the source file in which the intervention occurred, if known, or null otherwise. columnNumber A number representing the column in the source file in which the intervention occurred, if known, or null otherwise. ...
KeyboardEvent.altKey - Web APIs
The KeyboardEvent.altKey read-only property is a Boolean that indicates if the alt key (Option or ? on OS X) was pressed (true) or not (false) when the event occured. Syntax var altKeyPressed = instanceOfKeyboardEvent.altKey Return value Boolean Examples <html> <head> <title>altKey example</title> <script type="text/javascript"> function showChar(e){ alert( "Key KeyDown: " + String.fromCharCode(e.charCode) + "\n" + "charCode: " + e.charCode + "\n" + "ALT key KeyDown: " + e.altKey + "\n" ); } </script> </head> <body onkeydown="showChar(event);"> <p> Press any character key, with or without holding down the ALT key.<br /> You can also use the SHIFT key together with the ALT key. </p> </body> </html> Specifications Specification Status Comment ...
KeyboardEvent.ctrlKey - Web APIs
The KeyboardEvent.ctrlKey read-only property returns a Boolean that indicates if the control key was pressed (true) or not (false) when the event occured. Syntax var ctrlKeyPressed = instanceOfKeyboardEvent.ctrlKey Return value A Boolean Example <html> <head> <title>ctrlKey example</title> <script type="text/javascript"> function showChar(e){ alert( "Key Pressed: " + e.key + "\n" + "CTRL key pressed: " + e.ctrlKey + "\n" ); } </script> </head> <body onkeypress="showChar(event);"> <p>Press any character key, with or without holding down the CTRL key.<br /> You can also use the SHIFT key together with the CTRL key.</p> </body> </html> Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definiti...
KeyboardEvent.metaKey - Web APIs
Some operating systems may intercept the key so it is never detected. Note: On Macintosh keyboards, this is the ? Command key. On Windows keyboards, this is the Windows key (? Windows). At least as of Firefox 48, the ? Windows key is not considered the "Meta" key. KeyboardEvent.metaKey is false when the ? Windows is pressed. ...
KeyboardEvent.repeat - Web APIs
The repeat read-only property of the KeyboardEvent interface returns a Boolean that is true if the given key is being held down such that it is automatically repeating. Syntax var repeat = event.repeat; Return value Boolean Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'KeyboardEvent.repeat' in that specification. Obsolete Initial definition. ...
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. Syntax var shiftKeyPressed = instanceOfKeyboardEvent.shiftKey Return value A Boolean Example <html> <head> <title>shiftKey example</title> <script type="text/javascript"> function showChar(e){ alert( "Key Pressed: " + String.fromCharCode(e.charCode) + "\n" + "charCode: " + e.charCode + "\n" + "SHIFT key pressed: " + e.shiftKey + "\n" + "ALT key pressed: " + e.altKey + "\n" ); } </script> </head> <body onkeypress="showChar(event);"> <p>Press any character key, with or without holding down the SHIFT key.<br /> You can also use the SHIFT key together with the ALT key.</p> </body> </html> Specifications Sp...
LockedFile.active - Web APIs
Web › API › LockedFile › active
Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The active property allows to know if the LockedFile object is still usable (true) or not (false). If the object is inactive then it is impossible to perform any read or write operation with it. Typically, a LockedFile object becomes inactive when the LockedFile.abort() method is called or if an error occurs. Syntax var state = instanceOfLockedFile.active Value A Boolean. Specifications Specification Status Comment FileSystem API Editor's Draft Draft Proposal. ...
LockedFile.getMetadata() - Web APIs
l not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. Summary The getMetadata method allows to retrieve some metadata about the locked file. Syntax var request = instanceOfLockedFile.getMetadata(param); Parameters param Optional An object used to request specific metadata. Each key is a boolean where true means the metadata is expected and where false means it is not expected. Note that if the key is undefined, it is considered as if it were true. The following metadata are supported: size : will provide the size of the file lastModified : will provide the date when the file was last modified Return A FileRequest object. In case of success, the request's result is an object with the metada...
LockedFile - Web APIs
n the future. Summary The LockedFile interface provides tools to deal with a given file with all the necessary locks. Properties LockedFile.fileHandle Read only The FileHandle object from which the lock was opened. LockedFile.mode Read only The mode for accessing the file; can be readonly or readwrite. LockedFile.active Read only A flag indicating if the file can be accessed (true) or not (false). LockedFile.location The position of the reading/writing pointer within the file. Events Handler LockedFile.oncomplete The complete event is triggered each time a read or write operation is successful. LockedFile.onabort The abort event is triggered each time the abort() method is called. LockedFile.onerror The error event is triggered each time something goes wrong. ...
MSGraphicsTrust - Web APIs
es between implementations and the behavior may change in the future. The msGraphicsTrust() constructor returns an object that provides properties for info on protected video playback. This proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax var trustObject = media.msGraphicsTrustStatus; Parameters constrictionActive A read-only property which returns true when protected media is forced to play in a lower resolution. status A read-only property which returns an enum with the driver status when playing protected content. Inheritance hierarchy The MSGraphicsTrust does not inherit from any class or interface. Example var trustObject = media.msGraphicsTrustStatus; ...
MSManipulationEvent.initMSManipulationEvent() - Web APIs
the Microsoft Edge browser, the initEvent() constructor pattern for synthetic events is deprecated. Syntax MSManipulationEvent.initMSManipulationEvent(typeArg, canBubbleArg, cancelableArg, viewArg, detailArg, lastState, currentState); Parameters typeArg [in] Type: DOMString The type of the event being created. canBubbleArg [in] Type: boolean Indicates whether the event can bubble. When true the event should propagate upward. When false the event does not propagate upward. cancelableArg [in] Type: boolean Indicates whether the event's default action can be prevented. When true, the default action can be canceled. When false, the default action cannot be canceled. viewArg [in] Type: AbstractView The view in which the event is taking place. detailArg [in] Type: Integer Specifi...
MediaDevices.getSupportedConstraints() - Web APIs
ties the user agent understands. Syntax var supportedConstraints = navigator.mediaDevices.getSupportedConstraints(); Parameters None. Return value A new object based on the MediaTrackSupportedConstraints dictionary listing the constraints supported by the user agent. Because only constraints supported by the user agent are included in the list, each of these Boolean properties has the value true. Example This example outputs a list of the constraints supported by your browser. HTML <p>The following media constraints are supported by your browser:</p> <ul id="constraintList"> </ul> CSS body { font: 15px Arial, sans-serif; } JavaScript let constraintList = document.getElementById("constraintList"); let supportedConstraints = navigator.mediaDevices.getSupportedConstraints(); f...
MediaDevices - Web APIs
the user's permission through a prompt, turns on a camera and/or a microphone on the system and provides a MediaStream containing a video track and/or an audio track with the input. Example 'use strict'; // Put variables in global scope to make them available to the browser console. ...
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. You can be notified when the value of matches changes by watching for the change event to be fired at the MediaQueryList. Syntax var matches = <varm>MediaQueryList.matches; Value A Boolean which is true if the document currently matches the media query list; otherwise, it's false. Examples This example detects viewport orientation changes by creating a media query using the orientation media feature: function addMQListener(mq, callback) { if (mq.addEventListener) { mq.addEventListener("change", callback); } else { mq.addListener(callback); } } addMQListener(window.matchMedia("(orientation:landscape)"), e...
MediaQueryListEvent.MediaQueryListEvent() - Web APIs
The MediaQueryListEvent constructor creates a new MediaQueryListEvent instance. Syntax var myMqlEvent = new MediaQueryListEvent(init); Parameters init An init object that defines features of the new object instance. The available properties are: media: A DOMString representing a serialized media query. matches: A Boolean representing the media query status -- true if it matches, false if not. Examples var media = '(max-width: 600px)'; var matches = true; var myMediaQueryListEvent = new MediaQueryListEvent({media, matches}); Specifications Specification Status Comment CSS Object Model (CSSOM) View ModuleThe definition of 'MediaQueryListEvent()' in that specification. Working Draft Initial definition ...
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. Examples var mql = window.matchMedia('(max-width: 600px)'); function screenTest(e) { if (e.matches) { /* the viewport is 600 pixels wide or less */ para.textContent = 'This is a narrow screen -- less than 600px wide.'; document.body.style.backgroundColor = 'red'; } else { /* the viewport is more than than 600 pixels wide */ para.textContent = 'This is a wide screen -- more than 600px wide.'; document.body.style.backgroundColor = 'blue'; } }...
MediaQueryListEvent - Web APIs
-- instances are available as the event object on a function referenced by a MediaQueryList.onchange property or MediaQueryList.addListener() call. Constructor MediaQueryListEvent() Creates a new MediaQueryListEvent instance. Properties The MediaQueryListEvent interface inherits properties from its parent interface, Event. MediaQueryListEvent.matchesRead only A Boolean that returns true if the document currently matches the media query list, or false if not. MediaQueryListEvent.mediaRead only A DOMString representing a serialized media query. Methods The MediaQueryListEvent interface inherits methods from its parent interface, Event. Examples var mql = window.matchMedia('(max-width: 600px)'); function screenTest(e) { if (e.matches) { /* the viewport is 600 pix...
MediaRecorder() - Web APIs
e This example shows how to create a media recorder for a specified stream, whose audio bit rate is set to 128 Kbit/sec and whose video bit rate is set to 2.5 Mbit/sec. The recorded media data will be stored in an MP4 wrapper (so if you gather the chunks of media data and save them to disk, they will be in an MP4 file). ... if (navigator.mediaDevices.getUserMedia) { var constraints = { audio: true, video: true }; var chunks = []; var onSuccess = function(stream) { var options = { audioBitsPerSecond : 128000, videoBitsPerSecond : 2500000, mimeType : 'video/mp4' } var mediaRecorder = new MediaRecorder(stream,options); m = mediaRecorder; ... } } Specifications Specification Status Comment MediaStream Recording Working Dra...
MediaRecorder.mimeType - Web APIs
ings are standardized by the Internet Assigned Numbers Authority (IANA). For their official list of defined media type strings, see the article Media Types on the IANA site. See also media types to learn more about media types and how they're used in web content and by web browers. Example ... if (navigator.mediaDevices) { console.log('getUserMedia supported.'); var constraints = { audio: true, video: true }; var chunks = []; navigator.mediaDevices.getUserMedia(constraints) .then(function(stream) { var options = { audioBitsPerSecond: 128000, videoBitsPerSecond: 2500000, mimeType: 'video/mp4' } var mediaRecorder = new MediaRecorder(stream,options); m = mediaRecorder; m.mimeType; // would return 'video/mp4' ... }) ...
MediaRecorder.ondataavailable - Web APIs
e in the dataavailable event's data property. Syntax MediaRecorder.ondataavailable = function(event) { ... } MediaRecorder.addEventListener('dataavailable', function(event) { ... }) Example ... var chunks = []; mediaRecorder.onstop = function(e) { console.log("data available after MediaRecorder.stop() called."); var audio = document.createElement('audio'); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); } mediaRecorder.ondataavailable = function(e) { chunks.push(e.data); } ... Specifications Specification Status Comment MediaStream RecordingThe definition of 'MediaRecorde...
MediaRecorder.onstop - Web APIs
ing the Blob captured up to that point available for you to use in your application. Syntax MediaRecorder.onstop = function(event) { ... } MediaRecorder.addEventListener('stop', function(event) { ... }) Example ... mediaRecorder.onstop = function(e) { console.log("data available after MediaRecorder.stop() called."); var audio = document.createElement('audio'); audio.controls = true; var blob = new Blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audioURL = window.URL.createObjectURL(blob); audio.src = audioURL; console.log("recorder stopped"); } mediaRecorder.ondataavailable = function(e) { chunks.push(e.data); } ... Specifications Specification Status Comment MediaStream RecordingThe definition of 'MediaRecorder...
MediaRecorder.stream - Web APIs
r() constructor when the MediaRecorder was created. Syntax var stream = MediaRecorder.stream Values The MediaStream passed into the MediaRecorder() constructor when the MediaRecorder was originally created. Example if (navigator.getUserMedia) { console.log('getUserMedia supported.'); navigator.getUserMedia ( // constraints - only audio needed for this app { audio: true }, // Success callback function(stream) { var mediaRecorder = new MediaRecorder(stream); var myStream = mediaRecorder.stream; console.log(myStream); ... Specifications Specification Status Comment MediaStream RecordingThe definition of 'MediaRecorder.stream' in that specification. Working Draft Initial definitio...
Media Session action types - Web APIs
roperty seekOffset specifies the amount of time to seek forward. seekto Moves the playback position to the specified time within the media. The time to which to seek is specified in the MediaSessionActionDetails property seekTime. If you intend to perform multiple seekto operations in rapid succession, you can also specify the MediaSessionActionDetails property fastSeek property with a value of true. This lets the browser know it can take steps to optimize repeated operations, and is likely to result in improved performance. skipad Skips past the currently playing advertisement or commercial. This action may or may not be available, depending on the platform and user agent, or may be disabled due to subscription level or other circumstances. stop Halts playback entirely. Description A...
MediaSessionActionDetails.seekTime - Web APIs
Time: absTimeInSeconds }; let absTime = mediaSessionActionDetails.seekTime; Value A floating-point value indicating the absolute time in seconds into the media to which to move the current play position. Usage notes To perform a "fast" seek (such as when issuing multiple seekto actions in sequence while handling a scrubbing operation, the details object's fastSeek property's value is set to true, indicating that you should minimize or eliminate anything you do while handling the action that is only necessary at the final step. 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. Specifications Specification Status Comment Media S...
MediaSessionActionDetails - Web APIs
roperty seekOffset specifies the amount of time to seek forward. seekto Moves the playback position to the specified time within the media. The time to which to seek is specified in the MediaSessionActionDetails property seekTime. If you intend to perform multiple seekto operations in rapid succession, you can also specify the MediaSessionActionDetails property fastSeek property with a value of true. This lets the browser know it can take steps to optimize repeated operations, and is likely to result in improved performance. skipad Skips past the currently playing advertisement or commercial. This action may or may not be available, depending on the platform and user agent, or may be disabled due to subscription level or other circumstances. stop Halts playback entirely. Description A...
MediaSettingsRange - Web APIs
Returns the minimum difference between consecutive values of this setting. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoCapabilities().imageWidth to modify the size of an input range. ...
MediaSource.duration - Web APIs
own when setting a new value for this property. Exception Explanation InvalidAccessError An attempt was made to set a duration value that was negative, or NaN. InvalidStateError MediaSource.readyState is not equal to open, or one or more of the SourceBuffer objects in MediaSource.sourceBuffers are being updated (i.e. ...
MediaSource.endOfStream() - Web APIs
a data; maybe the data is corrupt, or is encoded using a codec that the browser doesn't know how to decode. Return value undefined Exceptions Exception Explanation InvalidStateError MediaSource.readyState is not equal to open, or one or more of the SourceBuffer objects in MediaSource.sourceBuffers are being updated (i.e. ...
MediaSource.isTypeSupported() - Web APIs
The MediaSource.isTypeSupported() static method returns a Boolean value which is true if the given MIME type is likely to be supported by the current user agent. That is, if it can successfully create SourceBuffer objects for that MIME type. If the returned value is false, then the user agent is certain that it cannot access media of the specified format. Syntax var isItSupported = mediaSource.isTypeSupported(mimeType); Parameters mimeType The MIME media type that you want to test support for in the current browser. This may include the codecs parameter to provide added details about the codecs used within the file. Return value A Boolean which is true if the browser feels that it can probably play media of the specified type. This is not a guarantee, however, and your code must be ...
MediaStream.ended - Web APIs
Web › API › MediaStream › ended
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. This value once the ended event has been fired. This property has been removed from the specification; you should instead rely on the ended event or check the value of MediaStreamTrack.readyState to see if its value is "ended" for the track or tracks you want to ensure have finished playing. Syntax var hasEnded = MediaStream.ended; Value A Boolean value that returns true if the end of the stream has been reached. Specifications No longer part of any specification. This property was part of earlier drafts of the Media Capture and Streams specification. ...
MediaStream.getTrackById() - Web APIs
atches the specified id string, that MediaStreamTrack object is returned. Otherwise, the returned value is null. Example This example activates a commentary track on a video by ducking the audio level of the main audio track to 50%, then enabling the commentary track. stream.getTrackById("primary-audio-track").applyConstraints({ volume: 0.5 }); stream.getTrackById("commentary-track").enabled = true; Specifications Specification Status Comment Media Capture and StreamsThe definition of 'getTrackById()' in that specification. Candidate Recommendation Initial specification. ...
MediaStream.getTracks() - Web APIs
The getTracks() method of the MediaStream interface returns a sequence that represents all the MediaStreamTrack objects in this stream's track set, regardless of MediaStreamTrack.kind. Syntax var mediaStreamTracks = mediaStream.getTracks() Parameters None. Return value An array of MediaStreamTrack objects. Example navigator.mediaDevices.getUserMedia({audio: false, video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; // Stop the stream after 5 seconds setTimeout(() => { const tracks = mediaStream.getTracks() tracks[0].stop() }, 5000) }) Specifications Specification Status Comment Media Capture and StreamsThe definition of 'getTracks()' in that specification. Candidate Recommendation Initial ...
MediaStream.getVideoTracks() - Web APIs
ich was used as the type for each entry in the list of video streams; however, this has since been merged into the main MediaStreamTrack interface. Example The following example, extracted from Chrome's Image Capture / Photo Resolution Sample, uses getVideoTracks() to retrieve a track for passing to the ImageCapture() constructor. var imageCapture; navigator.mediaDevices.getUserMedia({video: true}) .then(mediaStream => { document.querySelector('video').srcObject = mediaStream; const track = mediaStream.getVideoTracks()[0]; imageCapture = new ImageCapture(track); return imageCapture.getPhotoCapabilities(); }) Specifications Specification Status Comment Media Capture and StreamsThe definition of 'getVideoTracks()' in that specification. Candidate Recom...
MediaStream - Web APIs
ructor MediaStream() Creates and returns a new MediaStream object. You can create an empty stream, a stream which is based upon an existing stream, or a stream that contains a specified list of tracks (specified as an array of MediaStreamTrack objects). Properties This interface inherits properties from its parent, EventTarget. MediaStream.active Read only A Boolean value that returns true if the MediaStream is active, or false otherwise. MediaStream.ended Read only A Boolean value set to true if the end of the stream has been reached. This has been removed from the specification; you should instead check the value of MediaStreamTrack.readyState to see if its value is ended for the track or tracks you want to ensure have finished playing. MediaStream.id Read only A DOMSt...
MediaStreamAudioSourceNode() - Web APIs
en creates a new MediaStreamAudioSourceNode from its MediaStream. ...
MediaStreamAudioSourceNode - Web APIs
'pre'); var video = document.querySelector('video'); var myScript = document.querySelector('script'); var range = document.querySelector('input'); // getUserMedia block - grab stream // put it into a MediaStreamAudioSourceNode // also output the visuals into a video element if (navigator.mediaDevices) { console.log('getUserMedia supported.'); navigator.mediaDevices.getUserMedia ({audio: true, video: true}) .then(function(stream) { video.srcObject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // Create a MediaStreamAudioSourceNode // Feed the HTMLMediaElement into it var audioCtx = new AudioContext(); var source = audioCtx.createMediaStreamSource(stream); ...
MediaStreamConstraints - Web APIs
...
MediaStreamTrack.applyConstraints() - Web APIs
size of 1920 by 1280 is the preferred or an aspect ratio of 1.333 if that is not available. Note that these constraints also illustrate what the spec refers to as a backoff strategy. const constraints = { width: {min: 640, ideal: 1280}, height: {min: 480, ideal: 720}, advanced: [ {width: 1920, height: 1280}, {aspectRatio: 1.333} ] }; navigator.mediaDevices.getUserMedia({ video: true }) .then(mediaStream => { const track = mediaStream.getVideoTracks()[0]; track.applyConstraints(constraints) .then(() => { // Do something with the track such as using the Image Capture API. }) .catch(e => { // The constraints could not be satisfied by the available devices. }); }); Specifications Specification Status Comment Media Capture and Stream...
MediaStreamTrack: mute event - Web APIs
The mute event is sent to a MediaStreamTrack when the track's source is temporarily unable to provide media data. When the track is once again able to produce media output, an unmute event is sent. During the time between the mute event and the unmute event, the value of the track's muted property is true. Note: The condition that most people think of as "muted" (that is, a user-toggled state of silencing a track) is actually managed using the MediaStreamTrack.enabled property, for which there are no events. Bubbles No Cancelable No Interface Event Event handler property onmute Examples In this example, event handlers are established for the mute and unmute events in order to detect when the media is not flowing from the source for ...
MediaStreamTrack.muted - Web APIs
ng whether or not the track is currently unable to provide media output. To implement a way for users to mute and unmute a track, use the enabled property. When a track is disabled by setting enabled to false, it generates only empty frames (audio frames in which every sample is 0, or video frames in which every pixel is black). Syntax const mutedFlag = track.muted Value A Boolean which is true if the track is currently muted, or false if the track is currently unmuted. When possible, avoid polling muted to monitor the track's muting status. Instead, add event listeners for the mute and unmute events. Example This example counts the number of tracks in an array of MediaStreamTrack objects which are currently muted. let mutedCount = 0; trackList.forEach((track) => { if (track.mu...
MediaStreamTrack.remote - Web APIs
The MediaStreamTrack.remote read-only property allows Javascript to know whether a WebRTC MediaStreamTrack is from a remote source or a local one. It 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. Syntax var bool = track.remote; ...
MediaStreamTrackAudioSourceNode() - Web APIs
k (that is, its kind property isn't audio. Example This example uses getUserMedia() to obtain access to the user's camera, then creates a new MediaStreamAudioSourceNode from the first audio track provided by the device. ...
MediaStreamTrackAudioSourceNode - Web APIs
'pre'); var video = document.querySelector('video'); var myScript = document.querySelector('script'); var range = document.querySelector('input'); // getUserMedia block - grab stream // put it into a MediaStreamAudioSourceNode // also output the visuals into a video element if (navigator.mediaDevices) { console.log('getUserMedia supported.'); navigator.mediaDevices.getUserMedia ({audio: true, video: true}) .then(function(stream) { video.srcObject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // Create a MediaStreamAudioSourceNode // Feed the HTMLMediaElement into it var audioCtx = new AudioContext(); var source = audioCtx.createMediaStreamSource(stream); ...
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
iaStreamTrackAudioSourceNode will be taken. Example This example uses getUserMedia() to obtain access to the user's camera, then creates a new MediaStreamAudioSourceNode from the first audio track provided by the device. ...
MediaStream Image Capture API - Web APIs
is adapted from Chrome's Image Capture examples. First, get a reference to a device by calling MediaDevices.getUserMedia(). The example below simply says give me whatever video device is available, though the getUserMedia() method allows more specific capabilities to be requested. This method returns a Promise that resolves with a MediaStream object. navigator.mediaDevices.getUserMedia({ video: true }) .then(mediaStream => { // Do something with the stream. }) Next, isolate the visual part of the media stream. Do this by calling MediaStream.getVideoTracks(). This returns an array of MediaStreamTrack objects. The code below assumes that the first item in the MediaStreamTrack array is the one to use. You can use the properties of the MediaStreamTrack objects to select the one you nee...
Using the MediaStream Recording API - Web APIs
op = document.querySelector('.stop'); const soundClips = document.querySelector('.sound-clips'); Finally for this section, we set up the basic getUserMedia structure: if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { console.log('getUserMedia supported.'); navigator.mediaDevices.getUserMedia ( // constraints - only audio needed for this app { audio: true }) // Success callback .then(function(stream) { }) // Error callback .catch(function(err) { console.log('The following getUserMedia error occured: ' + err); } ); } else { console.log('getUserMedia not supported on your browser!'); } The whole thing is wrapped in a test that checks whether getUserMedia is supported before running anythi...
MediaTrackConstraints.autoGainControl - Web APIs
(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Automatic gain control is typically a feature provided by microphones, although it can be provided by other input sources as well. Syntax var constraintsObject = { autoGainControl: constraint }; constraintsObject.autoGainControl = constraint; Value If this value is 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. If, instead, the value is given as an object with an exact field, that field's Boolean value indicates a required setting for the automatic gain control feature; if it can't be met, then the request will result in an error. Exam...
MediaTrackConstraints.cursor - Web APIs
rned MediaTrackSettings object's cursor object. For example, if your app needs to alter the stream by inserting a representation of the cursor position if the stream doesn't include the rendered cursor, you can determine the need to do so by using code like this: let insertFakeCursorFlag = false; if (displayStream.getVideoTracks()[0].getSettings().cursor === "never") { insertFakeCursorFlag = true; } Following this code, insertFakeCursorFlag is true if there's no cursor rendered into the stream already. Later code can detect this flag's value and if it's true, can manually look at some metadata that might be provided and insert a fake representation of the cursor at the correct position. Examples Here are some example constraints objects for getDisplayMedia() that make use of the curso...
MediaTrackConstraints.echoCancellation - Web APIs
). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Because RTP doesn't include this information, tracks associated with a WebRTC RTCPeerConnection will never include this property. Syntax var constraintsObject = { echoCancellation: constraint }; constraintsObject.echoCancellation = constraint; Value If this value 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. If, instead, the value is given as an object with an exact field, that field's Boolean value indicates a required setting for the echo cancellation feature; if it can't be met, then the request will result in an error. Example See E...
MediaTrackConstraints.noiseSuppression - Web APIs
edConstraints(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Noise suppression is typically provided by microphones, although it can be provided by other input sources as well. Syntax var constraintsObject = { noiseSuppression: constraint }; constraintsObject.noiseSuppression = constraint; Value If this value is a simple 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. If, instead, the value is given as an object with an exact field, that field's Boolean value indicates a required setting for the noise suppression feature; if it can't be met, then the request will result in an error. Example See E...
MediaTrackSettings.autoGainControl - Web APIs
ine whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.autoGainControl as returned by a call to MediaDevices.getSupportedConstraints(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Syntax var autoGainControl = MediaTrackSettings.autoGainControl; Value A Boolean value which is true if the track has automatic gain control enabled or false if AGC is disabled. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Specifications Specification Status Comment Media Capture and StreamsThe definition of 'autoGainControl' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSettings.echoCancellation - Web APIs
y a call to MediaDevices.getSupportedConstraints(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Because RTP doesn't include this information, tracks associated with a WebRTC RTCPeerConnection will never include this property. Syntax var echoCancellation = MediaTrackSettings.echoCancellation; Value A Boolean value which is true if the track has echo cancellation functionality enabled or false if echo cancellation is disabled. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Specifications Specification Status Comment Media Capture and StreamsThe definition of 'echoCancellation' in that specification. Candidate Recommendation Initia...
MediaTrackSettings.noiseSuppression - Web APIs
whether or not this constraint is supported by checking the value of MediaTrackSupportedConstraints.noiseSuppression as returned by a call to MediaDevices.getSupportedConstraints(). However, typically this is unnecessary since browsers will simply ignore any constraints they're unfamiliar with. Syntax var noiseSuppression = MediaTrackSettings.noiseSuppression; Value A Boolean value which is true if the input track has noise suppression enabled or false if AGC is disabled. Example See Example: Constraint exerciser in Capabilities, constraints, and settings for an example. Specifications Specification Status Comment Media Capture and StreamsThe definition of 'noiseSuppression' in that specification. Candidate Recommendation Initial specification. ...
MediaTrackSupportedConstraints.aspectRatio - Web APIs
The MediaTrackSupportedConstraints dictionary's aspectRatio property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the aspectRatio constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax aspectConstraintSupported = supportedConstraintsDictionary.aspectRatio; Value This property is present in the dictionary (and its value is always true) if the user agent supports the aspectRatio constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and yo...
MediaTrackSupportedConstraints.channelCount - Web APIs
The MediaTrackSupportedConstraints dictionary's channelCount property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the channelCount constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax channelCountConstraintSupported = supportedConstraintsDictionary.channelCount; Value This property is present in the dictionary (and its value is always true) if the user agent supports the channelCount constraint. If the property isn't present, this property is missing from the supported constraints dictiona...
MediaTrackSupportedConstraints.cursor - Web APIs
The MediaTrackSupportedConstraints dictionary's cursor property indicates whether or not the cursor constraint is supported by the user agent and the device on which the content is being used. The supported constraints list is obtained by calling navigator.mediaDevices.getSupportedConstraints(). Syntax isCursorSupported = supportedConstraints.cursor; Value A Boolean value which is true if the cursor constraint is supported by the device and user agent. Example This method sets up the constraints object specifying the options for the call to getDisplayMedia(). It adds the cursor constraint only if it is known to be supported by the browser. Capturing is then started by calling getDisplayMedia() and attaching the returned stream to the video element referenced by the variable videoElem.
MediaTrackSupportedConstraints.deviceId - Web APIs
The MediaTrackSupportedConstraints dictionary's deviceId property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the deviceId constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax deviceIdConstraintSupported = supportedConstraintsDictionary.deviceId; Value This property is present in the dictionary (and its value is always true) if the user agent supports the deviceId constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get u...
MediaTrackSupportedConstraints.displaySurface - Web APIs
dConstraints dictionary's displaySurface property indicates whether or not the displaySurface constraint is supported by the user agent and the device on which the content is being used. The supported constraints list is obtained by calling navigator.mediaDevices.getSupportedConstraints(). Syntax isDisplaySurfaceSupported = supportedConstraints.displaySurface; Value A Boolean value which is true if the displaySurface constraint is supported by the device and user agent. Example This method sets up the constraints object specifying the options for the call to getDisplayMedia(). It adds the displaySurface constraint (requesting that only full-screen sharing be allowed) only if it is known to be supported by the browser. Capturing is then started by calling getDisplayMedia() and attaching...
MediaTrackSupportedConstraints.echoCancellation - Web APIs
The MediaTrackSupportedConstraints dictionary's echoCancellation property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the echoCancellation constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax echoCancellationConstraintSupported = supportedConstraintsDictionary.echoCancellation; Value This property is present in the dictionary (and its value is always true) if the user agent supports the echoCancellation constraint. If the property isn't present, this property is missing from the supported ...
MediaTrackSupportedConstraints.facingMode - Web APIs
The MediaTrackSupportedConstraints dictionary's facingMode property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the facingMode constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax facingModeConstraintSupported = supportedConstraintsDictionary.facingMode; Value This property is present in the dictionary (and its value is always true) if the user agent supports the facingMode constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and yo...
MediaTrackSupportedConstraints.groupId - Web APIs
The MediaTrackSupportedConstraints dictionary's groupId property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the groupId constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax groupIdConstraintSupported = supportedConstraintsDictionary.groupId; Value This property is present in the dictionary (and its value is always true) if the user agent supports the groupId constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefi...
MediaTrackSupportedConstraints.height - Web APIs
The MediaTrackSupportedConstraints dictionary's height property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the height constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax heightConstraintSupported = supportedConstraintsDictionary.height; Value This property is present in the dictionary (and its value is always true) if the user agent supports the height constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined i...
MediaTrackSupportedConstraints.latency - Web APIs
The MediaTrackSupportedConstraints dictionary's latency property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the latency constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax latencyConstraintSupported = supportedConstraintsDictionary.latency; Value This property is present in the dictionary (and its value is always true) if the user agent supports the latency constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefi...
MediaTrackSupportedConstraints.logicalSurface - Web APIs
dConstraints dictionary's logicalSurface property indicates whether or not the logicalSurface constraint is supported by the user agent and the device on which the content is being used. The supported constraints list is obtained by calling navigator.mediaDevices.getSupportedConstraints(). Syntax isLogicalSurfaceSupported = supportedConstraints.logicalSurface; Value A Boolean value which is true if the logicalSurface constraint is supported by the device and user agent. Example This method sets up the constraints object specifying the options for the call to getDisplayMedia(). It adds the logicalSurface constraint (requesting that only logical display surfaces--those which may not be entirely visible onscreen--be included among the options available to the user) only if it is known to ...
MediaTrackSupportedConstraints.sampleRate - Web APIs
The MediaTrackSupportedConstraints dictionary's sampleRate property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the sampleRate constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax sampleRateConstraintSupported = supportedConstraintsDictionary.sampleRate; Value This property is present in the dictionary (and its value is always true) if the user agent supports the sampleRate constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and yo...
MediaTrackSupportedConstraints.sampleSize - Web APIs
The MediaTrackSupportedConstraints dictionary's sampleSize property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the sampleSize constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax sampleSizeConstraintSupported = supportedConstraintsDictionary.sampleSize; Value This property is present in the dictionary (and its value is always true) if the user agent supports the sampleSize constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and yo...
MediaTrackSupportedConstraints.volume - Web APIs
The MediaTrackSupportedConstraints dictionary's volume property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the volume constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax volumeConstraintSupported = supportedConstraintsDictionary.volume; Value This property is present in the dictionary (and its value is always true) if the user agent supports the volume constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined...
MediaTrackSupportedConstraints.width - Web APIs
The MediaTrackSupportedConstraints dictionary's width property is a read-only Boolean value which is present (and set to true) in the object returned by MediaDevices.getSupportedConstraints() if and only if the user agent supports the width constraint. If the constraint isn't supported, it's not included in the list, so this value will never be false. You can access the supported constraints dictionary by calling navigator.mediaDevices.getSupportedConstraints(). Syntax widthConstraintSupported = supportedConstraintsDictionary.width; Value This property is present in the dictionary (and its value is always true) if the user agent supports the width constraint. If the property isn't present, this property is missing from the supported constraints dictionary, and you'll get undefined if you...
Capabilities, constraints, and settings - Web APIs
ated constraint set. Getting the current settings for a track Unless you only use exact constraints (which is pretty restrictive, so be sure you mean it!), there's no guarantee exactly what you're going to actually get after the constraints are applied. The values of the constrainable properties as they actually are in the resulting media are referred to as the settings. If you need to know the true format and other properties of the media, you can obtain those settings by calling MediaStreamTrack.getSettings(). This returns an object based on the dictionary MediaTrackSettings. For example: function whichCamera(track) { return track.getSettings().facingMode; } This function uses getSettings() to obtain the track's currently in-use values for the constrainable properties and returns the v...
Microdata DOM API - Web APIs
be used by other applications. The document.getItems(typeNames) method provides access to the top-level microdata items. It returns a NodeList containing the items with the specified types, or all types if no argument is specified. Each item is represented in the DOM by the element on which the relevant itemscope attribute is found. These elements have their element.itemScope IDL attribute set to true. The type(s) of items can be obtained using the element.itemType IDL attribute on the element with the itemscope attribute. Methods document . getItems( [ types ] ) Returns a NodeList of the elements in the Document that create items, that are not part of other items, and that are of the types given in the argument, if any are listed. The types argument is interpreted as a space-separated lis...
MouseEvent.altKey - Web APIs
Web › API › MouseEvent › altKey
hen a given mouse event occurs. Be aware that the browser can't always detect the alt key on some operating systems. On some Linux variants, for example, a left mouse click combined with the alt key is used to move or resize windows. Note: On Macintosh keyboards, this key is also known as the option key. Syntax var altKeyPressed = instanceOfMouseEvent.altKey Return value A Boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. Example This example logs the altKey property when you trigger a click event. HTML <p>Click anywhere to test the <code>altKey</code> property.</p> <p id="log"></p> JavaScript let log = document.querySelector('#log'); document.addEventListener('click', logKey); function logKey(e) { log.textContent = `The a...
MouseEvent.ctrlKey - Web APIs
Example This example logs the ctrlKey property when you trigger a click event. ...
MouseEvent.getModifierState() - Web APIs
See the document of KeyboardEvent.getModifierState() for details. Syntax var active = event.getModifierState(keyArg); Returns A Boolean Parameters keyArg A modifier key value. The value must be one of the KeyboardEvent.key values which represent modifier keys or "Accel". This is case-sensitive. ...
MouseEvent.metaKey - Web APIs
rating systems bind special functionality to the meta key, so this property may be false even when the key is actually pressed. On Windows, for example, this key may open the Start menu. Note: On Macintosh keyboards, this key is the command key (?). On Windows keyboards, this key is the Windows key (?). Syntax var metaKeyPressed = instanceOfMouseEvent.metaKey Return value A Boolean, where true indicates that the key is pressed, and false indicates that the key is not pressed. Example This example logs the metaKey property when you trigger a click event. HTML <p>Click anywhere to test the <code>metaKey</code> property.</p> <p id="log"></p> JavaScript let log = document.querySelector('#log'); document.addEventListener('click', logKey); function logKey(e) { log.textContent = `The...
MouseEvent.shiftKey - Web APIs
Example This example logs the shiftKey property when you trigger a click event. ...
msPlayToDisabled - Web APIs
ot work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. msPlayToDisabled is a read/write property which gets and sets if the PlayTo device is enabled or disabled. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax ptr = object.msPlayToDisabled; Value Boolean value set to true indicates that the PlayTo device is disabled. The msPlayToDisabled attribute extends the HTMLEmbedElement, HTMLImageElement, HTMLMediaElement, and HTMLObject interfaces. ...
msPlayToPrimary - Web APIs
e Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. msPlayToPrimary is a read/write property which gets or sets the primary DLNA PlayTo device. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax ptr = object.msPlayToPrimary; Value Boolean value set to true indicates that the device is the primary DLNA PlayTo device, otherwise false. Example // Microsoft extensions interface HTMLImageElement : HTMLElement { attribute boolean msPlayToDisabled; attribute boolean msPlayToPrimary; attribute DOMString msPlayToPreferredSourceUri; }; See also HTMLMediaElement ...
msRealTime - Web APIs
for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. msRealTime is a read/write property which specifies whether or not to enable low-latency playback on the media element. This proprietary property is specific to Internet Explorer and Microsoft Edge. Syntax ptr = object.msRealTime; Value Boolean value set to true indicates that low-latency playback will be enabled on the media element. Low-latency playback is useful in communication and some gaming scenarios, but is more demanding on power consumption and less reliable for smooth media playback. You must set the msRealTime before setting the src property in code. msRealTime should not be used in non-real-time or non-communication scenarios, such as audi...
MutationObserver.disconnect() - Web APIs
Usage notes If the element being observed is removed from the DOM, and then subsequently released by the browser's garbage collection mechanism, the MutationObserver is likewise deleted. Example This example creates an observer, then disconnects from it, leaving it available for possible reuse. const targetNode = document.querySelector("#someElement"); const observerOptions = { childList: true, attributes: true } const observer = new MutationObserver(callback); observer.observe(targetNode, observerOptions); /* some time later... */ observer.disconnect(); Specifications Specification Status Comment DOMThe definition of 'MutationObserver.disconnect()' in that specification. Living Standard ...
MutationObserver.takeRecords() - Web APIs
. Note: The queue of mutations which have occurred, but not been delivered to the observer's callback is left empty after calling takeRecords(). Example In this example, we demonstrate how to handle any undelivered MutationRecords by calling takeRecords() just before disconnecting the observer. const targetNode = document.querySelector("#someElement"); const observerOptions = { childList: true, attributes: true } const observer = new MutationObserver(callback); observer.observe(targetNode, observerOptions); /* ...later, when it's time to stop observing... */ /* handle any still-pending mutations */ let mutations = observer.takeRecords(); observer.disconnect(); if (mutations) { callback(mutations); } The code in lines 12-17 fetches any unprocessed mutation records, then invo...
MutationRecord - Web APIs
MutationRecord.oldValue String The return value depends on the MutationRecord.type. For attributes, it is the value of the changed attribute before the change. For characterData, it is the data of the changed node before the change. For childList, it is null. Note that for this to work as expected, attributeOldValue or characterDataOldValue must be set to true in the corresponding MutationObserverInit parameter of the MutationObserver observe method Specifications Specification Status Comment DOMThe definition of 'MutationRecord' in that specification. Living Standard ...
NDEFReader.scan() - Web APIs
Web › API › NDEFReader › scan
ord.id. recordType -- the match pattern for matching each NDEFRecord.recordType. mediaType -- the match pattern for matching each NDEFRecord.mediaType. signal -- optional AbortSignal that allows to cancell this scan() operation. Return value A Promise that resolves with undefined immediatelly after scheduling read operations for the NFC adapter. Exceptions This method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a DOMException whose name is one of the following: AbortError The scan operation was aborted with AbortSignal passed in options. NotAllowedError The permission for this operation was rejected. NotSupportedError There is no NFC adapter compatible with Web NFC, or a connection can not be established. Specifications ...
NDEFWriter.write() - Web APIs
Web › API › NDEFWriter › write
ated reader objects. Will be ignored if overwrite is false. overwrite -- Boolean specifying whether or not existing record should be overwritten, if such exists. signal -- optional AbortSignal that allows to cancell this write operation. Return value A Promise that resolves with undefined when and if the message transfer is successfully completed. Exceptions This method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a DOMException whose name is one of the following: AbortError The write operation was aborted with AbortSignal passed in options. NotAllowedError The permission for this operation was rejected or overwrite is false and there are already records on the tag. NotSupportedError There is no NFC adapter compatible with Web NF...
Navigator.credentials - Web APIs
to request credentials. The CredentialsContainer interface also notifies the user agent when an interesting event occurs, such as a successful sign-in or sign-out. This interface can be used for feature detection. Syntax var credentialsContainer = navigator.credentials Value The CredentialsContainer interface. Example if ('credentials' in navigator) { navigator.credentials.get({password: true}) .then(function(creds) { //Do something with the credentials. }); } else { //Handle sign-in the way you did before. }; Specifications Specification Status Comment Credential Management Level 1 Working Draft Initial definition. ...
Navigator.getBattery() - Web APIs
and sample code. Note: In some browsers access to this feature is controlled by Feature-Policy directive battery. Syntax var batteryPromise = navigator.getBattery(); Return value A Promise which, when resolved, calls its fulfillment handler with a single parameter: a BatteryManager object which you can use to get information about the battery's state. Exceptions This method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a DOMException whose name is one of the following: SecurityError The User Agent does not expose battery information to insecure contexts and this method was called from insecure context. Note: Old versions of some User Agents might allow use of this feature in insecure contexts. NotAllowedError Note: No User Agent curren...
Navigator.getUserMedia() - Web APIs
cope with various browsers' prefixes. Note that this is the deprecated way of doing it: See the Examples section under the MediaDevices.getUserMedia() for modern examples. ...
Navigator.mozIsLocallyAvailable() - Web APIs
termine whether or not a given resource is available. Note: Security exceptions can occur if the requested URI is not from the same origin. Syntax navigator.mozIsLocallyAvailable(uri, ifOffline); Parameters uri The URI of the resource whose availability is to be checked, as a string. ifOffline Allows you to specify whether or not the offline resources cache should be checked; specify true to consider the offline resources cache. Example var available = navigator.mozIsLocallyAvailable("my-image-file.png", true); if (available) { /* the offline resource is present */ } else { console.log("Certain needed resources are not available offline"); } Specifications Not part of any specifications. ...
msSaveBlob - Web APIs
The Navigator.msSaveBlob() method saves the File or Blob to disk. This method behaves in the same way as Navigator.msSaveOrOpenBlob() except that this disables the file open option. Syntax navigator.msSaveBlob(blob, defaultName); Parameters blob A blob to be saved. defaultName The file name to be used when saving file. Return value True is returned as long as the download notification bar is displayed, or false if a failure occured. Notes When a site calls this method, the behavior is the same as when Windows Internet Explorer downloads a file with the following in the header, where X-Download-Options removes the file open button from the browser file download dialog: Content-Length: <blob.size> Content-Type: <blob.type> Content-Disposition: attachment;filename=...
msSaveOrOpenBlob - Web APIs
The Navigator.msSaveOrOpenBlob() method saves the File or Blob to disk. This method behaves in the same way as Navigator.msSaveBlob() except that this enables the file open option. Syntax navigator.msSaveOrOpenBlob(blob, defaultName); Parameters blob A blob to be saved. defaultName The file name to be used when saving file. Return value True is returned as long as the download notification bar is displayed, or false if a failure occurred. Notes When a site calls this method, the behavior is the same as when Windows Internet Explorer downloads a file with the following in the header: Content-Length: <blob.size> Content-Type: <blob.type> Content-Disposition: attachment;filename=<defaultName> Specifications Not part of any specifications. ...
Navigator.oscpu - Web APIs
Web › API › Navigator › oscpu
Specifications Specification Status Comment HTML Living StandardThe definition of 'NavigatorID: oscpu' in that specification. Living Standard Initial definition ...
Navigator.sendBeacon() - Web APIs
navigator.sendBeacon() method asynchronously sends a small amount of data over HTTP to a web server. Syntax navigator.sendBeacon(url, data); Parameters url The URL that will receive the data. Can be relative or absolute. data A ArrayBuffer, ArrayBufferView, Blob, DOMString, FormData, or URLSearchParams object containing the data to send. Return values The sendBeacon() method returns true if the user agent successfully queued the data for transfer. Otherwise, it returns false. Description This method is for analytics and diagnostics that send data to a server before the document is unloaded, where sending the data any sooner may miss some possible data collection. For example, which link the user clicked before navigating away and unloading the page. Ensuring that data has been...
Navigator.vibrate() - Web APIs
Web › API › Navigator › vibrate
r.vibrate() method pulses the vibration hardware on the device, if such hardware exists. If the device doesn't support vibration, this method has no effect. If a vibration pattern is already in progress when this method is called, the previous pattern is halted and the new one begins instead. If the method was unable to vibrate because of invalid parameters, it will return false, else it returns true. If the pattern leads to a too long vibration, it is truncated: the max length depends on the implementation. Syntax var successBool = window.navigator.vibrate(pattern); pattern Provides a pattern of vibration and pause intervals. Each value indicates a number of milliseconds to vibrate or pause, in alternation. You may provide either a single value (to vibrate once for that many milliseco...
Online and offline events - Web APIs
gain. Effectively, the requirements break down as such: You need to know when the user comes back online, so that you can re-synchronize with the server. You need to know when the user is offline, so that you can queue your server requests for a later time. It is this process that online/offline events help to simplify. API navigator.onLine navigator.onLine is a property that maintains a true/false value (true for online, false for offline). This property is updated whenever the user switches into "Offline Mode" by selecting the corresponding menu item (File -> Work Offline in Firefox). Additionally, this property should update whenever a browser is no longer capable of connecting to the network. According to the specification: The navigator.onLine attribute must return false if the...
NetworkInformation.saveData - Web APIs
The NetworkInformation.saveData read-only property of the NetworkInformation interface returns true if the user has set a reduced data usage option on the user agent. Syntax var saveData = NetworkInformation.saveData; Value A Boolean. Specifications Specification Save Data API ...
NetworkInformation - Web APIs
the effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'. This value is determined using a combination of recently observed round-trip time and downlink values. NetworkInformation.rtt Read only Returns the estimated effective round-trip time of the current connection, rounded to the nearest multiple of 25 milliseconds. NetworkInformation.saveData Read only Returns true if the user has set a reduced data usage option on the user agent. NetworkInformation.type Read only Returns the type of connection a device is using to communicate with the network. It will be one of the following values: bluetooth cellular ethernet none wifi wimax other unknown Event handlers NetworkInformation.onchange The event that's fired when connection infor...
Network Information API - Web APIs
loadVideo flag is set to false. For simplicity and clarity, this example only tests for one connection type. A real-world use case would likely use a switch statement or some other method to check all of the possible values of NetworkInformation.type. Regardless of the type value you can get an estimate of connection speed through the NetworkInformation.effectiveType property. ...
Node.hasChildNodes() - Web APIs
The Node.hasChildNodes() method returns a Boolean value indicating whether the given Node has child nodes or not. Syntax bool = node.hasChildNodes(); Return value A Boolean that is true if the node has child nodes, and false otherwise. Example let foo = document.getElementById('foo'); if (foo.hasChildNodes()) { // Do something with 'foo.childNodes' } Polyfill Here is one possible polyfill: ;(function(prototype) { prototype.hasChildNodes = prototype.hasChildNodes || function() { return !!this.firstChild; } })(Node.prototype); There are various ways to determine whether the node has a child node: node.hasChildNodes() node.firstChild != null (or just node.firstChild) node.childNodes && node.childNodes.length (or node.childNodes.length > 0) Specifications S...
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. Syntax result = node.isDefaultNamespace(namespaceURI); Parameters namespaceURI is a string representing the namespace against which the element will be checked. Return value result is a Boolean that holds the return value true or false. Example var XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var el = document.getElementsByTagNameNS(XULNS, 'textbox')[0]; alert(el.isDefaultNamespace(XULNS)); // true Specifications Specification Status Comment DOMThe definition of 'Node: isDefaultNamespace' in that specification. Living Standard ...
Node.isSupported() - Web APIs
Web › API › Node › isSupported
be passed to the method hasFeature on DOMImplementation. Possible values defined within the core DOM specification are listed on the DOM Level 2 Conformance Section. version Is a DOMString containing the version number of the feature to test. In DOM Level 2, version 1, this is the string 2.0. If the version is not specified, supporting any version of the feature will cause the method to return true. Example <div id="doc"> </div> <script> // Get an element and check to see if its supports the DOM2 HTML Module. var main = document.getElementById('doc'); var output = main.isSupported('HTML', '2.0'); </script> Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.isSupported()' in that spec...
Node.setUserData() - Web APIs
Web › API › Node › setUserData
ted to userKey on this node will be removed. Example var d = document.implementation.createDocument('', 'test', null); d.documentElement.setUserData('key', 15, {handle:function (o, k, d, s, ds) {console.log(o+'::'+k+'::'+d+'::'+s+'::'+ds)}}); // 2::key::15::[object Element]::[object Element] console.log(d.documentElement.getUserData('key')); // 15 var e = document.importNode(d.documentElement, true); // causes handler to be called console.log(e.getUserData('key')); // null since user data is not copied Specifications Specification Status Comment Document Object Model (DOM) Level 3 Core SpecificationThe definition of 'Node.setUserData()' in that specification. Obsolete Initial definition ...
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. Living Standard Initial definition. ...
NodeIterator - Web APIs
pandEntityReferences Read only Is a Boolean indicating if, when discarding an EntityReference its whole sub-tree must be discarded at the same time. NodeIterator.referenceNode Read only Returns the Node to which the iterator is anchored. 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. Methods This interface doesn't inherit any method. NodeIterator.detach() This operation is a no-op. It doesn't do anything. Previously it was telling the engine that the NodeIterator was no more used, but this is now useless. NodeIterator.previousNode() Returns the previous Node in the document, or null if there are none. NodeIterator.
NonDocumentTypeChildNode.nextElementSibling - Web APIs
urn e; } }); } Polyfill for Internet Explorer 9+ and Safari // Source: https://github.com/jserz/js_piece/blob/master/DOM/NonDocumentTypeChildNode/nextElementSibling/nextElementSibling.md (function (arr) { arr.forEach(function (item) { if (item.hasOwnProperty('nextElementSibling')) { return; } Object.defineProperty(item, 'nextElementSibling', { configurable: true, enumerable: true, get: function () { var el = this; while (el = el.nextSibling) { if (el.nodeType === 1) { return el; } } return null; }, set: undefined }); }); })([Element.prototype, CharacterData.prototype]); Specifications Specification Status Comment DOMThe definition of ...
NonDocumentTypeChildNode.previousElementSibling - Web APIs
} }); } Polyfill for Internet Explorer 9+ and Safari // Source: https://github.com/jserz/js_piece/blob/master/DOM/NonDocumentTypeChildNode/previousElementSibling/previousElementSibling.md (function (arr) { arr.forEach(function (item) { if (item.hasOwnProperty('previousElementSibling')) { return; } Object.defineProperty(item, 'previousElementSibling', { configurable: true, enumerable: true, get: function () { let el = this; while (el = el.previousSibling) { if (el.nodeType === 1) { return el; } } return null; }, set: undefined }); }); })([Element.prototype, CharacterData.prototype]); Specifications Specification Status Comment DOMThe definition o...
Notification.requireInteraction - Web APIs
Note: This feature is available in Web Workers. The requireInteraction read-only property of the Notification interface returns a Boolean indicating that a notification should remain active until the user clicks or dismisses it, rather than closing automatically. Note: This can be set when the notification is first created by setting the requireInteraction option to true in the options object of the Notification.Notification() constructor. Syntax function spawnNotification(theTitle,theBody,shouldRequireInteraction) { var options = { body: theBody, requireInteraction: shouldRequireInteraction } var n = new Notification(theTitle,options); } Value A Boolean. Specifications Specification Status Comment Notifications APIThe definition of ...
Using the Notifications API - Web APIs
he load event handler (see issue 274284). Feature-detecting the requestPermission() promise Above we said that we had to check whether the browser supports the promise version of Notification.requestPermission(). We did this using the following: function checkNotificationPromise() { try { Notification.requestPermission().then(); } catch(e) { return false; } return true; } We basically try to see if the .then() method is available on requestPermission(). If so, we move on and return true. If it fails, we return false in the catch() {} block. Creating a notification Creating a notification is easy; just use the Notification constructor. This constructor expects a title to display within the notification and some options to enhance the notification such as an...
OES_vertex_array_object - Web APIs
e gl.getParameter() method: ext.VERTEX_ARRAY_BINDING_OES Returns a WebGLVertexArrayObject object when used in the gl.getParameter() method as the pname parameter. Methods This extension exposes four new methods. ext.createVertexArrayOES() Creates a new WebGLVertexArrayObject. ext.deleteVertexArrayOES() Deletes a given WebGLVertexArrayObject. ext.isVertexArrayOES() Returns true if a given object is a WebGLVertexArrayObject. ext.bindVertexArrayOES() Binds a given WebGLVertexArrayObject to the buffer. Examples var oes_vao_ext = gl.getExtension('OES_vertex_array_object'); var vao = oes_vao_ext.createVertexArrayOES(); oes_vao_ext.bindVertexArrayOES(vao); // ... // calls to bindBuffer or vertexAttribPointer // which will be "recorded" in the VAO // ... Specific...
OfflineAudioContext.startRendering() - Web APIs
rce code too.) // define online and offline audio context var audioCtx = new AudioContext(); var offlineCtx = new OfflineAudioContext(2,44100*40,44100); source = offlineCtx.createBufferSource(); // use XHR to load an audio track, and // decodeAudioData to decode it and OfflineAudioContext to render it function getData() { request = new XMLHttpRequest(); request.open('GET', 'viper.ogg', true); request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { myBuffer = buffer; source.buffer = myBuffer; source.connect(offlineCtx.destination); source.start(); //source.loop = true; offlineCtx.startRendering().then(function(renderedBuffer) { ...
OfflineAudioContext - Web APIs
rce code too.) // define online and offline audio context var audioCtx = new AudioContext(); var offlineCtx = new OfflineAudioContext(2,44100*40,44100); source = offlineCtx.createBufferSource(); // use XHR to load an audio track, and // decodeAudioData to decode it and OfflineAudioContext to render it function getData() { request = new XMLHttpRequest(); request.open('GET', 'viper.ogg', true); request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { myBuffer = buffer; source.buffer = myBuffer; source.connect(offlineCtx.destination); source.start(); //source.loop = true; offlineCtx.startRendering().then(function(renderedBuffer) { ...
Page Visibility API - Web APIs
oElement.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. Document.visibilityState Read only A DOMString indicating the document's current visibility state. Possible values are: visible The page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window. hidden The page's content is not vis...
PaymentCurrencyAmount.value - Web APIs
Specifications Specification Status Comment Payment Request APIThe definition of 'PaymentCurrencyAmount.value' in that specification. Candidate Recommendation ...
PaymentDetailsUpdate.error - Web APIs
r message to be displayed if the specified information doesn't offer any valid shipping options. Syntax errorString = paymentDetailsUpdate.error; paymentDetailsUpdate.error = errorString; Value A DOMString specifying the string to display to the user if the information specified in the PaymentDetailsUpdate doesn't provide any valid shipping options. This happens if both of the following are true: The PaymentRequest specifies using its requestShipping property that shipping information is required. The PaymentDetailsUpdate object specifies no valid shipping options in its shippingOptions list. This message can be used to explain to the user why they cannot submit their payment as currently specified--whether that's because the selected products cannot be shipped to their region or b...
PaymentItem - Web APIs
tax or other charge. Properties amount Secure context A PaymentCurrencyAmount object describing the monetary value of the item. label Secure context A string specifying a human-readable name or description of the item or service being charged for. This may be displayed to the user by the user agent, depending on the design of the interface. pending Secure context A Boolean value which is true if the specified amount has not yet been finalized. This can be used to show items such as shipping or tax amounts that depend upon the selection of shipping address, shipping option, or so forth. The user agent may show this information but is not required to do so. Specifications Specification Status Comment Payment Request APIThe definition of 'PaymentItem' in that s...
PaymentRequest: paymentmethodchange event - Web APIs
calls show() to present the payment interface to the user. The code assumes the existence of a method detailsForShipping(), which returns a PaymentDetailsUpdate object containing the shipping options for the ground shipping method, in the form found in the PaymentShippingOption dictionary. By doing so, the payment form defaults to the ground shipping method. ...
PaymentRequest.show() - Web APIs
If and only if every field is valid, the complete() method is called on the response with the string "success", which indicates that everything is valid and that the payment can complete accordingly. If any fields have unacceptable values, or if an exception is thrown by the previous code, complete() is called with the string "fail", which indicat...
PaymentRequest - Web APIs
identifier for a particular PaymentRequest, which can be set via details.id. When none is set, it defaults to a UUID. PaymentRequest.shippingAddress Read only Secure context If requested via payment options, returns the shipping address chosen by the user for the purposes of calculating shipping. This property is only populated if the constructor is called with the requestShipping flag set to true. Additionally, in some browsers, the parts of the address will be redacted for privacy until the user indicates they are ready to complete the transaction (i.e., they hit "Pay"). PaymentRequest.shippingOption Read only Secure context Returns the identifier of the selected shipping option. This property is only populated if the constructor is called with the requestShipping flag set to true. P...
PayerResponse.payerPhone - Web APIs
The payerPhone read-only property of the PaymentResponse interface returns the phone number supplied by the user. This option is only present when the requestPayerPhone option is set to true in the PaymentOptions object passed to the PaymentRequest constructor. Syntax var payerPhone = PaymentResponse.payerPhone; Specifications Specification Status Comment Payment Request API Candidate Recommendation Initial definition. ...
PeriodicWave - Web APIs
hods. Example The following example illustrates simple usage of createPeriodicWave(), to create a PeriodicWave object containing a simple sine wave. var real = new Float32Array(2); var imag = new Float32Array(2); var ac = new AudioContext(); var osc = ac.createOscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createPeriodicWave(real, imag, {disableNormalization: true}); osc.setPeriodicWave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); This works because a sound that contains only a fundamental tone is by definition a sine wave Here, we create a PeriodicWave with two values. The first value is the DC offset, which is the value at which the oscillator starts. 0 is good here, because we want to start the curve at the middle of the [-1.0; 1.0...
Permissions.query() - Web APIs
Web › API › Permissions › query
sage or be able to send silent push notifications. The default is false. sysex: (Midi only) Indicates whether you need and/or receive system exclusive messages. The default is false. Note: As of Firefox 44, the permissions for Notifications and Push have been merged. If permission is granted (e.g. by the user, in the relevant permissions dialog), navigator.permissions.query() will return true for both notifications and push. Note: The persistent-storage permission allows an origin to use a persistent box (i.e persistent storage) for its storage, as per the Storage API. Returns A Promise that resolves to a PermissionStatus object. Exceptions Exception Explanation TypeError Retrieving the PermissionDescriptor information failed in some way, or the per...
Permissions.revoke() - Web APIs
sage or be able to send silent push notifications. The default is false. sysex: (MIDI only) Indicates whether you need and/or receive system exclusive messages. The default is false. Note: As of Firefox 44, the permissions for Notifications and Push have been merged. If permission is granted (e.g. by the user, in the relevant permissions dialog), navigator.permissions.query() will return true for both notifications and push. Note: The persistent-storage permission allows an origin to use a persistent box (i.e persistent storage) for its storage, as per the Storage API. Returns A Promise that calls its fulfillment handler with a PermissionStatus object indicating the result of the request. Exceptions TypeError Retrieving the PermissionDescriptor information failed in some wa...
PhotoCapabilities - Web APIs
tracted from Chrome's Image Capture / Photo Resolution Sample, uses the results from getPhotoCapabilities() to modify the size of an input range. This example also shows how the ImageCapture object is created using a MediaStreamTrack retrieved from a device's MediaStream. ...
PointerEvent.getCoalescedEvents() - Web APIs
To change preferences in Firefox, visit about:config.Opera Android Full support 43Safari iOS No support NoSamsung Internet Android Full support 7.0Legend Full support Full support ...
Pointer Lock API - Web APIs
If you lock one iframe, you cannot try to lock another iframe and transfer the target to it; pointer lock will error out. To avoid this limitation, first unlock the locked iframe, and then lock the other. While iframes work by default, "sandboxed" iframes block Pointer lock. The ability to avoid this limitati...
Multi-touch interaction - Web APIs
t.style.background = "pink"; break; default: // Three or more simultaneous touches ev.target.style.background = "lightblue"; } } Event logging These functions are used send to event activity to the application window (to support debugging and learning about the event flow). ...
Pinch zoom gestures - Web APIs
che.length; i++) { if (evCache[i].pointerId == ev.pointerId) { evCache.splice(i, 1); break; } } } Event logging These functions are used to send event activity to the application's window (to support debugging and learning about the event flow). ...
PositionOptions.enableHighAccuracy - Web APIs
Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile device for example). 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. ...
PositionOptions - Web APIs
The PositionOptions dictionary describes an object containing option properties to pass as a parameter of Geolocation.getCurrentPosition() and Geolocation.watchPosition(). Properties PositionOptions.enableHighAccuracy Secure context Is a Boolean that indicates the application would like to receive the best possible results. If true and if the device is able to provide a more accurate position, it will do so. Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile device for example). On the other hand, if false, the device can take the liberty to save resources by responding more quickly and/or using less power. Default: false. PositionOptions.timeout Secure context Is a positive long value representing the maximum length...
ProgressEvent.initProgressEvent() - Web APIs
The operation has started. progress The operation still is in progress. error The operation failed and didn't complete. abort The operation was cancelled and didn't complete. load The operation completed. loadend The operation stopped. 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). lengthComputable Is a Boolean flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not. loaded Is an unsigned long long representing th...
PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() - Web APIs
isUserVerifyingPlatformAuthenticatorAvailable() is a static method of the PublicKeyCredential interface that returns a Promise which resolves to true if a user-verifying platform authenticator is available. A user-verifying platform authenticator is a kind of multi-factor authenticator that is part of the client device (it is generally not removable) and that involves an action from the user in order to identify them. At the time of this writing, this method's result only resolves to true on Windows when Windows Hello capabilities are available (on recent versions of this OS). Note: This method may only be used in top-level contexts and will not be available in an <iframe> for example. Syntax PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable() Parameters None. Retu...
PublicKeyCredential - Web APIs
se if the PublicKeyCredential was the result of a navigator.credentials.get() call. Methods PublicKeyCredential.getClientExtensionResults()Secure context If any extensions were requested, this method will return the results of processing those extensions. PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()Secure context A static method returning a Promise which resolves to true if an authenticator bound to the platform is capable of verifying the user. With the current state of implementation, this method only resolves to true when Windows Hello is available on the system. Examples Creating a new instance of PublicKeyCredential Here, we use navigator.credentials.create() to generate a new credential. var publicKey = { challenge: /* from the server */, rp: { ...
PublicKeyCredentialRequestOptions - Web APIs
mple.com */ userVerification: "preferred", timeout: 60000, // Wait for a minute allowCredentials: [ { transports: "usb", type: "public-key", id: new Uint8Array(26) // actually provided by the server }, { transports: "internal", type: "public-key", id: new Uint8Array(26) // actually provided by the server } ], extensions: { uvm: true, // RP wants to know how the user was verified loc: false, txAuthSimple: "Could you please verify yourself?" } }; navigator.credentials.get({ "publicKey": options }) .then(function (credentialInfoAssertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); Specification...
PushManager.getSubscription() - Web APIs
Working Draft Initial definition. ...
PushManager.subscribe() - Web APIs
ion(event) { console.log(event.data); // From here we can write the data to IndexedDB, send it to any open // windows, display a notification, etc. } navigator.serviceWorker.register('serviceworker.js'); // Use serviceWorker.ready to ensure that you can subscribe for push navigator.serviceWorker.ready.then( function(serviceWorkerRegistration) { var options = { userVisibleOnly: true, applicationServerKey: applicationServerKey }; serviceWorkerRegistration.pushManager.subscribe(options).then( function(pushSubscription) { console.log(pushSubscription.endpoint); // The push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an XMLHttpRequest. }, functio...
PushSubscription.endpoint - Web APIs
d a push message to the particular service worker instance that subscribed to the push service. For this reason, it is a good idea to keep your endpoint a secret, so others do not hijack it and abuse the push functionality. Syntax var myEnd = pushSubscription.endpoint; Value A USVString. Example navigator.serviceWorker.ready.then(function(reg) { reg.pushManager.subscribe({userVisibleOnly: true}).then(function(subscription) { console.log(subscription.endpoint); // At this point you would most likely send the subscription // endpoint to your server, save it, then use it to send a // push message at a later date }) }) Specifications Specification Status Comment Push APIThe definition of 'endPoint' in that specification. Working Draft ...
PushSubscription.getKey() - Web APIs
h subscribes / unsubscribes from // push messages. subBtn.disabled = false; if (!subscription) { console.log('Not yet subscribed to Push') // We aren't subscribed to push, so set UI // to allow the user to enable push return; } // Set your UI to show they have subscribed for // push messages subBtn.textContent = 'Unsubscribe from Push Messaging'; isPushEnabled = true; // initialize status, which includes setting UI elements for subscribed status // and updating Subscribers list via push var endpoint = subscription.endpoint; var key = subscription.getKey('p256dh'); var auth = subscription.getKey('auth'); ... Specifications Specification Status Comment Push API Working Draft This is the Push API spec, but note tha...
RTCDataChannel.id - Web APIs
Web › API › RTCDataChannel › id
Each RTCPeerConnection can therefore have up to a theoretical maximum of 65,534 data channels on it, although the actual maximum may vary from browser to browser. ...
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. See Creating a data channel in Using WebRTC data channels for further information about this property. 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. Example The code snippet below checks the value of negotiated; if it's true, a function called shutdownRemoteChannel() is called with the channel's id; presumably this would be implemented to transmit a shutdown signal to the remote peer prior to terminating the connection. if (dataChan...
RTCDataChannel.onclose - Web APIs
d the send button are only enabled for use when the connection is actually open. 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... */ Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCDataChannel.onclose' in that specification. Candidate Recommendation Initial specification. ...
RTCDataChannel.ordered - Web APIs
The read-only RTCDataChannel property ordered indicates whether or not the data channel guarantees in-order delivery of messages; the default is true, which indicates that the data channel is indeed ordered. This is set when the RTCDataChannel is created, by setting the ordered property on the RTCDataChannelInit object passed as RTCPeerConnection.createDataChannel()'s options parameter. Syntax var ordered = aDataChannel.ordered; A Boolean value which is true if in-order delivery is guaranteed and is otherwise false. Example var pc = new RTCPeerConnection(); var dc = pc.createDataChannel("my channel"); if (!dc.ordered) { // Handle unordered messaging } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe d...
RTCDataChannel.reliable - Web APIs
The read-only RTCDataChannel property reliable indicates whether or not the data channel is reliable. This property is obsolete. Use RTCDataChannel.ordered instead in any new code, and update existing code as soon as possible. Syntax var reliable = aDataChannel.reliable; Value true if the RTCDataChannel's connection is reliable; false if it isn't. Example // TBD Specifications No longer part of any specification. ...
RTCDataChannel.stream - Web APIs
The deprecated (and never part of the official specification) read-only RTCDataChannel property stream returns an ID number (between 0 and 65,535) which uniquely identifies the RTCDataChannel. This ID is set at the time the data channel is created, either by the user agent (if RTCDataChannel.negotiated is false) or by the site or app script (if negotiated is true). This property has been replaced with the RTCDataChannel.id property. If you have code that uses stream, you will need to update, since browsers have begun to remove support for stream. Syntax var stream = aDataChannel.stream; Value An unsigned short value (that is, an integer between 0 and 65,535) which uniquely identifies the data channel. Example var dataChannel = pc.createDataChannel("SampleChannel"); console.log("...
RTCIceCandidate.address - Web APIs
ndidate.address; Value A DOMString providing the IP address from which the candidate comes. Note: If port is null -- and port is supported by the user agent -- passing the candidate to addIceCandidate() will fail, throwing an OperationError exception. Security notes It's important to note here that although WebRTC does not require the two peers on an RTCPeerConnection to know one another's true IP addresses, the address property on RTCIceCandidate can expose more information about the source of the remote peer than the user expects. The IP address can be used to derive information about the remote device's location, network topology, and so forth. It can also be used for fingerprinting purposes. The candidate IP addresses are always exposed to the application through address, and unsav...
RTCIceCandidate.type - Web APIs
nd-type field. Syntax var type = RTCIceCandidate.type; Value A DOMString whose value is one of those defined by the RTCIceCandidateType enumerated type. These candidate types are listed in order of priority; the higher in the list they are, the more efficient they are. host The candidate is a host candidate, whose IP address as specified in the RTCIceCandidate.ip property is in fact the true address of the remote peer. srflx The candidate is a server reflexive candidate; the ip indicates an intermediary address assigned by the STUN server to represent the candidate's peer anonymously. prflx The candidate is a peer reflexive candidate; the ip is an intermediary address assigned by the STUN server to represent the candidate's peer anonymously. relay The candidate is a relay candi...
RTCIceCandidatePairStats.nominated - Web APIs
The RTCIceCandidatePairStats property nominated specifies whether or not the candidate pair described by the underlying RTCIceCandidatePair has been nominated to be used as the configuration for the WebRTC connection. Syntax nominated = rtcIceCandidatePairStats.nominated; Value A Boolean value which is set to true by the ICE layer if the controlling user agent has indicated that the candidate pair should be used to configure the WebRTC connection between the two peers. Note: If more than one candidate pair are nominated at the same time, the one whose priority is higher will be selected for use. Once a candidate pair has been nominated and the two peers have each reconfigured themselves to use the specified configuration, the ICE negotiation process can potentially end (or it can cont...
RTCIceCandidatePairStats.readable - Web APIs
The obsolete RTCIceCandidatePairStats property readable reports whether or not the connection described by the candidate pair has received at least one valid incoming ICE request. Syntax isReadable = rtcIceCandidatePairStats.readable; Value A Boolean value which is true if the connection described by this candidate pair has received at least one valid ICE request, and is therefore ready to be read from. Note: This property was removed from the specification in early 2017 because you can determine whether or not the connection is readable by checking to see if requestsReceived is greater than 0: if (icpStats.requestsReceived > 0) { /* at least one ICE request has been received */ } ...
RTCIceCandidatePairStats.writable - Web APIs
The obsolete RTCIceCandidatePairStats property writable reports whether or not the connection described by the candidate pair is writable. Syntax isWritable = rtcIceCandidatePairStats.writable; Value A Boolean value which is true if the connection described by this candidate pair has received acknowledgement of receipt (ACK) for at least one ICE request and that STUN consent hasn't expired. Note: This property was removed from the specification in early 2017 because you can determine whether or not an incoming ICE request is available to read by checking to see if responsesReceived is greater than 0 and that the time specified by consentExpiredTimestamp has not passed: if (icpStats.responsesReceived > 0 && icpStats.consentExpiredTimestamp < performance.now()) { /* at least one ...
RTCIceCandidateStats.candidateType - Web APIs
s interface's candidateType property is a string which indicates the type of ICE candidate the object represents. Syntax candidateType = rtcIceCandidateStats.candidateType; Value A DOMString whose value is one of the strings found in the RTCIceCandidateType enumerated type:host The candidate is a host candidate, whose IP address as specified in the RTCIceCandidate.ip property is in fact the true address of the remote peer. srflx The candidate is a server reflexive candidate; the ip indicates an intermediary address assigned by the STUN server to represent the candidate's peer anonymously. prflx The candidate is a peer reflexive candidate; the ip is an intermediary address assigned by the STUN server to represent the candidate's peer anonymously. relay The candidate is a relay candi...
RTCIceCandidateType - Web APIs
set of DOMString values representing the types of ICE candidate that can arrive. These strings are taken directly from the candidate a-line in SDP. Values These candidate types are listed in order of priority; the higher in the list they are, the more efficient they are. host The candidate is a host candidate, whose IP address as specified in the RTCIceCandidate.ip property is in fact the true address of the remote peer. srflx The candidate is a server reflexive candidate; the ip indicates an intermediary address assigned by the STUN server to represent the candidate's peer anonymously. prflx The candidate is a peer reflexive candidate; the ip is an intermediary address assigned by the STUN server to represent the candidate's peer anonymously. relay The candidate is a relay candi...
RTCOfferAnswerOptions - Web APIs
swerOptions as the base type for their options parameter's dictionary. createOffer() uses RTCOfferOptions and createAnswer() uses RTCAnswerOptions. Properties voiceActivityDetection Optional For configurations of systems and codecs that are able to detect when the user is speaking and toggle muting on and off automatically, this option enables and disables that behavior. The default value is true, enabling this functionality Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCOfferAnswerOptions' in that specification. Candidate Recommendation Initial definition. ...
RTCOfferOptions - Web APIs
The RTCOfferOptions dictionary is used to provide optional settings when creating an RTCPeerConnection offer with the createOffer() method. Properties This dictionary also inherits properties from the RTCOfferAnswerOptions dictionary, on which it's based. iceRestart Optional A Boolean which, when set to true, tells createOffer() to generate and use new values for the identifying properties of the SDP it creates, resulting in a request that triggers renegotiation of the ICE connection. This is useful if network conditions have changed in a way that make the current configuration untenable or impractical, for instance. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCOfferOptions' in that speci...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
s support trickle ICE. If trickling isn't supported, or you aren't able to tell, you can check for a falsy value for this property and then wait until the value of iceGatheringState changes to "completed" before creating and sending the initial offer. That way, the offer contains all of the candidates. 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. If no remote peer has been established, this value is null. Note: This property's value is determined once the local peer has called RTCPeerConnection.setRemoteDescription(); the provided description is used by the ICE agent to determine whether or not the remote peer supports trickled ICE candidates. Example var p...
RTCPeerConnection.removeStream() - Web APIs
tate is set to "closed", an InvalidStateError is raised. If the signalingState is set to "stable", the event negotiationneeded is sent on the RTCPeerConnection. ...
RTCPeerConnection.removeTrack() - Web APIs
(sender); Parameters mediaTrack A RTCRtpSender specifying the sender to remove from the connection. Return value undefined. Exceptions InvalidStateError The connection is not open. Example This example adds a video track to a connection and sets up a listener on a close button which removes the track when the user clicks the button. ...
RTCRtcpParameters - Web APIs
e of the rtcp property of the parameters of an RTCRtpSender or RTCRtpReceiver. Properties cname The Canonical Name (CNAME) being used by RTCP. This is used, for example, in SDES (SDP security descriptions) messages, described in RFC 4568. This property cannot be changed once initialized. reducedSize A Boolean value indicating whether or not reduced size RTCP is configured. If this value is true, reduced size RTCP (described in RFC 5506) is in effect. If false, compund RTCP is in use, as found in RFC 3550. This property cannot be changed once initialized. Examples This example obtains the canonical name (CNAME) being used for RTCP on an RTCRtpSender or RTCRtpReceiver. function getRtpCNAME(rtpObject) { let parameters = rtpObject.getParameters(); return parameters.rtcp.cname; } S...
RTCRtpEncodingParameters - Web APIs
An instance of the WebRTC API's RTCRtpEncodingParameters dictionary describes a single configuration of a codec for an RTCRtpSender. It's used in the RTCRtpSendParameters describing the configuration of an RTP sender's encodings; RTCRtpDecodingParameters is used to describe the configuration of an RTP receiver's encodings. Properties active If true, the described encoding is currently actively being used. That is, for RTP senders, the encoding is currently being used to send data, while for receivers, the encoding is being used to decode received data. The default value is true. codecPayloadType When describing a codec for an RTCRtpSender, codecPayloadType is a single 8-bit byte (or octet) specifying the codec to use for sending the stream; the value matches one from the owning RTCRtpP...
RTCRtpReceiver.getCapabilities() static function - Web APIs
TC connection. Since RTCRtpReceiver.getCapabilities() actually only indicates probable support, attempting to receive H.264 video might still fail even after getting a positive response from this function. function canReceiveH264() { let capabilities = RTCRtpReceiver.getCapabilities("video"); capabilities.codecs.forEach((codec) => { if (codec.mimeType === "video/H264") { return true; } }); return false; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpReceiver.getCapabilities()' in that specification. Candidate Recommendation ...
RTCRtpSendParameters.encodings - Web APIs
track. Syntax sendParameters.encodings = encodingParameterList; encodingParameterList = sendParameters.encodings; Value An array of objects conforming to the RTCRtpEncodingParameters dictionary, each of which contains properties which provide settings and parameters that describe and configure a single codec that could be used to encode the track. Each object's properties are: active If true, the described encoding is currently actively being used. That is, for RTP senders, the encoding is currently being used to send data, while for receivers, the encoding is being used to decode received data. The default value is true. codecPayloadType When describing a codec for an RTCRtpSender, codecPayloadType is a single 8-bit byte (or octet) specifying the codec to use for sending the strea...
RTCRtpSender.getCapabilities() static function - Web APIs
s sending H.264 video on an RTCRtpSender. Since RTCRtpSender.getCapabilities() actually only indicates probable support, H.264 support might still fail even after getting a positive response from this function. function canSendH264() { let capabilities = RTCRtpSender.getCapabilities("video"); capabilities.codecs.forEach((codec) => { if (codec.mimeType === "video/H264") { return true; } }); return false; } Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpSender.getCapabilities()' in that specification. Candidate Recommendation ...
RTCRtpSynchronizationSource.voiceActivityFlag - Web APIs
ctivityFlag property of the RTCRtpSynchronizationSource interface indicates whether or not the most recent RTP packet on the source includes voice activity. This is only present if the stream is using the voice activity detection feature; see the RTCOfferOptions flag voiceActivityDetection. 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. This property is omitted entirely if voice activity detection is not enabled on the source, or if the RFC 6464 extension header isn't present. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication B...
RTCRtpTransceiver.currentDirection - Web APIs
peer offers. "inactive" Does not offer to send RTP data, and will not do so. Does not offer to receive RTP data and will not do so. [1] To determine if a sender has at least one active encoding, the user agent gets its parameters using RTCRtpSender.getParameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to true, the sender has an active encoding. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpTransceiver.currentDirection' in that specification. Candidate Recommendation ...
RTCRtpTransceiver.direction - Web APIs
peer offers. "inactive" Does not offer to send RTP data, and will not do so. Does not offer to receive RTP data and will not do so. [1] To determine if a sender has at least one active encoding, the user agent gets its parameters using RTCRtpSender.getParameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to true, the sender has an active encoding. Exceptions When setting the value of direction, the following exceptions can occur: InvalidStateError Either the receiver's RTCPeerConnection is closed or the RTCRtpReceiver is stopped. Usage notes Setting the direction When you change the value of direction, an InvalidStateError exception will occur if the connection is closed or the receiver is stop...
RTCRtpTransceiver.stop() - Web APIs
That property has been deprecated and will be removed at some point. Instead, check the value of currentDirection. If it's stopped, the transceiver has been stopped. This method does nothing if the transceiver is already stopped. Syntax RTCRtpTransceiver.stop() Paramters None. ...
RTCRtpTransceiver.stopped - Web APIs
the RTCRtpTransceiver interface indicates whether or not the transceiver's associated sender and receiver have both been stopped. The transceiver is stopped if the stop() method has been called or if a change to either the local or the remote description has caused the transceiver to be stopped for some reason. Syntax var isStopped = RTCRtpTransceiver.stopped; Value A Boolean value which is true if the transceiver's sender will no longer send data, and its receiver will no longer receive data. If either or both are still at work, the result is false. Usage notes This property is deprecated and will be removed in the future. Instead, look at the value of currentDirection. Its value is stopped if the transceiver has stopped. Note: Currently only Firefox implements stopped, and has not ...
RTCRtpTransceiverDirection - Web APIs
peer offers. "inactive" Does not offer to send RTP data, and will not do so. Does not offer to receive RTP data and will not do so. [1] To determine if a sender has at least one active encoding, the user agent gets its parameters using RTCRtpSender.getParameters(), then looks at the parameters' encodings property; if any of the listed encodings has its active property set to true, the sender has an active encoding. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'RTCRtpTransceiverDirection' in that specification. Candidate Recommendation ...
RTCSessionDescription() - Web APIs
example uses the constructor to convert an SDP offer into an RTCSessionDescription object. This is no longer necessary, however; RTCPeerConnection.setLocalDescription() and other methods which take SDP as input now directly accept an object conforming to the RTCSessionDescriptionInit dictionary, so you don't have to instantiate an RTCSessionDescription yourself. navigator.getUserMedia({video: true}, function(stream) { pc.onaddstream({stream: stream}); // Adding a local stream won't trigger the onaddstream callback pc.addStream(stream); pc.createOffer(function(offer) { pc.setLocalDescription(new RTCSessionDescription(offer), function() { // send the offer to a server to be forwarded to the friend you're calling. }, error); }, error); } Specifications Spec...
Range.collapse() - Web APIs
Web › API › Range › collapse
The Range.collapse() method collapses the Range to one of its boundary points. A collapsed Range is empty, containing no content, specifying a single-point in a DOM tree. To determine if a Range is already collapsed, see the Range.collapsed property. 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 . Example var range = document.createRange(); referenceNode = document.getElementsByTagName("div").item(0); range.selectNode(referenceNode); range.collapse(true); Specifications Specification Status Comment DOMThe definition of 'Range.collapse()' in that specification. Living Standard The parameter is now optional and default to false. ...
Range.collapsed - Web APIs
Web › API › Range › collapsed
A collapsed Range is empty (containing no content), and specifies a single point in a DOM tree. To collapse a range, see the Range.collapse() method. ...
Range.isPointInRange() - Web APIs
Syntax bool = range.isPointInRange( referenceNode, offset ) Parameters referenceNode The Node to compare with the Range. offset The offset into Node of the point to compare with the Range. ...
ReadableStream.getReader() - Web APIs
t which point we return out of the recursive function and print the entire stream to another part of the UI. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = value; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textContent...
ReadableStream.locked - Web APIs
The locked read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. Syntax var locked = readableStream.locked; Value A Boolean indicating whether or not the readable stream is locked. Examples const stream = new ReadableStream({ ... }); const reader = stream.getReader(); stream.locked // should return true, as the stream has been locked to a reader Specifications Specification Status Comment StreamsThe definition of 'locked' in that specification. Living Standard Initial definition. ...
ReadableStreamBYOBReader.read() - Web APIs
iew to be read into. Return value A Promise, which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows: If a chunk is available, the promise will be fulfilled with an object of the form { value: theChunk, done: false }. If the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true }. If the stream becomes errored, the promise will be rejected with the relevant error. Exceptions TypeError The source object is not a ReadableStreamBYOBReader, the stream has no owner, the view is not an object or has become detached, or the view's length is 0. Examples TBD. Specifications Specification Status Comment StreamsThe definition of 'read()' in that...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
t which point we return out of the recursive function and print the entire stream to another part of the UI. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); listItem.textConten...
ReadableStreamDefaultReader.cancel() - Web APIs
(if (done)), we run reader.cancel() to cancel the stream, signalling that we don't need to use it any more. function fetchStream() { const reader = stream.getReader(); let charsReceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processText({ done, value }) { // Result objects contain two properties: // done - true if the stream has already given you all its data. // value - some data. Always undefined when done is true. if (done) { console.log("Stream complete"); reader.cancel(); para.textContent = result; return; } // value for fetch streams is a Uint8Array charsReceived += value.length; const chunk = value; let listItem = document.createElement('li'); ...
Report.body - Web APIs
Web › API › Report › body
tion. Depending on what type the Report is, the object returned will actually be a DeprecationReportBody, InterventionReportBody, CrashReportBody, or FeaturePolicyViolationReportBody. These all inherit from the base ReportBody class -- study their reference pages for more information on what the particular report body types contain. Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { let firstReport = reports[0]; // Log the first report's report body, i.e. a DeprecationReportBody object console.log(firstReport.body); }, options); Specifications Specification Status Comment Reporting APIThe definition of 'Report.body' in that specification. Editor's Draft ...
Report.type - Web APIs
Web › API › Report › type
The type read-only property of the Report interface returns the type of report generated, e.g. deprecation or intervention. Syntax let reportType = reportInstance.type Returns A string representing the type of the report. Currently the available types are deprecation, intervention, and crash. Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { let firstReport = reports[0]; // Log the first report's report type, i.e. "deprecation" console.log(firstReport.type); }, options); Specifications Specification Status Comment Reporting APIThe definition of 'Report.body' in that specification. Editor's Draft ...
Report.url - Web APIs
Web › API › Report › url
The url read-only property of the Report interface returns the URL of the document that generated the report. Syntax let reportURL = reportInstance.url Returns A string representing the URL of the document that generated the report. Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { let firstReport = reports[0]; // Log the URL of the document that generated the first report // e.g. "https://www.example.com/cats.html" console.log(firstReport.url); }, options); Specifications Specification Status Comment Reporting APIThe definition of 'Report.url' in that specification. Editor's Draft ...
Report - Web APIs
Web › API › Report
ntervention. Report.url Read only The URL of the document that generated the report. Methods This interface has no methods defined on it. Events This interface has no events that fire on it. ...
ReportingObserver() - Web APIs
available options are: types: An array of strings representing the types of report to be collected by this observer. Available types include deprecation, intervention, and crash (although this last type usually isn't retrievable via a ReportingObserver). buffered: a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (true) or not (false). Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { reportBtn.onclick = () => displayReports(reports); }, options); Specifications Specification Status Comment Reporting APIThe definition of 'ReportingObserver()' in that specification. Editor's Draft ...
ReportingObserver.disconnect() - Web APIs
porting observer that had previously started observing from collecting reports. After calling disconnect(), neither ReportingObserver.takeRecords() nor the records parameter of the ReportingObserver() callback will return any reports. The associated observer will no longer be active. Syntax reportingObserverInstance.disconnect() Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { reportBtn.onclick = () => displayReports(reports); }, options); observer.observe() ... observer.disconnect() Specifications Specification Status Comment Reporting APIThe definition of 'ReportingObserver.disconnect()' in that specification. Editor's Draft ...
ReportingObserver.observe() - Web APIs
The observe() method of the ReportingObserver interface instructs a reporting observer to start collecting reports in its report queue. Syntax reportingObserverInstance.observe() Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { reportBtn.onclick = () => displayReports(reports); }, options); observer.observe() Specifications Specification Status Comment Reporting APIThe definition of 'ReportingObserver.observe()' in that specification. Editor's Draft ...
ReportingObserver.takeRecords() - Web APIs
The takeRecords() method of the ReportingObserver interface returns the current list of reports contained in the observer's report queue, and empties the queue. Syntax reportingObserverInstance.takeRecords() Return value An array of Report objects. Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { reportBtn.onclick = () => displayReports(reports); }, options); observer.observe() // ... let records = observer.takeRecords(); console.log(records); Specifications Specification Status Comment Reporting APIThe definition of 'ReportingObserver.takeRecords()' in that specification. Editor's Draft ...
ReportingObserver - Web APIs
queue. ReportingObserver.takeRecords() Returns the current list of reports contained in the observer's report queue, and empties the queue. Events This interface has no events that fire on it. ...
ReportingObserverOptions - Web APIs
orting API allows options to be set in the constructor when creating a ReportingObserver. Properties types An array of strings representing the types of report to be collected by this observer. Available types include deprecation, intervention, and crash. buffered A boolean that defines whether the reports that were generated before the observer was able to be created should be observable (true) or not (false). Examples let options = { types: ['deprecation'], buffered: true } let observer = new ReportingObserver(function(reports, observer) { reportBtn.onclick = () => displayReports(reports); }, options); Specifications Specification Status Comment Reporting APIThe definition of 'ReportingObserverOptions' in that specification. Editor's Draft ...
Response.ok - Web APIs
Web › API › Response › ok
, extract a blob from the response using Body.blob, create an object URL out of it using URL.createObjectURL, and display this in an <img>. Note: at the top of the fetch() block we log the response ok value to the console. var myImage = document.querySelector('img'); var myRequest = new Request('flowers.jpg'); fetch(myRequest).then(function(response) { console.log(response.ok); // returns true if the response returned successfully response.blob().then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); }); Specifications Specification Status Comment FetchThe definition of 'ok' in that specification. Living Standard Initial definition ...
Response.redirected - Web APIs
of a request you made which was redirected. Relying on redirected to filter out redirects makes it easy for a forged redirect to prevent your content from working as expected. Instead, you should actually instead do the filtering when you call fetch(). See the example Disallowing redirects, which shows this being done. Syntax var isRedirected = Response.redirected; Value A Boolean which is true if the response indicates that your request was redirected. Examples Detecting redirects Checking to see if the response comes from a redirected request is as simple as checking this flag on the Response object. In the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation. Note, however, that this isn't as safe as outright rejecting redir...
Response.useFinalURL - Web APIs
urn undefined. Syntax var isfinalURL = Response.useFinalURL; Value A Boolean indicating whether or not the URL is final rather than a redirect. Example Consider a script residing in page index.html: fetch('/test').then((r) => console.log(r.url)) test.html is being controlled by the service worker sw.js: onfetch = (e) => { e.respondWith(fetch('/page2').then((r) => { r.usefinalURL = true; return r; }) } The output will be /page2 and not /test in index.html, since setting the usefinalURL means that the response's URL is not set to request's URL. ...
SVGAnimationElement: endEvent event - Web APIs
'li'); listItem.textContent = 'endEvent fired'; list.appendChild(listItem); }) animateElem.addEventListener('repeatEvent', (e) => { let listItem = document.createElement('li'); let msg = 'repeatEvent fired'; if(e.detail) { msg += '; repeat number: ' + e.detail; } listItem.textContent = msg; list.appendChild(listItem); }) btn.addEventListener('click', () => { btn.disabled = true; animateElem.setAttribute('repeatCount', '1'); }) Event handler property equivalent Note that you can also create an event listener for the end event using the onend event handler property: animateElem.onend = () => { console.log('endEvent fired'); } Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'endEvent' in that ...
SVGGraphicsElement: paste event - Web APIs
The paste event is fired on an SVGGraphicsElement when the user has initiated a "paste" action through the browser's user interface. Bubbles Yes Cancelable Yes Interface ClipboardEvent Event handler property onpaste If the cursor is in an editable context (for example, in a <textarea> or an element with contenteditable attribute set to true) then the default action is to insert the contents of the clipboard into the document at the cursor position. A handler for this event can access the clipboard contents by calling getData() on the event's clipboardData property. To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action us...
SVGTests - Web APIs
Web › API › SVGTests
An SVGStringList corresponding to the requiredFeatures attribute of the given element. SVGTests.requiredExtensions Read only An SVGStringList corresponding to the requiredExtensions attribute of the given element. SVGTests.systemLanguage Read only An SVGStringList corresponding to the systemLanguage attribute of the given element. Methods SVGTests.hasExtension() Read only Returns true if the browser supports the given extension, specified by a URI. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 2The definition of 'SVGTests' in that specification. Candidate Recommendation Removed requiredFeatures property and hasExtension() method. Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'SVGTests...
Screen.lockOrientation() - Web APIs
it to portrait. Note: It's possible to set several locks at the same time. So, if the lock is set for only one orientation, the screen orientation will never change until the screen orientation is unlocked. Otherwise, the screen orientation will change from an orientation to another as long as the orientations are amongst the orientations the device has been locked to. Return value Returns true if the orientation was authorized to be locked or false if the orientation locking was denied. Note that the return value doesn't indicate that the screen orientation is indeed locked: there may be a delay. Examples Usage with a DOMString argument screen.lockOrientationUniversal = screen.lockOrientation || screen.mozLockOrientation || screen.msLockOrientation; if (screen.lockOrientationUniver...
Screen.unlockOrientation() - Web APIs
The Screen.unlockOrientation() method removes all the previous screen locks set by the page/app. The ScreenOrientation.unlock() method should be used instead. Note: This method only works for installed Web apps or for Web pages in full-screen mode. 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. Example var unlockOrientation = screen.unlockOrientation || screen.mozUnlockOrientation || screen.msUnlockOrientation || (screen.orientation && screen.orientation.unlock); if (unlockOrientation()) { // orientation was unlocked } else { // orientation unlock failed } Specifications Specification Status Comment Screen Orientatio...
Screen Wake Lock API - Web APIs
ing platform wake lock and if referenced can be manually released and reacquired. Get an instance of the object by calling WakeLock.request. Navigator.wakelock Returns a WakeLock object instance, from which all other functionality can be accessed. Examples Feature Detection This code checks for wake lock support and updates the UI accordingly. if ('wakeLock' in navigator) { isSupported = true; statusElem.textContent = 'Screen Wake Lock API supported!'; } else { wakeButton.disabled = true; statusElem.textContent = 'Wake lock is not supported by this browser.'; } Requesting a wake lock The following example demonstrates how to request a WakeLockSentinel object. The WakeLock.request method is Promise based and so we can create an asynchronous function, which in turn updates the ...
ScriptProcessorNode.bufferSize - Web APIs
new AudioContext(); source = audioCtx.createBufferSource(); // Create a ScriptProcessorNode with a bufferSize of 4096 and a single input and output channel var scriptNode = audioCtx.createScriptProcessor(4096, 1, 1); console.log(scriptNode.bufferSize); // load in an audio track via XHR and decodeAudioData function getData() { request = new XMLHttpRequest(); request.open('GET', 'viper.ogg', true); request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { myBuffer = buffer; source.buffer = myBuffer; }, function(e){"Error with decoding audio data" + e.err}); } request.send(); } // Give the node a function to process audio events scriptNode.onaudioprocess = func...
ScriptProcessorNode.onaudioprocess - Web APIs
new AudioContext(); source = audioCtx.createBufferSource(); // Create a ScriptProcessorNode with a bufferSize of 4096 and a single input and output channel var scriptNode = audioCtx.createScriptProcessor(4096, 1, 1); console.log(scriptNode.bufferSize); // load in an audio track via XHR and decodeAudioData function getData() { request = new XMLHttpRequest(); request.open('GET', 'viper.ogg', true); request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { myBuffer = buffer; source.buffer = myBuffer; }, function(e){"Error with decoding audio data" + e.err}); } request.send(); } // Give the node a function to process audio events scriptNode.onaudioprocess = f...
ScriptProcessorNode - Web APIs
new AudioContext(); source = audioCtx.createBufferSource(); // Create a ScriptProcessorNode with a bufferSize of 4096 and a single input and output channel var scriptNode = audioCtx.createScriptProcessor(4096, 1, 1); console.log(scriptNode.bufferSize); // load in an audio track via XHR and decodeAudioData function getData() { request = new XMLHttpRequest(); request.open('GET', 'viper.ogg', true); request.responseType = 'arraybuffer'; request.onload = function() { var audioData = request.response; audioCtx.decodeAudioData(audioData, function(buffer) { myBuffer = buffer; source.buffer = myBuffer; }, function(e){"Error with decoding audio data" + e.err}); } request.send(); } // Give the node a function to process audio events scriptNode.onaudioprocess = func...
Selection.containsNode() - Web APIs
The Selection.containsNode() method indicates whether a specfied node is part of the selection. Syntax sel.containsNode(node, partialContainment) Parameters node The node that is being looked for in the selection. partialContainment Optional When true, containsNode() returns true when a part of the node is part of the selection. When false, containsNode() only returns true when the entire node is part of the selection. If not specified, the default value false is used. Example Check for selection This snippet checks whether anything inside the body element is selected. console.log(window.getSelection().containsNode(document.body, true)); Find the hidden word In this example, a message appears when you select the secret word. It uses addEventListener() to check for s...
ServiceWorker.onstatechange - Web APIs
istener('statechange', function(e) { logState(e.target.state); }); } Note that when statechange fires, the service worker's references may have changed. For example: navigator.serviceWorker.register(..).then(function(swr) { swr.installing.state == "installing" swr.installing.onstatechange = function() { swr.installing == null; // At this point, swr.waiting OR swr.active might be true. This is because the statechange // event gets queued, meanwhile the underlying worker may have gone into the waiting // state and will be immediately activated if possible. } }) Specifications Specification Status Comment Service WorkersThe definition of 'ServiceWorker.onstatechange' in that specification. Working Draft Initial definition ...
Using Service Workers - Web APIs
is one of the main reasons native apps are often chosen over web apps. Setting up to play with service workers Many service workers features are now enabled by default in newer versions of supporting browsers. If however you find that demo code is not working in your installed versions, you might need to enable a pref: Firefox Nightly: Go to about:config and set dom.serviceWorkers.enabled to true; restart browser. Chrome Canary: Go to chrome://flags and turn on experimental-web-platform-features; restart browser (note that some features are now enabled by default in Chrome.) Opera: Go to opera://flags and enable Support for ServiceWorker; restart browser. Microsoft Edge: Go to about:flags and tick Enable service workers; restart browser. You'll also need to serve your code via HTTPS ...
ShadowRoot.delegatesFocus - Web APIs
The delegatesFocus read-only property of the ShadowRoot interface returns a boolean that indicates whether delegatesFocus was set when the shadow was attached (see Element.attachShadow()). This is currently an experimental non-standard feature, available only in Chrome. Syntax var df = shadowRoot.delegatesFocus Value A boolean value -- true if the shadow root does delegate focus, false if it doesn't. Examples let customElem = document.querySelector('my-shadow-dom-element'); let shadow = customElem.shadowRoot; ... // Does it delegate focus? let hostElem = shadow.delegatesFocus; Specifications This feature is not currently in a specification. ...
SourceBuffer.appendBufferAsync() - Web APIs
Promise which is fulfilled when the buffer has been added successfully to the SourceBuffer, or null if the request could not be initiated. Example This simplified example async function, fillSourceBuffer(), takes as input parameters BufferSource, buffer, and a SourceBuffer to which to append the source media from the buffer. async function fillSourceBuffer(buffer, msBuffer) { try { while(true) { await msBuffer.appendBufferAsync(buffer); } } catch(e) { handleException(e); } } Specifications Not currently part of any specification. This is being experimented with under the auspices of the Web Platform Incubator Community Group (WICG). Specification Status Comment Media Source Extensions Recommendation Initial definition; does not inclu...
SourceBuffer.appendWindowEnd - Web APIs
onds. Exceptions The following exceptions may be thrown when setting a new value for this property. Exception Explanation InvalidAccessError An attempt was made to set the value to less than or equal to SourceBuffer.appendWindowStart, or NaN. InvalidStateError This SourceBuffer object is being updated (i.e. its SourceBuffer.updating property is currently true), or this SourceBuffer has been removed from the MediaSource. Example TBD Specifications Specification Status Comment Media Source ExtensionsThe definition of 'appendWindowEnd' in that specification. Recommendation Initial definition. ...
SourceBuffer.appendWindowStart - Web APIs
The following exceptions may be thrown when setting a new value for this property. Exception Explanation InvalidAccessError An attempt was made to set the value to less than 0, or a value greater than or equal to SourceBuffer.appendWindowEnd. InvalidStateError This SourceBuffer object is being updated (i.e. its SourceBuffer.updating property is currently true), or this SourceBuffer has been removed from the MediaSource. Example TBD Specifications Specification Status Comment Media Source ExtensionsThe definition of 'appendWindowStart' in that specification. Recommendation Initial definition. ...
SourceBuffer.mode - Web APIs
Web › API › SourceBuffer › mode
; Value A DOMString. Exceptions The following exceptions may be thrown when setting a new value for this property. Exception Explanation InvalidAccessError An attempt was made to set the value to segments when the initial value is sequence. InvalidStateError The SourceBuffer object is being updated (i.e. its SourceBuffer.updating property is currently true), the last media segment appended to this SourceBuffer is incomplete, or this SourceBuffer has been removed from the MediaSource. Example This snippet sets the sourceBuffer mode to 'sequence' if it is currently set to 'segments', thus setting the play order to the sequence in which media segments are appended. var curMode = sourceBuffer.mode; if (curMode == 'segments') { sourceBuffer.m...
SourceBuffer.remove() - Web APIs
time range, in seconds. Return value undefined. Exceptions Exception Explanation InvalidAccessError The MediaSource.duration property is equal to NaN, the start parameter is negative or greater than MediaSource.duration, or the end parameter is less than or equal to start or equal to NaN. InvalidStateError The SourceBuffer.updating property is equal to true, or this SourceBuffer has been removed from the MediaSource. Example TBD. Specifications Specification Status Comment Media Source ExtensionsThe definition of 'remove()' in that specification. Recommendation Initial definition. ...
SourceBuffer.timestampOffset - Web APIs
ffer.timestampOffset = 2.5; Value A double, with the offset amount expressed in seconds. Exceptions The following exceptions may be thrown when setting a new value for this property. Exception Explanation InvalidStateError One or more of the SourceBuffer objects in MediaSource.sourceBuffers are being updated (i.e. their SourceBuffer.updating property is currently true), a media segment inside the SourceBuffer is currently being parsed, or this SourceBuffer has been removed from the MediaSource. Example TBD Specifications Specification Status Comment Media Source ExtensionsThe definition of 'timestampOffset' in that specification. Recommendation Initial definition. ...
SourceBuffer.trackDefaults - Web APIs
Example TBD ...
SpeechRecognition.continuous - Web APIs
The continuous property of the SpeechRecognition interface controls whether continuous results are returned for each recognition, or only a single result. 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. var grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | m...
SpeechRecognition - Web APIs
current SpeechRecognition. If not specified, this defaults to the HTML lang attribute value, or the user agent's language setting if that isn't set either. SpeechRecognition.continuous Controls whether continuous results are returned for each recognition, or only a single result. 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. The default value is 1. SpeechRecognition.serviceURI Specifies the location of the speech recognition service used by the current SpeechRecognition to ha...
SpeechRecognitionResult.isFinal - Web APIs
Syntax var myIsFinal = speechRecognitionResultInstance.isFinal; Returns A Boolean. Examples recognition.onresult = function(event) { // The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object // The SpeechRecognitionResultList object contains SpeechRecognitionResult objects. ...
SpeechRecognitionResult - Web APIs
The SpeechRecognitionResult interface of the Web Speech API represents a single recognition match, which may contain multiple SpeechRecognitionAlternative objects. Properties SpeechRecognitionResult.isFinal Read only A Boolean that states whether this result is final (true) or not (false) -- if so, then this is the final time this result will be returned; if not, then this result is an interim result, and may be updated later on. SpeechRecognitionResult.length Read only Returns the length of the "array" -- the number of SpeechRecognitionAlternative objects contained in the result (also referred to as "n-best alternatives".) Methods SpeechRecognitionResult.item A standard getter that allows SpeechRecognitionAlternative objects within the result to be accessed via array syntax.
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. It can be set to paused even if nothing is currently being spoken through it. If utterances are then added to the utterance queue, they will not be spoken until the SpeechSynthesis object is unpaused, using SpeechSynthesis.resume(). Syntax var amIPaused = speechSynthesisInstance.paused; Value A Boolean. Examples var synth = window.speechSynthesis; synth.pause(); var amIPaused = synth.paused; // will return true Specifications Specification Status Comment Web Speech APIThe definition of 'paused' in that specification. Draft ...
SpeechSynthesis - Web APIs
SpeechSynthesis interface of the Web Speech API is the controller interface for the speech service; this can be used to retrieve information about the synthesis voices available on the device, start and pause speech, and other commands besides. Properties SpeechSynthesis also inherits properties from its parent interface, EventTarget. SpeechSynthesis.paused Read only A Boolean that returns true if the SpeechSynthesis object is in a paused state. SpeechSynthesis.pending Read only A Boolean that returns true if the utterance queue contains as-yet-unspoken utterances. SpeechSynthesis.speaking Read only A Boolean that returns true if an utterance is currently in the process of being spoken -- even if SpeechSynthesis is in a paused state. Methods SpeechSynthesis also inherits met...
SpeechSynthesisVoice.default - Web APIs
The spec is not very clear on which it should be, so some implementations may differ. Syntax var amIDefault = speechSynthesisVoiceInstance.default; Value A Boolean. ...
SpeechSynthesisVoice.localService - Web APIs
Syntax var amILocal = speechSynthesisVoiceInstance.localService; Value A Boolean. ...
SpeechSynthesisVoice - Web APIs
The SpeechSynthesisVoice interface of the Web Speech API represents a voice that the system supports. Every SpeechSynthesisVoice has its own relative speech service including information about language, name and URI. 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. SpeechSynthesisVoic...
StaticRange.collapsed - Web APIs
A collapsed range is one in which the start and end positions are the same, resulting in a zero-character-long range.. Specifications Specification Status Comment DOMThe definition of 'collapsed' in that specification. ...
StaticRange - Web APIs
nge</text></a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Constructor StaticRange() Creates a new StaticRange object given the StaticRangeInit dictionary specifying the default values for its properties. Properties The properties below are inherited from its parent interface, AbstractRange. StaticRange.collapsed Read only Returns a Boolean value which is true if the range's start and end positions are the same, resulting in a range of length 0. StaticRange.endContainer Read only Returns the DOM Node which contains the ending point of the range. The offset into the node at which the end position is located is indicated by endOffset. StaticRange.endOffset Read only Returns an integer value indicating the offset into the node given by endContainer ...
StorageManager.persist() - Web APIs
Syntax navigator.storage.persist().then(function(persistent) { ... }) Parameters None. Return value A Promise that resolves to a Boolean. ...
StorageManager.persisted() - Web APIs
Syntax navigator.storage.persisted().then(function(persistent) { ... }) Parameters None. Returns A Promise that resolves to a Boolean. ...
StorageManager - Web APIs
rsistance permissions and estimating available storage. You can get a reference to this interface using either navigator.storage or WorkerNavigator.storage. Methods StorageManager.estimate() Secure context Returns a Promise that resolves to a StorageEstimate object containing usage and quota numbers for your origin. StorageManager.persist() Secure context Returns a Promise that resolves to true if the user agent is able to persist your site's storage. StorageManager.persisted() Secure context Returns a Promise that resolves to true if persistence has already been granted for your site's storage. Specifications Specification Status Comment StorageThe definition of 'StorageManger' in that specification. Living Standard Initial definition. ...
Using the Storage Access API - Web APIs
torage Access API is designed to allow embedded content to request access to storage that would otherwise be blocked when a user's browser is set to block all third-party cookies. Since embedded content won't know which storage policy is in use by the user, it's best to always check whether the embedded frame has storage access before attempting to read or write from storage. This is particularly true for Document.cookie access, as browsers will often return an empty cookie jar when third-party cookies are blocked. Accessing a user's cookies in an embedded cross-origin iframe In this example we show how an embedded cross-origin <iframe> can access a user's cookies under a storage access policy that blocks third-party cookies. First of all, if the <iframe> is sandboxed, the embedding website...
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). Syntax bool = stylesheet.disabled Example // If the stylesheet is disabled... if (stylesheet.disabled) { // ... apply styles in-line. ...
SubtleCrypto.deriveKey() - Web APIs
Recommendation Initial definition. ...
SubtleCrypto.verify() - Web APIs
"HMAC" }. key is a CryptoKey containing the key that will be used to verify the signature. It is the secret key for a symmetric algorithm and the public key for a public-key system. signature is a ArrayBuffer containing the signature to verify. data is a ArrayBuffer containing the data whose signature is to be verified. Return value result is a Promise that fulfills with a Boolean: true if the signature is valid, false otherwise. Exceptions The promise is rejected when the following exception is encountered: InvalidAccessError Raised when the encryption key is not a key for the requested verifying algorithm or when trying to use an algorithm that is either unknown or isn't suitable for a verify operation. Supported algorithms The verify() method supports the same algor...
SyncEvent.lastChance - Web APIs
This is the value passed in the lastChance parameter of the SyncEvent() constructor. Syntax var lastChance = SyncEvent.lastChance Value A Boolean that indicates whether the user agent will not make further synchronization attempts after the current attempt. ...
SyncEvent - Web APIs
Web › API › SyncEvent
Methods Inherits methods from its parent, ExtendableEvent. None. ...
SyncManager.register() - Web APIs
ster([options]).then(function(syncRegistration) { ... }) Returns A Promise that resolves to an instance of SyncRegistration. Parameters options Optional An object that sets options for an instance of SyncRegistration. The available options are: allowOnBattery: A boolean that determines whether synchronization is allowed when the user agent is on a battery-powered device. The default is true. id: The unique identifier of the specified SyncRegistration object. idleRequired: A boolean that determines whether synchronization is allowed when the user agent's device is idle. The default is false. maxDelay: The maximum delay in milliseconds before the next sync event (or the first sync event if it is periodic). The default is 0, meaning there is no maximum delay. minDelay: The mini...
TextDecoder() - Web APIs
Is a TextDecoderOptions dictionary with the property: fatal A Boolean flag indicating if the TextDecoder.decode() method must throw a DOMException with the "EncodingError" value when an coding error is found. It defaults to false. Example var textDecoder1 = new TextDecoder("iso-8859-2"); var textDecoder2 = new TextDecoder(); var textDecoder3 = new TextDecoder("csiso2022kr", {fatal: true}); // Allows EncodingError exception to be thrown. var textDecoder4 = new TextDecoder("iso-2022-cn"); // Throw a TypeError exception. Specifications Specification Status Comment EncodingThe definition of 'TextDecoder()' in that specification. Living Standard Initial definition. ...
TextDecoder.prototype.decode() - Web APIs
ject. Syntax b1 = decoder.decode(buffer, options); b2 = decoder.decode(buffer); b3 = decoder.decode(); Parameters buffer Optional Is either an ArrayBuffer or an ArrayBufferView containing the text to decode. options Optional Is a TextDecodeOptions dictionary with the property: stream A Boolean flag indicating that additional data will follow in subsequent calls to decode(). Set to true if processing the data in chunks, and false for the final chunk or if the data is not chunked. It defaults to false. Example This example encodes and decodes the euro symbol, EUR. HTML <p>Encoded value: <span id="encoded-value"></span></p> <p>Decoded value: <span id="decoded-value"></span></p> JavaScript const encoder = new TextEncoder(); const array = encoder.encode('EUR'); // Uint8Ar...
TouchEvent.targetTouches - Web APIs
he TouchEvent.targetTouches property is a TouchList object that includes those TPs that are currently touching the surface and started on the element that is the target of the current event. As such, the targetTouches list is a strict subset of the touches list. In following code snippet, the function compares the length of the touches list to the the length of the targetTouches list and returns true if the lengths are the same and returns false otherwise. function touches_in_target(ev) { // Return true if all of the touches are within the target element; // otherwise return false. return (ev.touches.length == ev.targetTouches.length ? true : false); } Specifications Specification Status Comment Touch Events - Level 2 Draft Non-stable version. ...
TouchEvent - Web APIs
ouch and mouse events get sent (in order to let non-touch-specific code still interact with the user). If you use touch events, you should call preventDefault() to keep the mouse event from being sent as well. The exception to this is Chrome, starting with version 56 (desktop, Chrome for android, and android webview), where the default value for the passive option for touchstart and touchmove is true and calls to preventDefault() will have no effect. To override this behavior, you need to set the passive option to false, after which calling preventDefault() will work as specified. The change to treat listeners as passive by default prevents the listener from blocking page rendering while a user is scrolling. A demo is available on the Google Developer site. GlobalEventHandlers The GlobalEve...
Touch events - Web APIs
eEvents"); var type = null; var touch = null; switch (evt.type) { case "touchstart": type = "mousedown"; touch = evt.changedTouches[0]; break; case "touchmove": type = "mousemove"; touch = evt.changedTouches[0]; break; case "touchend": type = "mouseup"; touch = evt.changedTouches[0]; break; } newEvt.initMouseEvent(type, true, true, evt.originalTarget.ownerDocument.defaultView, 0, touch.screenX, touch.screenY, touch.clientX, touch.clientY, evt.ctrlKey, evt.altKey, evt.shiftKey, evt.metaKey, 0, null); evt.originalTarget.dispatchEvent(newEvt); } Calling preventDefault() only on a second touch One technique for preventing things like pinchZoom on a page is to call preventDefault() on the second touch in a se...
TransitionEvent.initTransitionEvent() - Web APIs
tTransitionEvent(typeArg, canBubbleArg, cancelableArg, transitionNameArg, elapsedTimeArg); Parameters typeArg Is a DOMString identifying the specific type of transition event that occurred. The following value is allowed: Value Meaning transitionend The transition completed. 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). transitionNameArg Is a DOMString containing the name of the CSS property associated with the transition. This value is not affected by the transition-delay property. elapsedTimeArg Is float giving the amount of time the transition has been running, in seconds, whe...
UIEvent.cancelBubble - Web APIs
Not all events are allowed to bubble up the DOM. Use Event.stopPropagation() instead of this non-standard method. ...
UIEvent.initUIEvent() - Web APIs
cifying some detail information about the event, depending on the type of event. For mouse events, it indicates how many times the mouse has been clicked on a given screen location. Example var e = document.createEvent("UIEvent"); // creates a click event that bubbles, can be cancelled, // and with its view and detail property initialized to window and 1, // respectively e.initUIEvent("click", true, true, window, 1); Specifications Specification Status Comment Document Object Model (DOM) Level 3 Events SpecificationThe definition of 'UIEvent.initUIEvent()' in that specification. Obsolete From Document Object Model (DOM) Level 2 Events Specification, deprecated. Document Object Model (DOM) Level 2 Events SpecificationThe definition of 'UIEvent.initUI...
UIEvent.isChar - Web APIs
Web › API › UIEvent › isChar
Some keystroke combinations may raise events but not produce any character (example: ctrl-alt-?). When this is the case, isChar returns false. It is used when event handlers need to do something like echo the input on the screen. ...
URLSearchParams.has() - Web APIs
Boolean that indicates whether a parameter with the specified name exists. Note: This feature is available in Web Workers. Syntax var hasName = URLSearchParams.has(name) Parameters name The name of the parameter to find. Return value A Boolean. Examples let url = new URL('https://example.com?foo=1&bar=2'); let params = new URLSearchParams(url.search.slice(1)); params.has('bar') === true; //true Specifications Specification Status Comment URLThe definition of 'has()' in that specification. Living Standard Initial definition. ...
URLSearchParams.set() - Web APIs
Living Standard Initial definition. ...
URL API - Web APIs
Web › API › URL API
epresented by the object. For example, to create a URL and set its username: let myUsername = "someguy"; let addr = new URL("https://mysite.com/login"); addr.username = myUsername; Setting the value of username not only sets that property's value, but it updates the overall URL. After executing the code snippet above, the value returned by addr.href is https://someguy@mysite.com/login. This is true for any of the writable properties. Queries The search property on a URL contains the query string portion of the URL. For example, if the URL is https://mysite.com/login?user=someguy&page=news, then the value of the search property is ?user=someguy&page=news. You can also look up the values of individual parameters with the URLSearchParams object's get() method: let addr = new URL("https://my...
USBDevice.clearHalt() - Web APIs
'in' or 'out'. endpointNumber Indicates the number of the endpoint to clear. The promise will reject if an invalid endpoint is supplied. Return value A promise. Example The following example shows how to test for and clear a 'stall' condition in the result of a data transfer. What data can be passed to a USB device and how it is passed is particular and unique to each device. while (true) { let result = await data.transferIn(1, 6); if (result.data && result.data.byteLength === 6) { console.log('Channel 1: ' + result.data.getUint16(0)); console.log('Channel 2: ' + result.data.getUint16(2)); console.log('Channel 5: ' + result.data.getUint16(4)); } if (result.status === 'stall') { console.warn('Endpoint stalled. Clearing.'); await device.clearHalt('in',...
UserProximityEvent.near - Web APIs
Syntax var near = userProximityEvent.near; Value A boolean ...
VTTCue - Web APIs
Web › API › VTTCue
which the cue applies. text The raw text of the cue, and rules for its interpretation. Properties This interface also inherits properties from TextTrackCue. VTTCue.region A VTTRegion object describing the video's sub-region that the cue will be drawn onto, or null if none is assigned. VTTCue.vertical Returns an enum representing the cue writing direction. VTTCue.snapToLines Returns true if the VTTCue.line attribute is an integer number of lines or a percentage of the video size. VTTCue.line Returns the line positioning of the cue. This can be the string auto or a number whose interpretation depends on the value of VTTCue.snapToLines. VTTCue.lineAlign Returns an enum representing the alignment of the VTTCue.line. VTTCue.position Returns the indentation of the cue within the...
ValidityState.rangeOverflow - Web APIs
ct indicates if the value of an <input>, after having been edited by the user, does not conform to the constraints set by the element's max attribute. If the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and a max value is set, if the value don't doesn't conform to the constraints set by the max value, the rangeOverflow property will be true. Given the following: <input type="number" min="20" max="40" step="2"/> if value > 40, rangeOverflow will be true. When true, the element matches the :invalid and :out-of-range CSS pseudo-classes. Specifications Specification Status Comment HTML Living StandardThe definition of 'ValidityState.rangeOverflow' in that specification. Living Standard HTML 5...
ValidityState.rangeUnderflow - Web APIs
t indicates if the value of an <input>, after having been edited by the user, does not conform to the constraints set by the element's min attribute. If the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and a min value is set, if the value don't doesn't conform to the constraints set by the min value, the rangeUnderflow property will be true. Given the following: <input type="number" min="20" max="40" step="2"/> if value < 20, rangeUnderflow will be true. When true, the element matches the :invalid and :out-of-range CSS pseudo-classes. Specifications Specification Status Comment HTML Living StandardThe definition of 'ValidityState.rangeUnderflow' in that specification. Living Standard HTML...
ValidityState.stepMismatch - Web APIs
tes if the value of an <input>, after having been edited by the user, does not conform to the constraints set by the element's step attribute. If the field is numeric in nature, including the date, month, week, time, datetime-local, number and range types and the step value is not any, if the value don't doesn't conform to the constraints set by the step and min values, then stepMismatch will be true. If the remainder of the form control's value less the min value, divided by the step value (which defaults to 1 if ommitted) is not zero, there is a mismatch. Given the following: <input type="number" min="20" max="40" step="2"/> if (value - min) / 2 != 0, stepMismatch will be true. If true, the element matches the :invalid and :out-of-range CSS pseudo-classes. Specifications Spe...
VideoTrack.selected - Web APIs
The VideoTrack property selected controls whether or not a particular video track is active. Syntax isVideoSelected = VideoTrack.selected; VideoTrack.selected = true | false; Value The selected property is a Boolean whose value is true if the track is active. Only a single video track can be active at any given time, so setting this property to true for one track while another track is active will make that other track inactive. Specifications Specification Status Comment HTML Living StandardThe definition of 'VideoTrack: selected' in that specification. Living Standard ...
Visual Viewport API - Web APIs
ndingUpdate flag and the call to requestAnimationFrame(). The pendingUpdate flag serves to prevent multiple invocations of the transfrom that can occur when onresize and onscroll fire at the same time. Using requestAnimationFrame() ensures that the transform ocurrs before the next render. 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. var viewport = event.target; var offsetLeft = viewport.offsetLeft; var offsetTop = viewport.height - layoutV...
WEBGL_debug_renderer_info - Web APIs
performance would be dramatically slow. WebGL extensions are available using the WebGLRenderingContext.getExtension() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: Depending on the privacy settings of the browser, this extension might only be available to privileged contexts or not work at all. In Firefox, if privacy.resistFingerprinting is set to true, this extensions is disabled. This extension is available to both, WebGL1 and WebGL2 contexts. Constants ext.UNMASKED_VENDOR_WEBGL Vendor string of the graphics driver. ext.UNMASKED_RENDERER_WEBGL Renderer string of the graphics driver. Examples With the help of this extension, privileged contexts are able to retrieve debugging information about about the user's graphic driver: var c...
WebGL2RenderingContext.isQuery() - Web APIs
Examples gl must be a WebGL2RenderingContext. WebGLQuery objects are not available in WebGL 1. var query = gl.createQuery(); // ... gl.isQuery(query); Specifications Specification Status Comment WebGL 2.0The definition of 'isQuery' in that specification. Editor's Draft Initial definition. ...
WebGL2RenderingContext.isSampler() - Web APIs
Examples gl must be a WebGL2RenderingContext. WebGLSampler objects are not available in WebGL 1. var sampler = gl.createSampler(); // ... gl.isSampler(sampler); Specifications Specification Status Comment WebGL 2.0The definition of 'isSampler' in that specification. Editor's Draft Initial definition. ...
WebGL2RenderingContext.isSync() - Web APIs
Examples gl must be a WebGL2RenderingContext. WebGLSync objects are not available in WebGL 1. var sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0); // ... gl.isSync(sync); Specifications Specification Status Comment WebGL 2.0The definition of 'isSync' in that specification. Editor's Draft Initial definition. ...
WebGL2RenderingContext.vertexAttribIPointer() - Web APIs
ey were originally specified as integers in the buffer), this method allows specifying values which are interpreted as integers in the shader. Examples Linear Blend Skinning //Describe the layout of the buffer: //1. position gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 20, 0); gl.enableVertexAttribArray(0); //2. bone weights, normalized to [0, 1] gl.vertexAttribPointer(1, 4, gl.UNSIGNED_BYTE, true, 20, 12); gl.enableVertexAttribArray(1); //3. bone indices, interpreted as integer gl.vertexAttribIPointer(2, 4, gl.UNSIGNED_BYTE, 20, 16); gl.enableVertexAttribArray(2); //Connect to attributes from the vertex shader gl.bindAttribLocation(shaderProgram, 0, "position"); gl.bindAttribLocation(shaderProgram, 1, "boneWeights"); gl.bindAttribLocation(shaderProgram, 2, "boneIndices"); <script id="s...
WebGLRenderingContext.blendEquation() - Web APIs
l.FUNC_ADD); gl.blendEquation(gl.FUNC_SUBTRACT); gl.blendEquation(gl.FUNC_REVERSE_SUBTRACT); To get the blend equations, query the BLEND_EQUATION, BLEND_EQUATION_RGB and BLEND_EQUATION_ALPHA constants which return gl.FUNC_ADD, gl.FUNC_SUBTRACT, gl.FUNC_REVERSE_SUBTRACT, or if the EXT_blend_minmax is enabled: ext.MIN_EXT or ext.MAX_EXT. gl.getParameter(gl.BLEND_EQUATION_RGB) === gl.FUNC_ADD; // true gl.getParameter(gl.BLEND_EQUATION_ALPHA) === gl.FUNC_ADD; // true Specifications Specification Status Comment WebGL 1.0The definition of 'blendEquation' in that specification. Recommendation Initial definition for WebGL. OpenGL ES 2.0The definition of 'glBlendEquation' in that specification. Standard Man page of the OpenGL ES 2.0 API. Open...
WebGLRenderingContext.blendEquationSeparate() - Web APIs
the blend equations, use: gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_SUBTRACT); To get the current blend equations, query the BLEND_EQUATION, BLEND_EQUATION_RGB and BLEND_EQUATION_ALPHA constants which return gl.FUNC_ADD, gl.FUNC_SUBTRACT, gl.FUNC_REVERSE_SUBTRACT, or if the EXT_blend_minmax is enabled: ext.MIN_EXT or ext.MAX_EXT. gl.getParameter(gl.BLEND_EQUATION_RGB) === gl.FUNC_ADD; // true gl.getParameter(gl.BLEND_EQUATION_ALPHA) === gl.FUNC_ADD; // true Specifications Specification Status Comment WebGL 1.0The definition of 'blendEquationSeparate' in that specification. Recommendation Initial definition for WebGL. OpenGL ES 2.0The definition of 'glBlendEquationSeparate' in that specification. Standard Man page of the OpenGL ES 2.0 AP...
WebGLRenderingContext.blendFunc() - Web APIs
ontext.enable() with the argument gl.BLEND. gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_COLOR, gl.DST_COLOR); To get the current blend function, query the BLEND_SRC_RGB, BLEND_SRC_ALPHA, BLEND_DST_RGB, and BLEND_DST_ALPHA constants which return one of the blend function constants. gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_COLOR, gl.DST_COLOR); gl.getParameter(gl.BLEND_SRC_RGB) == gl.SRC_COLOR; // true Specifications Specification Status Comment WebGL 1.0The definition of 'blendFunc' in that specification. Recommendation Initial definition. In WebGL, constant color and constant alpha cannot be used together as source and destination factors in the blend function. See section 6.13. of the specification. OpenGL ES 2.0The definition of 'glBlendFunc' in...
WebGLRenderingContext.blendFuncSeparate() - Web APIs
able(gl.BLEND); gl.blendFuncSeparate(gl.SRC_COLOR, gl.DST_COLOR, gl.ONE, gl.ZERO); To get the current blend function, query the BLEND_SRC_RGB, BLEND_SRC_ALPHA, BLEND_DST_RGB, and BLEND_DST_ALPHA constants which return one of the blend function constants. gl.enable(gl.BLEND); gl.blendFuncSeparate(gl.SRC_COLOR, gl.DST_COLOR, gl.ONE, gl.ZERO); gl.getParameter(gl.BLEND_SRC_RGB) == gl.SRC_COLOR; // true Specifications Specification Status Comment WebGL 1.0The definition of 'blendFunc' in that specification. Recommendation Initial definition. In WebGL, constant color and constant alpha cannot be used together as source and destination factors in the blend function. See section 6.13. of the specification. OpenGL ES 2.0The definition of 'glBlendFunc' in...
WebGLRenderingContext.cullFace() - Web APIs
gl.BACK gl.FRONT_AND_BACK Return value None. Examples Polygon culling is disabled by default. To enable or disable culling, use the enable() and disable() methods with the argument gl.CULL_FACE. gl.enable(gl.CULL_FACE); gl.cullFace(gl.FRONT_AND_BACK); To check the current cull face mode, query the CULL_FACE_MODE constant. gl.getParameter(gl.CULL_FACE_MODE) === gl.FRONT_AND_BACK; // true Specifications Specification Status Comment WebGL 1.0The definition of 'cullFace' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glCullFace' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.depthFunc() - Web APIs
th buffer value) gl.ALWAYS (always pass) Return value None. Examples The depth testing is disabled by default. To enable or disable depth testing, use the enable() and disable() methods with the argument gl.DEPTH_TEST. gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.NEVER); To check the current depth function, query the DEPTH_FUNC constant. gl.getParameter(gl.DEPTH_FUNC) === gl.NEVER; // true Specifications Specification Status Comment WebGL 1.0The definition of 'depthFunc' in that specification. Recommendation Initial definition. OpenGL ES 2.0The definition of 'glDepthFunc' in that specification. Standard Man page of the OpenGL API. ...
WebGLRenderingContext.depthMask() - Web APIs
Return value None. Examples gl.depthMask(false); To get the current depth mask, query the DEPTH_WRITEMASK constant which returns a Boolean. ...
WebGLRenderingContext.enable() - Web APIs
tant Description gl.RASTERIZER_DISCARD Primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. Return value None. Examples gl.enable(gl.DITHER); To check if a capability is enabled, use the WebGLRenderingContext.isEnabled() method: gl.isEnabled(gl.DITHER); // true Specifications Specification Status Comment WebGL 1.0The definition of 'enable' in that specification. Recommendation Initial definition for WebGL. OpenGL ES 2.0The definition of 'glEnable' in that specification. Standard Man page of the OpenGL ES 2.0 API. OpenGL ES 3.0The definition of 'glEnable' in that specification. Standard Man p...
WebGLRenderingContext.getTexParameter() - Web APIs
TEXTURE_COMPARE_FUNC GLenum Comparison function gl.LEQUAL (default value), gl.GEQUAL, gl.LESS, gl.GREATER, gl.EQUAL, gl.NOTEQUAL, gl.ALWAYS, gl.NEVER. gl.TEXTURE_COMPARE_MODE GLenum Texture comparison mode gl.NONE (default value), gl.COMPARE_REF_TO_TEXTURE. gl.TEXTURE_IMMUTABLE_FORMAT GLboolean Immutability of the texture format and size true or false. gl.TEXTURE_IMMUTABLE_LEVELS GLuint ? Any uint values. gl.TEXTURE_MAX_LEVEL GLint Maximum texture mipmap array level Any int values. gl.TEXTURE_MAX_LOD GLfloat Texture maximum level-of-detail value Any float values. gl.TEXTURE_MIN_LOD GLfloat Texture minimum level-of-detail value Any float val...
WebGLRenderingContext.isBuffer() - Web APIs
Syntax GLboolean gl.isBuffer(buffer); Parameters buffer A WebGLBuffer to check. Return value A GLboolean indicating whether or not the buffer is valid. Examples Creating a buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var buffer = gl.createBuffer(); gl.isBuffer(buffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isBuffer' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.isContextLost() - Web APIs
Usage notes There are several reasons why a WebGL context may be lost, making it necessary to re-establish the context before resuming rendering. ...
WebGLRenderingContext.isEnabled() - Web APIs
When using a WebGL 2 context, the following values are available additionally: Constant Description gl.RASTERIZER_DISCARD Primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. 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.isFramebuffer() - Web APIs
Syntax GLboolean gl.isFramebuffer(framebuffer); Parameters framebuffer A WebGLFramebuffer to check. Return value A GLboolean indicating whether or not the frame buffer is valid. Examples Checking a frame buffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var framebuffer = gl.createFramebuffer(); gl.isFramebuffer(framebuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isFramebuffer' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.isProgram() - Web APIs
Syntax GLboolean gl.isProgram(program); Parameters program A WebGLProgram to check. Return value A GLboolean indicating whether or not the program is valid. Examples Checking a program var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var program = gl.createProgram(); // ... gl.isProgram(program); Specifications Specification Status Comment WebGL 1.0The definition of 'isProgram' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.isRenderbuffer() - Web APIs
Syntax GLboolean gl.isRenderbuffer(renderbuffer); Parameters renderbuffer A WebGLRenderbuffer to check. Return value A GLboolean indicating whether or not the renderbuffer is valid. Examples Checking a renderbuffer var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var renderbuffer = gl.createRenderbuffer(); gl.isRenderbuffer(renderbuffer); Specifications Specification Status Comment WebGL 1.0The definition of 'isRenderbuffer' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.isShader() - Web APIs
Syntax GLboolean gl.isShader(shader); Parameters shader A WebGLShader to check. Return value A GLboolean indicating whether or not the shader is valid. Examples Checking a shader var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var shader = gl.createShader(gl.VERTEX_SHADER); // ... gl.isShader(shader); Specifications Specification Status Comment WebGL 1.0The definition of 'isShader' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.isTexture() - Web APIs
Syntax GLboolean gl.isTexture(texture); Parameters texture A WebGLTexture to check. Return value A GLboolean indicating whether or not the texture is valid. Examples Checking a texture var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); var texture = gl.createTexture(); gl.isTexture(texture); Specifications Specification Status Comment WebGL 1.0The definition of 'isTexture' in that specification. Recommendation Initial definition. ...
WebGLRenderingContext.pixelStorei() - Web APIs
e) Description Type Default value Allowed values (for param) Specified in gl.PACK_ALIGNMENT Packing of pixel data into memory GLint 4 1, 2, 4, 8 OpenGL ES 2.0 gl.UNPACK_ALIGNMENT Unpacking of pixel data from memory. GLint 4 1, 2, 4, 8 OpenGL ES 2.0 gl.UNPACK_FLIP_Y_WEBGL Flips the source data along its vertical axis if true. GLboolean false true, false WebGL gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL Multiplies the alpha channel into the other color channels GLboolean false true, false WebGL gl.UNPACK_COLORSPACE_CONVERSION_WEBGL Default color space conversion or no color space conversion. GLenum gl.BROWSER_DEFAULT_WEBGL gl.BROWSER_DEFAULT_WEBGL, gl.NONE WebGL ...
WebGLRenderingContext - Web APIs
ext. WebGLRenderingContext.drawingBufferHeight The read-only height of the current drawing buffer. Should match the height of the canvas element associated with this context. WebGLRenderingContext.getContextAttributes() Returns a WebGLContextAttributes object that contains the actual context parameters. Might return null, if the context is lost. WebGLRenderingContext.isContextLost() Returns true if the context is lost, otherwise returns false. WebGLRenderingContext.makeXRCompatible() Ensures the context is compatible with the user's XR hardware, re-creating the context if necessary with a new configuration to do so. This can be used to start an application using standard 2D presentation, then transition to using a VR or AR mode later. Viewing and clipping WebGLRenderingContext.sci...
Hello vertex attributes - Web APIs
TIC_DRAW); gl.drawArrays(gl.POINTS, 0, 1); }, false); } var buffer; function initializeAttributes() { gl.enableVertexAttribArray(0); buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.0]), gl.STATIC_DRAW); gl.vertexAttribPointer(0, 1, gl.FLOAT, false, 0, 0); } window.addEventListener("beforeunload", cleanup, true); function cleanup() { gl.useProgram(null); if (buffer) gl.deleteBuffer(buffer); if (program) gl.deleteProgram(program); } function getRenderingContext() { var canvas = document.querySelector("canvas"); canvas.width = canvas.clientWidth; canvas.height = canvas.clientHeight; var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { ...
WebGL constants - Web APIs
R 0x8B31 Passed to createShader to define a vertex shader COMPILE_STATUS 0x8B81 Passed to getShaderParamter to get the status of the compilation. Returns false if the shader was not compiled. You can then query getShaderInfoLog to find the exact error DELETE_STATUS 0x8B80 Passed to getShaderParamter to determine if a shader was deleted via deleteShader. Returns true if it was, false otherwise. LINK_STATUS 0x8B82 Passed to getProgramParameter after calling linkProgram to determine if a program was linked correctly. Returns false if there were errors. Use getProgramInfoLog to find the exact error. VALIDATE_STATUS 0x8B83 Passed to getProgramParameter after calling validateProgram to determine if it is valid. Returns false if errors...
Matrix math for the web - Web APIs
ain class are multiplied together they preserve the history of the transformations and are reversible. This means that if a translation, rotation, and scale matrix are all combined together, when the order of the matrices is reversed and re-applied then the original points are returned. The order that matrices are multiplied in matters. When multiplying numbers, a * b = c, and b * a = c are both true. For example 3 * 4 = 12, and 4 * 3 = 12. In math these numbers would be described as commutative. Matrices are not guaranteed to be the same if the order is switched, so matrices are non-commutative. Another mind-bender is that matrix multiplication in WebGL and CSS needs to happen in the reverse order that the operations intuitively happen. For instance, to scale something down by 80%, move it ...
WebGL model view projection - Web APIs
that this addition allows for lots of nice techniques for manipulating 3D data. This added dimension introduces the notion of perspective into the coordinate system; with it in place, we can map 3D coordinates into 2D space--thereby allowing two parallel lines to intersect as they recede into the distance. The value of w is used as a divisor for the other components of the coordinate, so that the true values of x, y, and z are computed as x/w, y/w, and z/w (and w is then also w/w, becoming 1). A three dimensional point is defined in a typical Cartesian coordinate system. The added fourth dimension changes this point into a homogeneous coordinate. It still represents a point in 3D space and it can easily be demonstrated how to construct this type of coordinate through a pair of simple function...
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
other peer over the signaling service. Deactivating hold mode Local peer When the local user clicks the interface widget to disable hold mode, the disableHold() method is called to begin the process of restoring normal functionality. async function disableHold(micStream) { await audioTransceiver.sender.replaceTrack(micStream.getAudioTracks()[0]); audioTransceiver.receiver.track.enabled = true; audioTransceiver.direction = "sendrecv"; } This reverses the steps taken in enableHold() as follows: The audio transceiver's RTCRtpSender's track is replaced with the specified stream's first audio track. The transceiver's incoming audio track is re-enabled. The audio transceiver's direction is set to "sendrecv", indicating that it should return to both sending and receiving streamed aud...
Fundamentals of WebXR - Web APIs
lopers to experiment, it became clear that in order to finish an API for virtual environments on the web, it would make more sense to start a new specification than to try to "fix" WebVR. Thus, WebXR was created. The most obvious difference, at the highest level, is that WebXR supports not just virtual reality applications, but also augmented reality, which blends virtual objects with the user's true physical environment. Another key difference is that WebXR has integrated support for the advanced input controllers that are used with most mixed reality headsets, while WebVR relied on the Gamepad API to support the controllers. In WebXR, the primary select and squeeze actions are directly supported using events, while other controls are available through a special WebXR-specific implementatio...
Geometry and reference spaces in WebXR - Web APIs
At a fundamental level, rendering of scenes for WebXR presentation in either augmented reality or virtual reality contexts is performed using WebGL, so the two APIs share much of the same design language. However, in order to provide the ability to present scenes in true 3D using XR headsets and other such equipment, WebXR has additional concepts that must be understood. In this article, we introduce the ways in which WebXR expands upon the geometry of WebGL, and how the positions and orientations of objects--both physical and virtual--are described in relation to one another using spaces and, in particular, reference spaces. The article Spatial tracking in WebXR builds upon the information provided here to cover how the physical position and orientation of the user's head, as well as pot...
Inputs and input sources - Web APIs
se it simply doesn't have any added controls on it. This gamepad object is not only used to obtain access to specialty buttons, trackpads, and so forth, but also provides a way to more directly access and monitor the controls that serve as the primary select and squeeze inputs, since these are included in its buttons list. Because this use of the Gamepad interface is a convenience rather than a true application of the Gamepad API, there are several differences between how it's used with WebXR and how it's used in Gamepad API applications. The most notable--but not the only--difference is that WebXR adds the xr-standard gamepad mapping, expanding the GamepadMappingType enumerated type. This gamepad mapping defines how the controls on a typical one-hand handheld VR controller are mapped to gam...
Rendering and the WebXR frame animation callback - Web APIs
lated by subtracting from the current time as specified by the currentFrameTime parameter the saved time at which the last frame was rendered, lastFrameTime. The result is a DOMHighResTimeStamp value indicating the number of milliseconds that have elapsed since the last frame was rendered. We can use this value while drawing the scene to ensure we move everything the appopriate distance given the true elapsed time, rather than assuming that the callback will be fired at a consistent frame rate. This elapsed time is saved in the variable deltaTime, and the value of lastFrameTime is replaced with this frame's time, ready to compute the differential for the next frame. It's now time to actually render the scene for each eye. We iterate over the views within the viewer poses's views array. For ea...
WebXR Device API - Web APIs
if the position and/or orient Extensions to the WebGL API The WebGL API is extended by the WebXR specification to augment the WebGL context to allow it to be used to render views for display by a WebXR device. WebGLRenderingContextBase.makeXRCompatibile() Configures the WebGL context to be compatible with WebXR. If the context was not initially created with the xrCompatible property set to true, you must call makeXRCompatible() prior to attempting to use the WebGL context for WebXR rendering. Returns a Promise which resolves once the context has been prepared, or is rejected if the context cannot be configured for use by WebXR. Guides and tutorials The following guides and tutorials are a great resource to learn how to comprehend WebXR and the underlying 3D and VR/AR graphics concept...
Using the Web Storage API - Web APIs
space, but storage is actually available. Our feature detection should take these scenarios into account. ...
Functions and classes available to Web Workers - Web APIs
returned object. 21 (21) and 26 (26) for URL() constructor No support No support No support WebGL with OffscreenCanvas WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins. 44 (44) behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true. No support No support No support WebSocket Creates and returns a new WebSocket object; this mimics the behavior of the standard WebSocket() constructor. 37 (37) 11.0 (Yes) (Yes) Worker Creates a new Worker. Yes, workers can spawn more workers. 3.5 (1.9.1) 10.0 Enabled since Chrome 69 No support WorkerGlobalScope The global sco...
Using Web Workers - Web APIs
which will simulate the behavior of a value that is cloned and not shared during the passage from a worker to the main page or vice versa: function emulateMessage(vVal) { return eval('(' + JSON.stringify(vVal) + ')'); } // Tests // test #1 var example1 = new Number(3); console.log(typeof example1); // object console.log(typeof emulateMessage(example1)); // number // test #2 var example2 = true; console.log(typeof example2); // boolean console.log(typeof emulateMessage(example2)); // boolean // test #3 var example3 = new String('Hello World'); console.log(typeof example3); // object console.log(typeof emulateMessage(example3)); // string // test #4 var example4 = { 'name': 'John Smith', "age": 43 }; console.log(typeof example4); // object console.log(typeof emulateMessage(exam...
Window.confirm() - Web APIs
Web › API › Window › confirm
If a browser is ignoring in-page dialogs, then the returned value is always false. ...
Window: devicemotion event - Web APIs
Editor's Draft ...
Window: deviceorientation event - Web APIs
Editor's Draft ...
window.dump() - Web APIs
Web › API › Window › dump
ugging content to a user's console when they might not be interested in it at all. Note that dump output from XPCOM components goes to stderr, while dump called elsewhere will output to stdout. In Gecko dump() is disabled by default - it doesn't do anything but doesn't raise an error either. To see the dump output you have to enable it by setting the preference browser.dom.window.dump.enabled to true. You can set the preference in about:config or in a user.js file. Note: this preference is not listed in about:config by default, you may need to create it (right-click the content area -> New -> Boolean). On Windows, you will need a console to actually see anything. If you don't have one already, closing the application and re-opening it with the command line parameter -console should create th...
Window.find() - Web APIs
Web › API › Window › find
Note: Support for Window.find() might change in future versions of Gecko. See bug 672395. The Window.find() method finds a string in a window. Syntax window.find(aString, aCaseSensitive, aBackwards, aWrapAround, aWholeWord, aSearchInFrames, aShowDialog); aString The text string for which to search. aCaseSensitive Boolean. If true, specifies a case-sensitive search. aBackwards Boolean. If true, specifies a backward search. aWrapAround Boolean. If true, specifies a wrap around search. aWholeWord Unimplemented Boolean. If true, specifies a whole word search. This is not implemented; see bug 481513. aSearchInFrames Boolean. If true, specifies a search in frames. Returns true if the string is found; otherwise, false. Example JavaScript findString = fu...
Window.frames - Web APIs
Web › API › Window › frames
Returns the window itself, which is an array-like object, listing the direct sub-frames of the current window. Syntax frameList = window.frames; frameList is a list of frame objects. It is similar to an array in that it has a length property and its items can be accessed using the [i] notation. frameList === window evaluates to true. Each item in the window.frames pseudo-array represents the Window object corresponding to the given <frame>'s or <iframe>'s content, not the (i)frame DOM element (i.e., window.frames[0] is the same thing as document.getElementsByTagName("iframe")[0].contentWindow). For more details about the returned value, refer to this thread on mozilla.dev.platform. Example var frames = window.frames; // or // var frames = window.parent.frames; for (var i = 0; i < ...
Window.fullScreen - Web APIs
Web › API › Window › fullScreen
indowRef.fullScreen; With chrome privileges, the property is read-write, otherwise it is read-only. Bear in mind that if you try to set this property without chrome privileges, it will not throw an exception and instead just silently fail. This is to prevent scripts designed to set this property in Internet Explorer from breaking. Return value isInFullScreen A boolean. Possible Values: true: The window is in full screen mode. false: The window is not in full screen mode. Notes Switching between regular window and full screen will fire the "resize" event on the corresponding window. Example if (window.fullScreen) { // it's fullscreen! } else { // not fullscreen! } ...
Window: load event - Web APIs
Web › API › Window › load event
y-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } JS const log = document.querySelector('.event-log-contents'); const reload = document.querySelector('#reload'); reload.addEventListener('click', () => { log.textContent =''; window.setTimeout(() => { window.location.reload(true); }, 200); }); window.addEventListener('load', (event) => { log.textContent = log.textContent + 'load\n'; }); document.addEventListener('readystatechange', (event) => { log.textContent = log.textContent + `readystate: ${document.readyState}\n`; }); document.addEventListener('DOMContentLoaded', (event) => { log.textContent = log.textContent + `DOMContentLoaded\n`; }); Result ...
Window: online event - Web APIs
Note: This event shouldn't be used to determine the availability of a particular website. Network problems or firewalls might still prevent the website from being reached. ...
Obsolete features - Web APIs
scape 6.x, Netscape 7.x and Mozilla browser. It renders the Bookmarks Toolbar in Firefox. In addition to the Personal Toolbar, Mozilla browser will render the Site Navigation Bar if such toolbar is visible, present in the parent window. Mozilla and Firefox users can force new windows to always render the Personal Toolbar/Bookmarks toolbar by setting dom.disable_window_open_feature.personalbar to true in about:config or in their user.js file. ...
Window: popstate event - Web APIs
eld name set to off is reset. See The HTML autocomplete attribute for more about the autocomplete field names and how autocomplete works. If new-entry's document is already fully loaded and ready--that is, its readyState is complete--and the document is not already visible, it's made visible and the pageshow event is fired at the document with the PageTransitionEvent's persisted attribute set to true. The document's URL is set to that of new-entry. If the history traversal is being performed with replacement enabled, the entry immediately prior to the destination entry (taking into account the delta parameter on methods such as go()) is removed from the history stack. If the new-entry doesn't have persisted user state and its URL's fragment is non-null, the document is scrolled to that fra...
Window.scrollX - Web APIs
Web › API › Window › scrollX
t viewport. If there is no viewport, the returned value is 0. Example This example checks the current horizontal scroll position of the document. If it's greater than 400 pixels, the window is scrolled back to the beginning. if (window.scrollX > 400) { window.scroll(0,0); } Notes The pageXOffset property is an alias for the scrollX property: window.pageXOffset == window.scrollX; // always true For cross-browser compatibility, use window.pageXOffset instead of window.scrollX. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A fully compatible example: var x = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || doc...
Window.scrollY - Web APIs
Web › API › Window › scrollY
ndow.scroll(0, 0); // reset the scroll position to the top left of the document. } window.scrollByPages(1); Notes Use this property to check that the document hasn't already been scrolled when using relative scroll functions such as scrollBy(), scrollByLines(), or scrollByPages(). The pageYOffset property is an alias for the scrollY property: window.pageYOffset === window.scrollY; // always true For cross-browser compatibility, use window.pageYOffset instead of window.scrollY. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A fully compatible example: var supportPageOffset = window.pageXOffset !== undefined; var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"); var ...
Window.window - Web APIs
Web › API › Window › window
indow object points to the window object itself. Thus, the following expressions all return the same window object: window.window window.window.window window.window.window.window // ... In web pages, the window object is also a global object. This means: global variables of your script are in fact properties of window: var global = {data: 0}; alert(global === window.global); // displays "true" you can access built-in properties of the window object without having to type window. prefix: setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout. alert(window === window.window); // displays "true" The point of having the window property refer to the object itself, was likely to make it easy to refer to the global object. Otherwise, you'd have to do a manual var...
WindowEventHandlers.onhashchange - Web APIs
s navigating. oldURL DOMString The previous URL from which the window was navigated. Polyfill for event.newURL and event.oldURL // Let this snippet run before your hashchange event binding code if (!window.HashChangeEvent)(function(){ var lastURL = document.URL; window.addEventListener("hashchange", function(event){ Object.defineProperty(event, "oldURL", {enumerable:true,configurable:true,value:lastURL}); Object.defineProperty(event, "newURL", {enumerable:true,configurable:true,value:document.URL}); lastURL = document.URL; }); }()); Specifications Specification Status Comment HTML Living StandardThe definition of 'onhashchange' in that specification. Living Standard HTML 5.1The definition of 'GlobalEventHa...
WindowOrWorkerGlobalScope.isSecureContext - Web APIs
Syntax var isItSecure = self.isSecureContext; // or just isSecureContext Value A Boolean. ...
WindowOrWorkerGlobalScope - Web APIs
olean value that indicates whether a SharedArrayBuffer can be sent via a Window.postMessage() call. WindowOrWorkerGlobalScope.indexedDB Read only Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an IDBFactory object. WindowOrWorkerGlobalScope.isSecureContext Read only Returns a boolean indicating whether the current context is secure (true) or not (false). WindowOrWorkerGlobalScope.origin Read only Returns the origin of the global scope, serialized as a string. Methods These methods are defined on the WindowOrWorkerGlobalScope mixin, and implemented by Window and WorkerGlobalScope. WindowOrWorkerGlobalScope.atob() Decodes a string of data which has been encoded using base-64 encoding. WindowOrWorkerGlobalScope.btoa() C...
WritableStream.locked - Web APIs
leStream is locked to a writer. Syntax var locked = writableStream.locked; Value A Boolean indicating whether or not the writable stream is locked. Examples const writableStream = new WritableStream({ write(chunk) { ... }, close() { ... }, abort(err) { ... } }, queuingStrategy); ... const writer = writableStream.getWriter(); writableStream.locked // should return true, as the stream has been locked to a writer Specifications Specification Status Comment StreamsThe definition of 'locked' in that specification. Living Standard Initial definition. ...
WritableStreamDefaultWriter.ready - Web APIs
nk. The second also checks whether the the WritableStream is done writing, but this time because the writing must be finished before the writer can be closed. function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter var defaultWriter = writableStream.getWriter(); var encoder = new TextEncoder(); var encoded = encoder.encode(message, {stream: true}); encoded.forEach(function(chunk) { // Make sure the stream and its writer are able to // receive data. defaultWriter.ready .then(function() { defaultWriter.write(chunk) .then(function() { console.log("Chunk written to sink.); }) .catch(function(err) { console.log("Chunk error: " + err); }); }); // Call ready again to ensu...
XMLDocument.async - Web APIs
Web › API › XMLDocument › async
document.async can be set to indicate whether a XMLDocument.load() call should be an asynchronous or synchronous request. true is the default value, indicating that documents should be loaded asynchronously. (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'); ...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
cert.sha1Fingerprint + "\n"); var validity = cert.validity.QueryInterface(Ci.nsIX509CertValidity); dump("\tValid from " + validity.notBeforeGMT + "\n"); dump("\tValid until " + validity.notAfterGMT + "\n"); } } catch(err) { alert(err); } } function test(url) { var req = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(); req.open('GET', url, true); req.addEventListener("error", function(e) { var error = createTCPErrorFromFailedXHR(req); dumpSecurityInfo(req, error); }, false); req.onload = function(e) { dumpSecurityInfo(req); }; req.send(); } Then test("https://addons.mozilla.org"); produced the following output in my console: Connection status: succeeded Security Info: Security sta...
XMLHttpRequest.abort() - Web APIs
LHttpRequest.UNSENT (0) and the request's status code is set to 0. Syntax XMLHttpRequest.abort() Parameters None. ...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
Example This example examines the headers in the request's readystatechange event handler, XMLHttpRequest.onreadystatechange. The code shows how to obtain the raw header string, as well as how to convert it into an array of individual headers and then how to take that array and create a mapping of header names to their values. ...
XMLHttpRequest.getResponseHeader() - Web APIs
t is created and sent, and a readystatechange handler is established to look for the readyState to indicate that the headers have been received; when that is the case, the value of the Content-Type header is fetched. If the Content-Type isn't the desired value, the XMLHttpRequest is canceled by calling abort(). ...
XMLHttpRequest.mozAnon - Web APIs
XMLHttpRequest.mozAnon is a boolean. If true, the request will be sent without cookies or authentication headers. ...
XMLHttpRequest.mozBackgroundRequest - Web APIs
Note: This method is not available from Web content. It requires elevated privileges to access. XMLHttpRequest.mozBackgroundRequest is a Boolean, indicating if the object represents a background service request. If true, no load group is associated with the request, with security dialogs prevented from being shown to the user. In cases in where a security dialog (such as authentication or a bad certificate notification) would normally be shown, this request fails instead. Note: This property must be set before calling open(). ...
XMLHttpRequest.mozSystem - Web APIs
mozSystem is a boolean. If true, the same origin policy is not enforced on the request. ...
XMLHttpRequest.multipart - Web APIs
e may also be large incompatibilities between implementations and the behavior may change in the future. Obsolete since Gecko 22 This Gecko-only feature was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or responseText from progress events instead. This boolean indicates if the response is expected to be a stream of possibly multiple XML documents. If set to true, the content type of the initial response must be multipart/x-mixed-replace or an error will occur. All requests must be asynchronous. This enables support for server push; for each XML document that's written to this request, a new XML DOM document is created and the onload handler is called between documents. Note: When this is set, the onload handler and other event handlers are not reset a...
XMLHttpRequest.onreadystatechange - Web APIs
of the XMLHttpRequest changes. Warning: This should not be used with synchronous requests and must not be used from native code. Syntax XMLHttpRequest.onreadystatechange = callback; Values callback is the function to be executed when the readyState changes. ...
XMLHttpRequest.open() - Web APIs
ch open() has already been called) is the equivalent of calling abort(). Syntax XMLHttpRequest.open(method, url[, async[, user[, password]]]) Parameters method The HTTP request method to use, such as "GET", "POST", "PUT", "DELETE", etc. Ignored for non-HTTP(S) URLs. url A DOMString representing the URL to send the request to. async Optional An optional Boolean parameter, defaulting to true, indicating whether or not to perform the operation asynchronously. If this value is false, the send() method does not return until the response is received. If true, notification of a completed transaction is provided using event listeners. This must be true if the multipart attribute is true, or an exception will be thrown. Note: Synchronous requests on the main thread can be easily disruptive...
XMLHttpRequest.readyState - Web APIs
ent in versions of Internet Explorer earlier than 11. Instead of UNSENT, OPENED, HEADERS_RECEIVED, LOADING and DONE, the names READYSTATE_UNINITIALIZED (0), READYSTATE_LOADING (1), READYSTATE_LOADED (2), READYSTATE_INTERACTIVE (3) and READYSTATE_COMPLETE (4) are used. ...
XMLHttpRequest.response - Web APIs
ssed into the callback function provided to load(). The content is handled as raw text data (since nothing here is overriding the default responseType). ...
XMLHttpRequest.responseText - Web APIs
has been received when the value of readyState becomes XMLHttpRequest.DONE (4), and status becomes 200 ("OK"). Exceptions InvalidStateError The XMLHttpRequest.responseType is not set to either the empty string or "text". Since the responseText property is only valid for text content, any other value is an error condition. ...
XMLHttpRequest.responseURL - Web APIs
The read-only XMLHttpRequest.responseURL property returns the serialized URL of the response or the empty string if the URL is null. If the URL is returned, any URL fragment present in the URL will be stripped away. ...
XMLHttpRequest.statusText - Web APIs
ntains the text of the response status, such as "OK" or "Not Found". If the request's readyState is in UNSENT or OPENED state, the value of statusText will be an empty string. If the server response doesn't explicitly specify a status text, statusText will assume the default value "OK". ...
XMLHttpRequest.timeout - Web APIs
ror exception. When a timeout happens, a timeout event is fired. Note: You may not use a timeout for synchronous requests with an owning window. Using a timeout with an asynchronous request In Internet Explorer, the timeout property may be set only after calling the open() method and before calling the send() method. Example var xhr = new XMLHttpRequest(); xhr.open('GET', '/server', true); xhr.timeout = 2000; // time in milliseconds xhr.onload = function () { // Request finished. Do processing here. }; xhr.ontimeout = function (e) { // XMLHttpRequest timed out. Do something here. }; xhr.send(null); Specifications Specification Status Comment XMLHttpRequest Living Standard WHATWG living standard ...
XMLHttpRequest - Web APIs
g the upload process. XMLHttpRequest.withCredentials Is a Boolean that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers. Non-standard properties XMLHttpRequest.channelRead only Is a nsIChannel. The channel used by the object when performing the request. XMLHttpRequest.mozAnonRead only Is a boolean. If true, the request will be sent without cookie and authentication headers. XMLHttpRequest.mozSystemRead only Is a boolean. If true, the same origin policy will not be enforced on the request. XMLHttpRequest.mozBackgroundRequest Is a boolean. It indicates whether or not the object represents a background service request. XMLHttpRequest.mozResponseArrayBuffer Obsolete since Gecko 6 Read only Arra...
XMLHttpRequestEventTarget.onabort - Web APIs
onabort is the function called when an XMLHttpRequest transaction is aborted, such as when the XMLHttpRequest.abort() function is called. Syntax XMLHttpRequest.onabort = callback; Values callback is the function to be executed when the transaction is aborted. Example var xmlhttp = new XMLHttpRequest(), method = 'GET', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onabort = function () { console.log('** The request was aborted'); }; xmlhttp.send(); //.. xmlhttp.abort(); // This will invoke our onabort handler above Specifications Specification Status Comment XMLHttpRequest Living Standard WHATWG living standard ...
XMLHttpRequestEventTarget.onerror - Web APIs
The XMLHttpRequestEventTarget.onerror is the function called when an XMLHttpRequest transaction fails due to an error. Syntax XMLHttpRequest.onerror = callback; Values callback is the function to be executed when the request fails. ...
XMLHttpRequestEventTarget.onload - Web APIs
est.onload = callback; Values callback is the function to be executed when the request completes successfully. It receives a ProgressEvent object as its first argument. The value of this (i.e. the context) is the same XMLHttpRequest this callback is related to. ...
XMLHttpRequestEventTarget.onloadstart - Web APIs
XMLHttpRequestEventTarget.onloadstart is the function called when an XMLHttpRequest transaction starts transferring data. ...
XMLHttpRequestEventTarget.onprogress - Web APIs
to be called periodically before the request is completed. Event event.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
XPathResult.invalidIteratorState - Web APIs
Note: This feature is available in Web Workers. Syntax var iteratorState = result.invalidIteratorState; Return value A boolean value indicating whether the iterator has become invalid. Example The following example shows the use of the invalidIteratorState property. ...
XPathResult - Web APIs
f a given node. Since XPath expressions can result in a variety of result types, this interface makes it possible to determine and handle the type and value of the result. Properties XPathResult.booleanValueRead only A boolean representing the value of the result if resultType is BOOLEAN_TYPE. XPathResult.invalidIteratorStateRead only Signifies that the iterator has become invalid. It is true if resultType is UNORDERED_NODE_ITERATOR_TYPE or ORDERED_NODE_ITERATOR_TYPE and the document has been modified since this result was returned. XPathResult.numberValueRead only A number representing the value of the result if resultType is NUMBER_TYPE. XPathResult.resultTypeRead only A number code representing the type of the result, as defined by the type constants. XPathResult.singleNodeV...
XRInputSource.targetRaySpace - Web APIs
as their target ray space, since the gaze input comes from the viewer's head. This shared space represents the same location as the space returned by the XRSession method requestReferenceSpace(), but is maintained as a different object to allow for future enhancements to the API. The target ray space reported by tracked pointer inputs (targetRayMode of tracked-pointer) is actually based upon the true spatial position and orientation of the input device. To determine the position and orientation of the target ray while rendering a frame, pass it into the XRFrame method getPose() method, then use the returned XRPose object's transform to gather the spatial information you need. Example This fragment of code shows part of a function to be called once every frame. It looks for inputs which ha...
XRPose - Web APIs
Web › API › XRPose
ven 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). If any component of the transform is computed or created artificially (such as by using mouse or keyboard controls to move through space), this value is instead true, indicating that the transform is in part emulated in software. Example <<<--- TODO: Needs example --->>> Specifications Specification Status Comment WebXR Device APIThe definition of 'XRPose' in that specification. Working Draft Initial definition. ...
XRReferenceSpace: reset event - Web APIs
e world to resynchronize to the device's current orientation. That works by sending a `reset` event to the reference space or reference spaces that are based on the headset's orientation. Handling discontinuities You can handle jumps in the viewer's position by watching the Boolean XRPose property emulatedPosition. 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. This is typically the desired behavior if your site or app doesn't simulate motion through the space by expressly changing the position and/or orientation of the viewer (rather than the user's physical movements being used by the XR device to introduce movement). H...
XRRenderState.baseLayer - Web APIs
as the source of the world's contents when rendering each frame of the scene. See the examples below to see how to use updateRenderState() to set the current XRWebGLLayer used for rendering the scene. Examples You can set the XRWebGLLayer used for rendering by calling updateRenderState(), like this: let canvas = document.querySelector("canvas"); gl = canvas.getContext("webgl", { xrCompatible: true }); setNewWebGLLayer(); function setNewWebGLLayer(gl) { if (!gl) { /* WebGL not available */ return; } xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSession, gl); }); }; Here, the canvas obtained in the first line is the canvas into which WebGL is going to draw. That context is passed into new XRWebGLLayer() to create an XRWebGLLayer which uses the contents o...
XRRigidTransform.position - Web APIs
if that fails (probably because bounded-floor isn't supported), we try requesting a local-floor reference space. If we're not in an immersive session, we instead request a viewer reference space. In all cases, once the space has been obtained, it gets passed into the refSpaceCreated() function. For immersive spaces, the specified space i...
XRSession.requestReferenceSpace() - Web APIs
and inline, though it's most useful for inline sessions. It's particularly useful when determining the distance between the viewer and an input, or when working with offset spaces. Otherwise, typically, one of the other reference space types will be used more often. XRReferenceSpace Return value A Promise that resolves with an XRReferenceSpace object. Exceptions Rather than throwing true exceptions, requestReferenceSpace() rejects the returned promise with a DOMException whose name is found in the list below: NotSupportedError The requested reference space is not supported. Specifications Specification Status Comment WebXR Device APIThe definition of 'requestReferenceSpace()' in that specification. Working Draft Initial definition. ...
XRSession: visibilitychange event - Web APIs
hanged. Examples This example demonstrates how to listen for a visibilitychange event on a WebXR session, using addEventListener() to begin listening for the event: navigator.xr.requestSession("inline").then((xrSession) => { xrSession.addEventListener("visibilitychange", e => { switch(e.session.visiblityState) { case "visible": case "visible-blurred": mySessionVisible(true); break; case "hidden": mySessionVisible(false); break; } }); }); When a visibility state change occurs, the event is received and dispatched to a function mySessionVisible(), with a Boolean parameter indicating whether or not the session is presently being displayed to the user. You can also create the event handler by assigning it to the XRSession's onvisi...
XRSessionEvent() - Web APIs
session to change. It reacts by calling a function mySessionVisible() with a Boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfigure a worker that handles rendering the scene. 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. Working Draft Initial definition. ...
XRSessionEvent.session - Web APIs
vent is about. Syntax xrSession = xrSessionEvent.session; Value An XRSession object indicating which WebXR session the event refers to. Examples In this example, the session property is used to obtain the session object to manage when an event is received. 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. Specifications Specification Status Comment WebXR Device APIThe definition of 'XRSessionEvent.session' in that specification. Working Draft Initial definition. ...
XRSessionEvent - Web APIs
session to change. It reacts by calling a function mySessionVisible() with a Boolean indicating whether or not the session is visible; this function might, for instance, spin up or reconfigure a worker that handles rendering the scene. 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. Working Draft Initial definition. ...
XRSystem: devicechange event - Web APIs
by toggling the availability of the "Enter XR" button based on whether or not any immersive devices are currently available. 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. If there is, the button to enter XR mode is enabled; otherwise it's disabled. You can also use the ondevicechange event handler property to set a single handler for devicechange ev...
XRSystem: requestSession() - Web APIs
le on any user agent offering WebXR API support. sessionInit Optional A XRSessionInit object providing options to configure the new XRSession. See Specifying session options for details on how to configure a WebXR session. Return value A Promise that resolves with an XRSession object if the device and user agent support the requested mode and features. Exceptions This method doesn't throw true exceptions; instead, it rejects the returned promise, passing into it a DOMException whose name is one of the following: InvalidStateError The requested session mode is immersive-vr but there is already an immersive VR session either currently active or in the process of being set up. There can only be one immersive VR session at a time. NotSupportedError There is no WebXR-compatible device...
XRView - Web APIs
Web › API › XRView
!mouseYaw && !mousePitch && !axialDistance && !transverseDistance && !verticalDistance) { return refSpace; } // Compute the quaternion used to rotate the image based // on the pitch and yaw. quat.identity(inverseOrientation); quat.rotateX(inverseOrientation, inverseOrientation, -mousePitch); quat.rotateY(inverseOrientation, inverseOrientation, -mouseYaw); // Compute the true "up" vector for our object. vec3.cross(vecX, vecY, cubeOrientation); vec3.cross(vecY, cubeOrientation, vecX); // Now compute the transform that teleports the object to the // specified point and save a copy of it to display to the user // later; otherwise we probably wouldn't need to save mouseMatrix // at all. let newTransform = new XRRigidTransform({x: transverseDistance, ...
XRWebGLLayer.framebuffer - Web APIs
RAMEBUFFER_UNSUPPORTED error (0x8CDD) to be reported. 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. Opaque framebuffers initialized without specifying a stencil will not have a stencil buffer. Opaque framebuffers will not have an alpha channel available unless the alpha property is true when creating the layer. The XR compositor assumes that opaque framebuffers use colors with premultiplied allpha, regardless of whether or not the WebGL context's premultipliedAlpha context attribute is set. Note: The depth and stencil properties are not required to be supported in order for a browser to be construed as having full WebGL support. The default configuration of a new framebuff...
XRWebGLLayerInit.alpha - Web APIs
The alpha property is a Boolean value which, if present and set to true in the XRWebGLLayerInit dictionary passed into the XRWebGLLayer() constructor, specifies that the new layer's color buffer is to include an alpha channel. Otherwise, the color buffer won't have an alpha channel. The default is true. Syntax let layerInit = { alpha: boolValue }; let glLayer = new XRWebGLLayer(xrSession, gl, layerInit); let glLayer = new XRWebGLLayer(xrSession, gl, { alpha: boolValue }); Value A Boolean which can be set to true to request that the new WebGL layer for rendering the WebXR scene is to have an alpha channel. Example In this example, a new XRWebGLLayer is created for a WebXR session, xrSession, without an alpha channel. xrSession.updateRenderState({ baseLayer: new XRWebGLLayer(xrSe...
XRWebGLLayerInit.antialias - Web APIs
The Boolean antialias property, if present and set to true in the XRWebGLLayerInit object provided as the XRWebGLLayer() constructor's layerInit parameter, requests that the new WebGL rendering layer support anti-aliasing. If this property is missing or is false, anti-aliasing is not desired. There is no way to request a specific anti-aliasing format or level; this decision is left up to the user agent. Syntax let layerInit = { antialias: boolValue }; let glLayer = new XRWebGLLayer(xrSession, gl, layerInit); let glLayer = new XRWebGLLayer(xrSession, gl, { antialias: boolValue }); Value A Boolean value which can be set to true to request anti-aliasing support in the new WebGL rendering layer. If false, anti-aliasing is not desired. Usage notes The state of anti-aliasing for the co...
XRWebGLLayerInit.stencil - Web APIs
ffer values correspond to pixels which should be drawn to the screen during each frame. 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. The default value is true. Example In this example, a new XRWebGLLayer is created for a WebXR session, xrSession, without 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. Working Draft I...
msCachingEnabled - Web APIs
There may also be large incompatibilities between implementations and the behavior may change in the future. The msCachingEnabled method gets the current caching state for an XMLHttpRequest. This proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax var cacheState = XMLHttpRequest.msCachingEnabled(); Parameters cacheState[out, retval] Type = boolean. If true, XMLHttpRequest is cached to disk. If false, it is not written to disk. Return value Type: boolean. If true, XMLHttpRequest is cached to disk. If false, it is not written to disk. See also msCaching property Microsoft API extensions ...
msGetPropertyEnabled - Web APIs
or may change in the future. The msGetPropertyEnabled returns whether a given property in the style object is enabled. This proprietary method is specific to Internet Explorer browser. Syntax var retVal = style.msGetPropertyEnabled(name); Parameters name [in] Type: String The name of the property to enable. Return value Type: Boolean If false, the property is not enabled. If true, the property is enabled. See also Microsoft API extensions ...
msPutPropertyEnabled - Web APIs
it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future. The msPutPropertyEnabled method sets whether a given property in the style object is enabled or disabled. This proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax var retval = style.msPutPropertyEnabled(propertyName, true); Parameters name[in]: Name of the property. (String) boolean[in]: True = Enable the property. False = Disable the property. Return value Type = HRESULT: If this method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. See also CSS Style Declaration Microsoft API extensions ...
Using the aria-labelledby attribute - Accessibility
</div> ... </div> Notes The most common accessibility API mapping for a label is the accessible name property Used by ARIA roles All elements of the base markup Related A...
Using the group role - Accessibility
this technique. The information provided above is one of those opinions and therefore not normative. Examples Example 1: Using the group role with a HTML tree view The snippet below shows how the group role is added directly into the html source code. ...
Using the log role - Accessibility
formation is only added to the end of the log. When this role is added to an element, the browser will send out an accessible log event to assistive technology products which can then notify the user about it. By default updates contain only the changes to the live region and these are announced when the user is idle. Where the user needs to hear the entire live region upon a change aria-atomic="true" should be set. To have announcements made as soon as possible and where the user may be interrupted, aria-live="assertive" can be set for more aggressive updates. Possible effects on user agents and assistive technology When the log role is added to an element, or such an element becomes visible, the user agent should do the following: Expose the element as having a log role in the operati...
Using the radio role - Accessibility
class="radiogroup" id="rg1" role="radiogroup" aria-labelledby="rg1_label"> <li id="r1" tabindex="-1" role="radio" aria-checked="false"> <img role="presentation" src="radio-unchecked.gif" /> Thai </li> <li id="r2" tabindex="-1" role="radio" aria-checked="false"> <img role="presentation" src="radio-unchecked.gif" /> Subway </li> <li id="r3" tabindex="0" role="radio" aria-checked="true"> <img role="presentation" src="radio-checked.gif" /> Radio Maria </li> </ul> Working Examples: Notes ARIA attributes used Related ARIA techniques Compatibility TBD: Add support information for common UA and AT product combinations Additional resources ...
ARIA: tabpanel role - Accessibility
ntics and behavior you require already built in, instead of re-purposing an element and adding an ARIA role, state or property to make it accessible, then do so. Then post full details in best practices section below. Examples Fill in a simple example that nicely shows a typical usage of the property, then perhaps some more complex examples. <div role="tablist"> <div role="tab" aria-selected="true" aria-controls="tabpanel-id" id="tab-id" tabindex="0">Tab label</div> Accessibility concerns Optionally, warn of any potential accessibility concerns that exist with using this property, and how to work around them. Remove this section if there are none to list. Best practices Optionally, here list any best practices that exist for this role. Remove the section if none exist. Added benefits...
ARIA: alert role - Accessibility
lert role is used to provide the user with important, and usually time-sensitive, information, and often to tell the user an element has been dynamically updated. The alert role is added to the node containing an alert message, not the element causing the alert to be triggered. Alerts are assertive live regions. Setting role="alert" is equivalent to setting aria-live="assertive" and aria-atomic="true". They don't receive focus, and therefore focus does not need to be managed and no user interaction should be required. The most important thing to know about the alert role is that it is for dynamic content. It is perfect for situations such as when a user fills out a form and JavaScript is used to add an error message - the alert would immediately read out the message. It should not be used on...
ARIA: document role - Accessibility
t events, such as Up or Down arrow keyboard events, to control the reading cursor. In contrast to the article role, the document role does not have any relation to other elements with a document role, it merely has a relationship to the containing composit widget. An article can have associated articles. 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. Other values include the default undefined which means the document is not collapsible. tabindex="0" Used to make it focusable so the assistive technology user can tab to it and start reading right away. Keyboard interactions The element should be made focusable by setting th...
ARIA: gridcell role - Accessibility
nderstand the position and relationship of the gridcell element to the rest of the table-style grouping of content. Interactive grids and treegrids Editable cells Both td elements and elements with a role of gridcell applied to them can be made editable, mimicking functionality similar to editing a spreadsheet. This is done by applying the HTML contenteditable attribute. <td contenteditable="true">Notes</td> <div role="gridcell" contenteditable="true">Item cost</div> contenteditable will make the element it is applied to focusable via the Tab key. If a gridcell is conditionally toggled into a state where editing is prohibited, toggle aria-readonly on the gridcell element. Expandable cells In a treegrid, gridcells may be made expandable by toggling the aria-expanded attribute. Note th...
Web applications and ARIA FAQ - Accessibility
int of view, the native HTML defines the semantic meaning and behavior of an element, with ARIA attributes acting as a layer on top to help support the AT API. Though on its own ARIA will not change any styles, as with any HTML attributes, CSS can take advantage of ARIA attributes as element selectors. This may provide a convenient mechanism to style ARIA-enabled widgets. .tab-panel[aria-hidden="true"] { display: none; } .tab-panel[aria-hidden="false"] { display: block; } What about validation? The new attributes introduced in ARIA, such as role and those prefixed with aria-, aren't officially part of the HTML 4 or XHTML 4 specifications. As a result, pages that include ARIA may not validate using tools such as the W3C's Markup Validator. The first potential solution to this prob...
HTML To MSAA - Accessibility
TEM_ READONLY if @readonly attribute is used n/a "activate" n/a input @type=password ROLE_SYSTEM_ TEXT n/a n/a STATE_SYSTEM_ READONLY if @readonly attribute is used STATE_SYSTEM_ PROTECTED n/a "activate" n/a input type="checkbox" ROLE_SYSTEM_ CHECKBUTTON n/a n/a STATE_SYSTEM_ MARQUEED used as state checkable STATE_SYSTEM_ MIXED for HTML 5 if intermediate property of DOM element returns true STATE_SYSTEM_ CHECKED if checked property of DOM element returns true n/a "check"/"uncheck"/"cycle" depending on state EVENT_OBJECT_ STATECHANGE when state is changed input type="radio" ROLE_SYSTEM_ RADIOBUTTON n/a n/a STATE_SYSTEM_ MARQUEED used as state checkable STATE_SYSTEM_ CHECKED if checked property of DOM element returns true n/a "select" EVENT_OBJECT_ STATECHANGE when state is cha...
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
f data nodes the Accessible object is exposing through COM, and what the screen boundaries of each object are. In addition, MSDN has improved their MSAA documentation. When to use MSAA, and when not to It's a common mistake to say that MSAA is not worth using, for a number of reasons. Myths for not using MSAA Myth: MSAA doesn't really work Reality: MSAA works really well for dialogs and UI. True, it's not great for documents, but it's the only existing widely-used standard for exposing accessibility. Myth: MSAA is too slow Reality: Assistive technology vendors have found ways around most of the performance problems related to out-of-process COM method calls. Just make sure to have decent performance on your end. Myth: "MSAA sucks" Reality: This statement may come from another enginee...
Accessibility Information for Web Authors - Accessibility
r accessibility checkers. No document upload needed and no additional application to launch; everything is accessible within the Firefox browser. This HTML advanced validator Firefox extension is very resourceful and highly customizable. It's an extension add-on to Firefox 2.x and Firefox 3.x. It not only checks and reports possible markup errors and warnings (based on W3C Tidy and/or based on true SGML validation) but it can also report accessibility errors and warnings according to selectable accessibility guidelines (Section 508, WCAG Priorities 1, 2 or 3). Its accessibility report is viewable in the View Source window (View > Source code Ctrl+U or right-click on the status bar). Two panes are added at the bottom of the view source code window: the left pane contains the errors and warni...
Mobile accessibility checklist - Accessibility
MUST be provided. Headings MUST not break hierarchical structure <h1>Top level heading</h1> <h2>Secondary heading</h2> <h2>Another secondary heading</h2> <h3>Low level heading</h3> ARIA Landmark Roles SHOULD be used to describe an app or document structure, such as banner, complementary, contentinfo, main, navigation, search. For touch events, at least one of the following must be true (WCAG 2.1: Pointer Cancellation): The down-event should not be used to trigger any action The action is triggered on the up event and an option to abort the action before its completion is available or an option to undo the action after its completion The up-event will undo any action that was triggered on a down event It is essential to trigger the action on the down event. For ex...
Perceivable - Accessibility
.5:1. Larger text is defined as at least 18pt, or 14pt bold. See Color and color contrast. 1.4.7 Low or no background audio (AAA) Prerecorded audio recordings that primarily feature speech should have minimal background noise, so the content can be easily understood. 1.4.8 Visual presentation (AAA) For text content presentation, the following should be true: Foreground and background colors should be user-selectable. Text blocks should be no wider than 80 characters (or glyphs), for maximum readability. Text should not be fully justified (e.g., text-align: justify;). Line height should be at least 1.5 times the text size within paragraphs (e.g., line-height: 1.5;), and at least 2.25 times the text size between paragraphs (e...
Understandable - Accessibility
s can be given to the user. Such suggestions should be displayed usefully in context, just like error messages (see 3.3.1). No tutorial suggestions yet. 3.3.4 Error Prevention (Legal, Financial, Data) (AA) In the case of forms involved with entry of sensitive data (such as legal agreements, e-commerce transactions, or personal data), at least one of the following should be true: Submissions are reversible. Data is checked for errors, and the user is given an opportunity to correct them. A mechanism is available for confirming and correcting information before final submission. Reversible -- for any view where data can be entered, provide an equivalent view that allows you to edit or even delete an entry, as appropriate. Checkin...
-moz-user-input - CSS: Cascading Style Sheets
the working group. Syntax Values none The element does not respond to user input, and it does not become :active. enabled The element accepts user input. For textboxes, this is the default behavior. Please note that this value is no longer supported in Firefox 60 onwards (bug 1405087). disabled The element does not accept user input. However, this is not the same as setting disabled to true, in that the element is drawn normally. Please note that this value is no longer supported in Firefox 60 onwards (bug 1405087). Formal definition Initial valueautoApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Formal syntax auto | none | enabled | disabled Examples Disabling user input for an element input.example { /* The user will be able to select ...
:-moz-focusring - CSS: Cascading Style Sheets
The :-moz-focusring CSS pseudo-class is a Mozilla extension that is similar to the :focus pseudo-class, but it only matches an element if it's currently focused and a focus ring or other indicator should be drawn around it. If :-moz-focusring matches, then :focus also matches, but the converse is not always true: it depends on whether the user agent has focus ring drawing enabled and how the element was focused. Whether the user agent has focus ring drawing enabled can depend on operating system settings and other factors, so the precise behavior of this pseudo-class will vary from platform to platform. This feature is not defined in any specification yet, though it was discussed in the working group and it was decided to add it to Selectors 4 or 5. Note: Developers tend to use ...
:-moz-window-inactive - CSS: Cascading Style Sheets
This attribute is no longer used. ...
::spelling-error - CSS: Cascading Style Sheets
Working Draft Initial definition. ...
font-style - CSS: Cascading Style Sheets
que <angle>{0,2} Examples Specifying an italic font style As an example, consider the garamond font family, in its normal form, we get the following result: @font-face { font-family: garamond; src: url('garamond.ttf'); } The italicized version of this text uses the same glyphs present in the unstyled version, but they are artificially sloped by a few degrees. On the other hand, if a true italicized version of the font family exists, we can include it in the src descriptor and specify the font style as italic, so that it is clear that the font is italicized. True italics use different glyphs and are a bit different from their upright counterparts, having some unique features and generally have a rounded and calligraphic quality. These fonts are specially created by font designers ...
font-variation-settings - CSS: Cascading Style Sheets
Syntax /* Use the default settings */ font-variation-settings: normal; /* Set values for OpenType axis names */ font-variation-settings: "xhgt" 0.7; Values normal Text is laid out using default settings. <string> <number> When rendering text, the list of OpenType axis names is passed to the text layout engine to enable or disable font features. Each setting is always a <string> of 4 ASCII characters, followed by a <number> indicating the axis value. ...
font-weight - CSS: Cascading Style Sheets
800 Extra Bold (Ultra Bold) 900 Black (Heavy) Variable fonts Most fonts have a particular weight which corresponds to one of the numbers in Common weight name mapping. However some fonts, called variable fonts, can support a range of weights with more or less fine granularity, and this can give the designer a much closer degree of control over the chosen weight. For TrueType or OpenType variable fonts, the "wght" variation is used to implement varying weights. Accessibility concerns People experiencing low vision conditions may have difficulty reading text set with a font-weight value of 100 (Thin/Hairline) or 200 (Extra Light), especially if the font has a low contrast color ratio. MDN Understanding WCAG, Guideline 1.4 explanations Understanding Success Cr...
-webkit-transition - CSS: Cascading Style Sheets
It was never supported in browsers not based on WebKit or Blink. Apple has a description in Safari CSS Reference; this is now called simply transition there. Note: You should not use this media feature; it was never specified, has never been widely implemented, and has been removed from all browsers. Use an @supports feature query instead. Syntax @media (-webkit-transition) { /* CSS to use if transitions are supported */ } Examples Use @supports instead Do not use the -webkit-transition media feature. ...
prefers-color-scheme - CSS: Cascading Style Sheets
Alternately, users can create the numeric preference ui.systemUsesDarkTheme to override the default behavior and return light (value: 0), dark (value: 1), or no-preference (value: 2). (Any other value causes Firefox to return light.) The prefers-color-scheme CSS media feature is used to detect if the user has requested the system use a light or dark color theme. Syntax light Indicates that user has notified the system that they prefer an interface that has a light theme, or has not expressed an active preference. ...
At-rules - CSS: Cascading Style Sheets
Web › CSS › At-rule
erties, each at-rule has a different syntax. Nevertheless, several of them can be grouped into a special category named conditional group rules. These statements share a common syntax and each of them can include nested statements--either rulesets or nested at-rules. Furthermore, they all convey a common semantic meaning--they all link some type of condition, which at any time evaluates to either true or false. If the condition evaluates to true, then all of the statements within the group will be applied. Conditional group rules are defined in CSS Conditionals Level 3 and are: @media, @supports, @document. (deferred to Level 4 of CSS Spec) Since each conditional group may also contain nested statements, there may be an unspecified amount of nesting. Specifications Specific...
CSS Box Alignment - CSS: Cascading Style Sheets
aph elements, are laid out and it runs across the Inline axis. When aligning items on the inline axis you will use the properties which begin with justify-: justify-items justify-self justify-content When aligning items on the block axis you will use the properties that begin align-: align-items align-self align-content Flexbox adds an additional complication in that the above is true when flex-direction is set to row. The properties are swapped when flexbox is set to column. Therefore, when working with flexbox it is easier to think about the main and cross axis rather than inline and block. The justify- properties are always used to align on the main axis, the align- properties on the cross axis. The alignment subject The alignment subject is the thing that is being aligne...
Using feature queries - CSS: Cascading Style Sheets
one property in your feature query. To do so, you can include a list of features to test for, separated by and keywords: @supports (property1: value) and (property2: value) { CSS rules to apply } For example, if the CSS you want to run requires that the browser supports CSS Shapes and CSS Grid, you could create a rule which checks for both of these things. The following rule will only return true if both shape-outside: circle() and display: grid are supported by the browser. You can also use or, if one property out of a selection could match to enable the CSS you want to use: @supports (property1: value) or (property2: value) { CSS rules to apply } This can be particularly useful if a feature is vendor prefixed, as you can test for the standard property plus any vendor prefixes. ...
CSS Containment - CSS: Cascading Style Sheets
e across a layout containment boundary The layout container will be a containing block for absolute/fixed position descendants. The containing box creates a stacking context, therefore z-index can be used. Paint containment article { contain: paint; } Paint containment essentially clips the box to the padding edge of the principal box. There can be no visible overflow. The same things are true for paint containment as layout containment (see above). Another advantage is that if the containing box is offscreen, the browser does not need to paint its contained elements -- these must also be offscreen as they are contained completely by that box. Size containment article { contain: size; } Size containment does not offer much in the way of performance optimizations when used on its ...
Variable fonts guide - CSS: Cascading Style Sheets
ers from accidentally applying the variation axis and a synthesized italic. This can be used to prevent faux-bolding as well. font-style: italic; font-variation-settings: 'ital' 1; font-synthesis: none; The following live example's CSS can be edited to allow you to play with font italics. Slant Slant (represented by the slnt tag), or as it's often referred to, 'oblique' -- is different to true italics in that it changes the angle of the letterforms but doesn't perform any kind of character substitution. It is also variable, in that it is expressed as a numeric range. This allows the font to be varied anywhere along that axis. The allowed range is generally 0 (upright) to 20 degrees -- any number value along that range can be supplied, so the font can be slanted just a tiny bit. However...
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
uts could be implemented for IE10, through to Edge 15, using the -ms properties. As these properties are vendor prefixed, they will not effect any browser supporting the up to date and unprefixed specification. Autoprefixer grid layout support The popular tool Autoprefixer has been updated to support the -ms- grid version. By default, grid prefixes are disabled, but you can enable it with grid: true option. autoprefixer({ grid: 'autoplace' }) Grid prefixes are disabled by default because some properties can't be prefixed. Is it safe to use CSS grids for my layout? As with any front-end technology choice, the decision to use CSS Grid Layout will come down to the browsers your site visitors are typically using. If they tend to use up-to-date versions of Firefox, Chrome, Opera, and Safari, ...
Layout and the containing block - CSS: Cascading Style Sheets
we examine the factors that determine an element's containing block. When a user agent (such as your browser) lays out a document, it generates a box for every element. Each box is divided into four areas: Content area Padding area Border area Margin area Many developers believe that the containing block of an element is always the content area of its parent, but that isn't necessarily true. Let's investigate the factors that determine what an element's containing block is. Effects of the containing block Before learning what determines the containing block of an element, it's useful to know why it matters in the first place. The size and position of an element are often impacted by its containing block. Percentage values that are applied to the width, height, padding, margin, an...
Testing media queries programmatically - CSS: Cascading Style Sheets
e landscape */ } Receiving query notifications If you need to be aware of changes to the evaluated result of the query on an ongoing basis, it's more efficient to register a listener than to poll the query's result. 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. const mediaQueryList = window.matchMedia("(orientation: portrait)"); // Define a callback function for the event listener. function handleOrientationChange(mql) { // ... } // Run the orientation change handler once. handleOrientationChange(mediaQueryList); // Add the callback function as a listener to the query list. mediaQueryList.addListener(handleOrie...
Cubic Bezier Generator - CSS: Cascading Style Sheets
<html> <canvas id="bezier" width="336" height="336"> </canvas> <form> <label for="x1">x1 = </label><input onchange="updateCanvas();" type="text" maxlength=6 id="x1" value="0.79" class='field'> <label for="y1">y1 = </label><input onchange="updateCanvas();return true;" type="text" maxlength=6 id="y1" value="0.33" class='field'> <label for="x2">x2 = </label><input onchange="updateCanvas();return true;" type="text" maxlength=6 id="x2" value="0.14" class='field'> <label for="y2">y2 = </label><input onchange="updateCanvas();return true;" type="text" maxlength=6 id="y2" value="0.53" class='field'> <br> <output id="output">Log</output> </form> </html> .field { width: 40px; } function updateCanvas() { var x1 =...
background-color - CSS: Cascading Style Sheets
CSS Level 1The definition of 'background-color' in that specification. Initial definition ...
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
en behave in the same way as the flex children of a block-level container. The only thing that has changed is that the parent is now an inline-level box. It therefore behaves like other inline-level things, and doesn't take up the full width (or size in the inline dimension) that a block-level box does. This means that some following text could come up alongside the flex container. The same is true when working with grid layout. Using display: grid will give you a block-level box, which creates a grid formatting context for the direct children. Using display: inline-grid will create an inline-level box, which creates a grid formatting context for the children. The two-value syntax As you can see from the above explanation, the display property has gained considerable new powers. In additi...
font-stretch - CSS: Cascading Style Sheets
<percentage> A <percentage> value between 50% and 200% (inclusive). Negative values are not allowed for this property. In earlier versions of the font-stretch specification, the property accepts only the nine keyword values. CSS Fonts Level 4 extends the syntax to accept a <percentage> value as well. This enables variable fonts to offer something more like a continuum of character widths. For TrueType or OpenType variable fonts, the "wdth" variation is used to implement varying widths. However, note that the <percentage> syntax is not yet supported by all browsers: check the Browser compatibility table for details. Keyword to numeric mapping The table below shows the mapping between keyword values and numeric percentages: Keyword Percentage ultra-condensed 5...
font-style - CSS: Cascading Style Sheets
the beginning. In general, for a requested angle of 14 degrees or greater, larger angles are prefered; otherwise, smaller angles are preferred (see the spec's font matching section for the precise algorithm). Variable fonts Variable fonts can offer a fine control over the degree to which an oblique face is slanted. You can select this using the <angle> modifier for the oblique keyword. For TrueType or OpenType variable fonts, the "slnt" variation is used to implement varying slant angles for oblique, and the "ital" variation with a value of 1 is used to implement italic values. See font-variation-settings. For the example below to work, you'll need a browser that supports the CSS Fonts Level 4 syntax in which font-style: oblique can accept an <angle>. HTML <header> <input type...
font-variation-settings - CSS: Cascading Style Sheets
no other way to enable or access those features exist. You should only use it when no basic properties exist to set those features (e.g. font-weight, font-style). Font characteristics set using font-variation-settings will always override those set using the corresponding basic font properties, e.g. font-weight, no matter where they appear in the cascade. In some browsers, this is currently only true when the @font-face declaration includes a font-weight range. Registered and custom axes Variable font axes come in two types: registered and custom. Registered axes are the most commonly encountered -- common enough that the authors of the specification felt they were worth standardizing. Note that this doesn't mean that the author has to include all of these in their font. Here are the regi...
font-weight - CSS: Cascading Style Sheets
900 Black (Heavy) 950 Extra Black (Ultra Black) Variable fonts Most fonts have a particular weight which corresponds to one of the numbers in Common weight name mapping. However some fonts, called variable fonts, can support a range of weights with a more or less fine granularity, and this can give the designer a much closer degree of control over the chosen weight. For TrueType or OpenType variable fonts, the "wght" variation is used to implement varying widths. For the example below to work, you'll need a browser that supports the CSS Fonts Level 4 syntax in which font-weight can be any number between 1 and 1000. HTML <header> <input type="range" id="weight" name="weight" min="1" max="1000" /> <label for="weight">Weight</label> </header> <div class="c...
overflow - CSS: Cascading Style Sheets
Web › CSS › overflow
idden and overflow-y: scroll, or overflow: scroll hidden instead. -moz-hidden-unscrollable Intended mainly for internal use and by themes. Disables scrolling of XML root elements, <html>, and <body> with the keyboard's arrow keys and the mouse wheel. [1] As of Firefox 63, this feature is behind a feature preference setting. In about:config, set layout.css.overflow.moz-scrollbars.enabled to true Description Overflow options include clipping, showing scrollbars, or displaying the content flowing out of its container into the surrounding area. Specifying a value other than visible (the default) creates a new block formatting context. This is necessary for technical reasons -- if a float intersected with the scrolling element it would forcibly rewrap the content after each scroll step, l...
url() - CSS: Cascading Style Sheets
Web › CSS › url()
s, if used, are relative to the URL of the stylesheet (not to the URL of the web page). The url() function can be included as a value for background, background-image, list-style, list-style-image, content, cursor, border, border-image, border-image-source, mask, mask-image, src as part of a @font-face block, and @counter-style/symbol In CSS Level 1, the url() functional notation described only true URLs. In CSS Level 2, the definition of url() was extended to describe any URI, including URNs. CSS Values and Units Level 3 returned to the narrower, initial definition. Now, url() denotes only true <url>s. Syntax Values <string> <url> A url, which is a relative or absolute address, or pointer, to the web resource to be included, or a data uri, optionally in single or double quotes.
regexp:test() - EXSLT
Web › EXSLT › regexp › test
st.. regExpString The JavaScript style regular expression to evaluate. flagsStringOptional An optional string containing character flags. The character flags are: g Global match Has no effect for this function; it's allowed for consistency with other regexp functions. i Case insensitive match If this flag is specified, the match is performed in a case insensitive fashion. Returns true if the specified regexp matches the test string. Specifications EXSLT - REGEXP:TEST ...
set:has-same-node() - EXSLT
Specifications EXSLT - SET:HAS-SAME-NODE ...
Video player styling basics - Developer guides
checkVolume() is also called when the volumechange event is raised: video.addEventListener('volumechan...
Challenge solutions - Developer guides
jumps back afterwards. Solution Add lines to modify the margin-left property. Be sure to specify it as marginLeft in JavaScript. ...
Orientation and motion data explained - Developer guides
xes are aligned based on the pull of gravity and the standard magnetic north orientation. We use upper-case letters ("X", "Y", and "Z") to describe the axes of the Earth coordinate frame. The X axis follows along the ground plane, perpendicular to the Y axis and positive toward the east (and therefore negative toward the west). The Y axis follows along the ground plane, and is positive toward true north (that is, the North Pole, not magnetic north) and negative toward true south. The Z axis is perpendicular to the ground plane; think of it as a line drawn between the device and the center of the Earth. The value of the Z coordinate is positive upward (away from the center of the Earth) and negative downward (toward the center of the Earth). Device coordinate frame The device coordinate...
Constraint validation - Developer guides
valueMissing constraint violation step date An integer number of days Unless the step is set to the any literal, the value must be min + an integral multiple of the step. stepMismatch constraint violation month An integer number of months week An integer number of weeks datetime, d...
Introduction to HTML5 - Developer guides
ark-up was defined, meaning that as soon as one small error was made in the mark-up (most websites have at least one), the behavior was undefined. Essentially, it meant that all browsers behaved differently, which is no longer the case. Now, faced with errors in the mark-up, all compliant browsers must behave exactly in the same way. This requirement helps web developers quite a bit. While it is true that all modern browsers now use these HTML5 parsing rules, non-HTML5-compliant browsers are still used by some. Keep in mind that it's still highly recommended that one writes valid mark-up, as such code is easier to read and maintain, and it greatly decreases the prominence of incompatibilities that exists in various older browsers. Don't worry -- you don't have to change anything on your webs...
Writing forward-compatible websites - Developer guides
ow these guidelines too. If they don't, you can't rely on that library not breaking in the future. Unfortunately, libraries are common transgressors of these guidelines. Sniffing Sniff for specific features If you plan to use some feature, use object-detection to sniff for that exact feature, if possible. As a simple example, don't assume that any browser in which "filter" in body.style tests true must be Microsoft Internet Explorer and therefore e.g. will have a window.event object available in event handlers. Don't assume that browsers with support for a given DOM feature must also have some other, especially nonstandard, DOM feature. Or, conversely, that they don't have support for some other feature (e.g., don't assume that a browser that supports onload on script elements will never s...
HTML attribute: max - HTML: Hypertext Markup Language
Web › HTML › Attributes › max
aint validation will prevent form submission. Valid for the numeric input types, including the date, month, week, time, datetime-local, number and range types, and both the <progress> and <meter> elements, the max attribute is a number that specifies the most positive value a form control to be considered valid. If the value exceeds the max value allowed, the validityState.rangeOverflow will be true, and the the control will be matched by the :out-of-range and :invalid pseudo-classes. Syntax Syntax for max values by input type Input type Syntax Example date yyyy-mm-dd <input type="date" max="2019-12-25" step="1"> month yyyy-mm <input type="month" max="2019-12" step="12"> week yyyy-W## <input type="week" max="2019-W23" step=""...
HTML attribute: maxlength - HTML: Hypertext Markup Language
t value of the field is greater than maxlength UTF-16 code units long. Constraint validation is only applied when the value is changed by the user. Constraint validation While the browser will generally prevent user from entering more text than the maxlength attribute allows, should the length be longer than the maxlength allows, the read-only tooLong property of a ValidityState object will be true. Examples <input type="password" maxlength="4"/> Specifications Specification Status HTML Living StandardThe definition of 'maxlength attribute' in that specification. Living Standard HTML 5.1The definition of 'maxlength attribute' in that specification. Recommendation ...
HTML attribute: minlength - HTML: Hypertext Markup Language
specified, or an invalid value is specified, the input has no minimum length. This value must be less than or equal to the value of maxlength, otherwise the value will never be valid, as it is impossible to meet both criteria. The input will fail constraint validation if the length of the text value of the field is less than minlength UTF-16 code units long, with validityState.tooShort returning true. Constraint validation is only applied when the value is changed by the user. Once submission fails, some browsers will display an error message indicating the minimum length required and the current length. Examples By adding minlength="5", the value must either be empty or five characters or longer to be valid. <label for="fruit">Enter a fruit name that is at least 5 letters long</label> <in...
<a>: The Anchor element - HTML: Hypertext Markup Language
Web › HTML › Element › a
See Referer header: privacy and security concerns for information. Using target="_blank" without rel="noreferrer" and rel="no...
<button>: The Button element - HTML: Hypertext Markup Language
Web › HTML › Element › button
ssistive technology, such as screen readers, to access when they parse the document and generate an accessibility tree. Assistive technology then uses the accessibility tree to navigate and manipulate page content. To give an icon button an accessible name, put text in the <button> element that concisely describes the button's functionality. Example <button name="favorite"> <svg aria-hidden="true" viewBox="0 0 10 10"><path d="M7 9L5 8 3 9V6L1 4h3l1-3 1 3h3L7 6z"/></svg> Add to favorites </button> If you want to visually hide the button's text, an accessible way to do so is to use a combination of CSS properties to remove it visually from the screen, but keep it parseable by assistive technology. However, it is worth noting that leaving the button text visually apparent can aid people...
<i>: The Idiomatic Text element - HTML: Hypertext Markup Language
Web › HTML › Element › i
ng about, anyway?") Ship or vessel names in Western writing systems (such as "They searched the docks for the Empress of the Galaxy, the ship to which they were assigned.") In earlier versions of the HTML specification, the <i> element was merely a presentational element used to display text in italics, much like the <b> element was used to display text in bold letters. This is no longer true, as these tags now define semantics rather than typographic appearance. A browser will typically still display the contents of the <i> element in italic type, but is, by definition, no longer required to do so. To display text in italic type, authors should use the CSS font-style property. Be sure the text in question is not actually more appropriately marked up with another element. Use <...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
Web › HTML › Element › iframe
es application, document, img, none, presentation DOM interface HTMLIFrameElement Attributes This element includes the global attributes. allow Specifies a feature policy for the <iframe>. See the article Privacy, permissions, and information security for details on security issues and how <iframe> works with Feature Policy to keep systems safe. allowfullscreen Set to true if the <iframe> can activate fullscreen mode by calling the requestFullscreen() method. This attribute is considered a legacy attribute and redefined as allow="fullscreen". allowpaymentrequest Set to true if a cross-origin <iframe> should be allowed to invoke the Payment Request API. This attribute is considered a legacy attribute and redefined as allow="payment". csp A Content Se...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
S request is sent with credentials omitted (that is, no cookies, X.509 certificates, or Authorization request header). use-credentials The CORS request is sent with any credentials included (that is, cookies, X.509 certificates, and the Authorization request header). If the server does not opt into sharing credentials with the origin site (by sending back the Access-Control-Allow-Credentials: true response header), then the browser marks the image as tainted and restricts access to its image data. If the attribute has an invalid value, browsers handle it as if the anonymous value was used. See CORS settings attributes for additional information. decoding Provides an image decoding hint to the browser. Allowed values: sync Decode the image synchronously, for atomic prese...
<input type="file"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › file
tContent = `File name ${file.name}: Not a valid file type. Update your selection.`; listItem.appendChild(para); } list.appendChild(listItem); } } } The custom validFileType() function takes a File object as a parameter, then uses Array.prototype.includes() to check if any value in the fileTypes matches the file's type property. If a match is found, the function returns true. If no match is found, it returns false. // https://developer.mozilla.org/docs/Web/Media/Formats/Image_types const fileTypes = [ "image/apng", "image/bmp", "image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/svg+xml", "image/tiff", "image/webp", "image/x-icon" ]; function validFileType(file) { return fileTypes.includes(file.type); } The returnFileSize() function...
<input type="text"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › text
ength of the input data, use the maxlength attribute. spellcheck spellcheck is a global attribute which is used to indicate whether or not to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of spellcheck on <input> elements. The permitted values for spellcheck are: false Disable spell checking for this element. true Enable spell checking for this element. "" (empty string) or no value Follow the element's default behavior for spell checking. This may be based upon a parent's spellcheck setting or other factors. An input field can have spell checking enabled if it doesn't have the readonly attribute set and is not disabled. The value returned by reading spellcheck may not reflect the actual state of spe...
<input type="url"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › url
ength of the input data, use the maxlength attribute. spellcheck spellcheck is a global attribute which is used to indicate whether or not to enable spell checking for an element. It can be used on any editable content, but here we consider specifics related to the use of spellcheck on <input> elements. The permitted values for spellcheck are: false Disable spell checking for this element. true Enable spell checking for this element. "" (empty string) or no value Follow the element's default behavior for spell checking. This may be based upon a parent's spellcheck setting or other factors. An input field can have spell checking enabled if it doesn't have the readonly attribute set and is not disabled. The value returned by reading spellcheck may not reflect the actual state of spe...
<marquee>: The Marquee element (Obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › marquee
ill scroll. If no value is specified, the default value is -1, which means the marquee will scroll continuously. scrollamount Sets the amount of scrolling at each interval in pixels. The default value is 6. scrolldelay Sets the interval between each scroll movement in milliseconds. The default value is 85. Note that any value smaller than 60 is ignored and the value 60 is used instead, unless truespeed is specified. truespeed By default, scrolldelay values lower than 60 are ignored. If truespeed is present, those values are not ignored. vspace Sets the vertical margin in pixels or percentage value. width Sets the width in pixels or percentage value. Event handlers onbounce Fires when the marquee has reached the end of its scroll position. It can only fire when the behavior attr...
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available. This attribute allows the elimination of parser-blocking JavaScript where the browser would have to load and evaluate scripts before continuing to parse. defer has a similar effect in this case. 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. See Browser compatibility for notes on browser support. See also Async scripts for asm.js. crossorigin Normal script elements pass minimal information to the window.onerror for scripts which do not pass the standard CORS checks. To allow error logging for sites which use a separate domain for static media, use this attribut...
<table>: The Table element - HTML: Hypertext Markup Language
Web › HTML › Element › table
ng This attribute defines the space between the content of a cell and its border, displayed or not. If the cellpadding's length is defined in pixels, this pixel-sized space will be applied to all four sides of the cell's content. If the length is defined using a percentage value, the content will be centered and the total vertical space (top and bottom) will represent this value. The same is true for the total horizontal space (left and right). To achieve a similar effect, apply the border-collapse property to the <table> element, with its value set to collapse, and the padding property to the <td> elements. cellspacing This attribute defines the size of the space between two cells in a percentage value or pixels. The attribute is applied both horizontally and vertically, to the...
<textarea> - HTML: Hypertext Markup Language
Web › HTML › Element › textarea
the user from clicking or selecting in the control. The value of a read-only control is still submitted with the form. required This attribute specifies that the user must fill in a value before submitting a form. rows The number of visible text lines for the control. spellcheck Specifies whether the <textarea> is subject to spell checking by the underlying browser/OS. the value can be: true: Indicates that the element needs to have its spelling and grammar checked. default : Indicates that the element is to act according to a default behavior, possibly based on the parent element's own spellcheck value. false : Indicates that the element should not be spell checked. wrap Indicates how the control wraps text. Possible values are: hard: The browser automatically inserts ...
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
formation about how to properly use autoplay. To disable video autoplay, autoplay="false" will not work; the video will autoplay if the attribute is there in the <video> tag at all. To remove autoplay, the attribute needs to be removed altogether. In some browsers (e.g. Chrome 70.0) autoplay doesn't work if no muted attribute is present. autoPictureInPicture A Boolean attribute which if true indicates that the element should automatically toggle picture-in-picture mode when the user switches back and forth between this document and another document or application. buffered An attribute you can read to determine the time ranges of the buffered media. This attribute contains a TimeRanges object. controls If this attribute is present, the browser will offer controls to allow the use...
class - HTML: Hypertext Markup Language
'class' in that specification. Living Standard No change from latest snapshot, HTML 5.1 HTML 5.1The definition of 'class' in that specification. Recommendation Snapshot of HTML Living Standard, no change from HTML5 HTML5The definition of 'class' in that specification. Recommendation Snapshot of HTML Living Standard. From HTML 4.01 Specification, class is now a true global attribute. HTML 4.01 SpecificationThe definition of 'class' in that specification. Recommendation Supported on all elements but <base>, <basefont>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>. ...
dir - HTML: Hypertext Markup Language
pecification. Living Standard No change from latest snapshot, HTML 5.1 HTML 5.1The definition of 'dir' in that specification. Recommendation Snapshot of HTML Living Standard, no change from HTML5 HTML5The definition of 'dir' in that specification. Recommendation Snapshot of HTML Living Standard, from HTML 4.01 Specification it added the auto value, and is now a true global attribute. HTML 4.01 SpecificationThe definition of 'dir' in that specification. Recommendation Supported on all elements but <applet>, <base>, <basefont>, <bdo>, <br>, <frame>, <frameset>, <iframe>, <param>, and <script>. ...
id - HTML: Hypertext Markup Language
ation. Living Standard No change from latest snapshot, HTML 5.1 HTML 5.1The definition of 'id' in that specification. Recommendation Snapshot of HTML Living Standard, no change from HTML5 HTML5The definition of 'id' in that specification. Recommendation Snapshot of HTML Living Standard, now accept '_', '-' and '.' if not at the beginning of the id. It is also a true global attribute. HTML 4.01 SpecificationThe definition of 'id' in that specification. Recommendation Supported on all elements but <base>, <head>, <html>, <meta>, <script>, <style>, and <title>. ...
lang - HTML: Hypertext Markup Language
Living Standard No change from latest snapshot, HTML 5.1 HTML 5.1The definition of 'lang' in that specification. Recommendation Snapshot of HTML Living Standard, no change from HTML5 HTML5The definition of 'lang' in that specification. Recommendation Snapshot of HTML Living Standard, behavior with xml:lang and language determination algorithm defined. It also is a true global attribute. HTML 4.01 SpecificationThe definition of 'lang' in that specification. Recommendation Supported on all elements but <applet>, <base>, <basefont>, <br>, <frame>, <frameset>, <iframe>, <param>, and <script>. ...
style - HTML: Hypertext Markup Language
of 'style' in that specification. Living Standard No change from latest snapshot, HTML 5.1 HTML 5.1The definition of 'style' in that specification. Recommendation Snapshot of HTML Living Standard, no change from HTML5 HTML5The definition of 'style' in that specification. Recommendation Snapshot of HTML Living Standard. From HTML 4.01 Specification, it is now a true global attribute. HTML 4.01 SpecificationThe definition of 'style' in that specification. Recommendation Supported on all elements but <base>, <basefont>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title>. CSS Style Attributes Recommendation Defines the content of the style attribute. ...
title - HTML: Hypertext Markup Language
of 'title' in that specification. Living Standard No change from latest snapshot, HTML 5.1 HTML 5.1The definition of 'title' in that specification. Recommendation Snapshot of HTML Living Standard, no change from HTML5 HTML5The definition of 'title' in that specification. Recommendation Snapshot of HTML Living Standard. From HTML 4.01 Specification, it is now a true global attribute. HTML 4.01 SpecificationThe definition of 'title' in that specification. Recommendation Supported on all elements but <base>, <basefont>, <head>, <html>, <meta>, <param>, <script>, and <title>. ...
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
or multiple values depends on the form control. 45 HTML attribute: pattern Attribute, Attributes, Constraint Validation API, Reference The pattern attribute specifies a regular expression the form control's value should match. If a non-null value doesn't conform to the constraints set by the pattern value, the ValidityState object's read-only patternMismatch property will be true. 46 HTML attribute: readonly Attribute, Attributes, Constraint validation, Forms, required The Boolean readonly attribute, when present, makes the element not mutable, meaning the user can not edit the control. 47 HTML attribute: rel Attribute, Attributes, Constraint validation, Link, form, rel The rel attribute defines the relationship between a linked r...
Common MIME types - HTTP
ourne shell script application/x-sh .svg Scalable Vector Graphics (SVG) image/svg+xml .swf Small web format (SWF) or Adobe Flash document application/x-shockwave-flash .tar Tape Archive (TAR) application/x-tar .tif .tiff Tagged Image File Format (TIFF) image/tiff .ts MPEG transport stream video/mp2t .ttf TrueType Font font/ttf .txt Text, (generally ASCII or ISO 8859-n) text/plain .vsd Microsoft Visio application/vnd.visio .wav Waveform Audio Format audio/wav .weba WEBM audio audio/webm .webm WEBM video video/webm .webp WEBP image image/webp .woff Web Open Font Format (WOFF) font/woff .w...
Reason: CORS disabled - HTTP
Web › HTTP › CORS › Errors › CORSDisabled
...
Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’ - HTTP
dentials flag set, but the server is configured using the wildcard ("*") as the value of Access-Control-Allow-Origin, which doesn't allow the use of credentials. To correct this problem on the client side, simply ensure that the credentials flag's value is false when issuing your CORS request. If the request is being issued using XMLHttpRequest, make sure you're not setting withCredentials to true. If using Server-sent events, make sure EventSource.withCredentials is false (it's the default value). If using the Fetch API, make sure Request.credentials is "omit". If, instead, you need to adjust the server's behavior, you'll need to change the value of Access-Control-Allow-Origin to grant access to the origin from which the client is loaded. ...
CORS errors - HTTP
Web › HTTP › CORS › Errors
Reason: CORS request external redirect not allowed Reason: CORS request not http Reason: CORS header 'Access-Control-Allow-Origin' missing Reason: CORS header 'Access-Control-Allow-Origin' does not match 'xyz' Reason: Credential is not supported if the CORS header 'Access-Control-Allow-Origin' is '*' Reason: Did not find method in CORS header 'Access-Control-Allow-Methods' Reason: expected 'true' in CORS header 'Access-Control-Allow-Credentials' Reason: CORS preflight channel did not succeed Reason: invalid token 'xyz' in CORS header 'Access-Control-Allow-Methods' Reason: invalid token 'xyz' in CORS header 'Access-Control-Allow-Headers' Reason: missing token 'xyz' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel Reason: Multiple CORS header 'Access-Control-A...
X-DNS-Prefetch-Control - HTTP
es can be resolved in advance of the images being requested, pages that load many images can see an improvement of 5% or more in the time of loading images. Configuring prefetching in the browser In general, you don't need to do anything to manage prefetching. However, the user may wish to disable prefetching. On Firefox, this can be done by setting the network.dns.disablePrefetch preference to true. Also, by default, prefetching of embedded link hostnames is not performed on documents loaded over HTTPS. On Firefox, this can be changed by setting the network.dns.disablePrefetchFromHTTPS preference to false. Examples Turning on and off prefetching You can either send the X-DNS-Prefetch-Control header server-side, or from individual documents, using the http-equiv attribute on the <meta> e...
HTTP Index - HTTP
Web › HTTP › Index
uest is using any other method, this error occurs. 32 Reason: Multiple CORS header 'Access-Control-Allow-Origin' not allowed CORS, CORSMultipleAllowOriginNotAllowed, Cross-Origin, Error, HTTP, HTTPS, Messages, Reasons, Security, console, troubleshooting More than one Access-Control-Allow-Origin header was sent by the server. This isn't allowed. 33 Reason: expected 'true' in CORS header 'Access-Control-Allow-Credentials' CORS, CORSMissingAllowCredentials, Cross-Origin, Error, HTTP, HTTPS, Messages, Reasons, Security, console, troubleshooting The CORS request requires that the server permit the use of credentials, but the server's Access-Control-Allow-Credentials header's value isn't set to true to enable their use. 34 Reason: invalid token 'x...
Network Error Logging - HTTP
is required. The following object keys can be specified in the NEL header: report_to The reporting API group to send network error reports to (see below). max_age Specifies the lifetime of the policy, in seconds (in a similar way to e.g. HSTS policies are time-restricted). The referenced reporting group should have a lifetime at least as long as the NEL policy. include_subdomains If true, the policy applies to all subdomains under the origin that the policy header is set. The reporting group should also be set to include subdomains, if this option is to be enabled. success_fraction Floating point value between 0 and 1 which specifies the proportion of successful network requests to report. Defaults to 0, so that no successful network requests will be reported if the key is not ...
An overview of HTTP - HTTP
Web › HTTP › Overview
nt domains; there could even be security-related reasons to do so. Authentication Some pages may be protected so that only specific users can access them. Basic authentication may be provided by HTTP, either using the WWW-Authenticate and similar headers, or by setting a specific session using HTTP cookies. Proxy and tunneling Servers or clients are often located on intranets and hide their true IP address from other computers. HTTP requests then go through proxies to cross this network barrier. Not all proxies are HTTP proxies. The SOCKS protocol, for example, operates at a lower level. Other protocols, like ftp, can be handled by these proxies. Sessions Using HTTP cookies allows you to link requests with the state of the server. This creates sessions, despite basic HTTP being a stat...
Concurrency model and the event loop - JavaScript
inimum time--not a guaranteed time. Here is an example that demonstrates this concept (setTimeout does not run immediately after its timer expires): const s = new Date().getSeconds(); setTimeout(function() { // prints out "2", meaning that the callback is not called immediately after 500 milliseconds. console.log("Ran after " + (new Date().getSeconds() - s) + " seconds"); }, 500) while (true) { if (new Date().getSeconds() - s >= 2) { console.log("Good, looped for 2 seconds") break; } } Zero delays Zero delay doesn't actually mean the call back will fire-off after zero milliseconds. Calling setTimeout with a delay of 0 (zero) milliseconds doesn't execute the callback function after the given interval. The execution depends on the number of waiting tasks in the queue. I...
Functions - JavaScript
2 + 3) In this example, C accesses B's y and A's x. This can be done because: B forms a closure including A (i.e. B can access A's arguments and variables). C forms a closure including B. Because B's closure includes A, C's closure includes A, C can access both B and A's arguments and variables. In other words, C chains the scopes of B and A, in that order. The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B. Name conflicts When two arguments or variables in the scopes of a closure have the same name, there is a name conflict. More nested scopes take precedence. So, the inner-most scope takes the highest precedence, while the outer-most scope takes the lowest. This ...
Keyed collections - JavaScript
ject Set objects are collections of values. You can iterate its elements in insertion order. A value in a Set may only occur once; it is unique in the Set's collection. The following code shows some basic operations with a Set. See also the Set reference page for more examples and the complete API. let mySet = new Set(); mySet.add(1); mySet.add('some text'); mySet.add('foo'); mySet.has(1); // true mySet.delete('foo'); mySet.size; // 2 for (let item of mySet) console.log(item); // 1 // "some text" Converting between Array and Set You can create an Array from a Set using Array.from or the spread operator. Also, the Set constructor accepts an Array to convert in the other direction. Note: Remember that Set objects store unique values--so any duplicate elements from an Array are deleted ...
Assertions - JavaScript
d words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions). Types The following section is also duplicated on this cheatsheet. Do not forget to edit it as well, thanks! Boundary-type assertions Characters Meaning ^ Matches the beginning of input. If the multiline flag is set to true, also matches immediately after a line break character. For example, /^A/ does not match the "A" in "an A", but does match the first "A" in "An A". This character has a different meaning when it appears at the start of a group. $ Matches the end of input. If the multiline flag is set to true, also matches immediately before a line break character. For example, ...
Regular expression syntax cheatsheet - JavaScript
ape sequences like \p or \k. To match this character literally, escape it with itself. In other words to search for \ use /\\/. Assertions If you are looking to contribute to this document, please also edit the original article Boundary-type assertions Characters Meaning ^ Matches the beginning of input. If the multiline flag is set to true, also matches immediately after a line break character. For example, /^A/ does not match the "A" in "an A", but does match the first "A" in "An A". This character has a different meaning when it appears at the start of a group. $ Matches the end of input. If the multiline flag is set to true, also matches immediately before a line break character. For example, ...
Regular expressions - JavaScript
exec() and with the String methods match(), replace(), search(), and split(). These methods are explained in detail in the JavaScript reference. Methods that use regular expressions Method Description exec() Executes a search for a match in a string. It returns an array of information or null on a mismatch. test() Tests for a match in a string. It returns true or false. match() Returns an array containing all of the matches, including capturing groups, or null if no match is found. matchAll() Returns an iterator containing all of the matches, including capturing groups. search() Tests for a match in a string. It returns the index of the match, or -1 if the search fails. replace() Executes a search for a m...
Inheritance and the prototype chain - JavaScript
le property that is on the prototype chain will be enumerated. To check whether an object has a property defined on itself and not somewhere on its prototype chain, it is necessary to use the hasOwnProperty method which all objects inherit from Object.prototype. 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. Note: It is not enough to check whether a property is undefined. The property might very well exist, but its val...
Memory Management - JavaScript
ll start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects. This algorithm is an improvement over the previous one since an object having zero references is effectively unreachable. The opposite does not hold true as we have seen with circular references. As of 2012, all modern browsers ship a mark-and-sweep garbage-collector. All improvements made in the field of JavaScript garbage collection (generational/incremental/concurrent/parallel garbage collection) over the last few years are implementation improvements of this algorithm, but not improvements over the garbage collection algorithm itself nor its ...
constructor - JavaScript
...
Classes - JavaScript
to return a parent Array object, instead of the MyArray object. 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. This is one advantage over prototype-based inheritance. class Cat { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); } } class Lion extends Cat { speak() { super.speak(); console.log(`${this.name} roars.`); } } let l =...
SyntaxError: test for equality (==) mistyped as assignment (=)? - JavaScript
The JavaScript warning "test for equality (==) mistyped as assignment (=)?" occurs when there was an assignment (=) when you would normally expect a test for equality (==). Message Warning: SyntaxError: test for equality (==) mistyped as assignment (=)? Error type (Firefox only) SyntaxError warning which is reported only if javascript.options.strict preference is set to true. What went wrong? There was an assignment (=) when you would normally expect a test for equality (==). To help debugging, JavaScript (with strict warnings enabled) warns about this pattern. Examples Assignment within conditional expressions It is advisable to not use simple assignments in a conditional expression (such as if...else), because the assignment can be confused with equality when glancing over the cod...
SyntaxError: missing } after function body - JavaScript
function code: var charge = function() { if (sunny) { useSolarCells(); } else { promptBikeRide(); }; Correct would be: var charge = function() { if (sunny) { useSolarCells(); } else { promptBikeRide(); } }; It can be more obscure when using IIFE, Closures, or other constructs that use a lot of different parenthesis and curly brackets, for example. (function() { if (true) { return false; } ); Oftentimes, indenting differently or double checking indentation helps to spot these errors. (function() { if (true) { return false; } }); ...
TypeError: can't delete non-configurable array element - JavaScript
ties by default if you haven't specified them as configurable. var arr = []; Object.defineProperty(arr, 0, {value: 0}); Object.defineProperty(arr, 1, {value: "1"}); arr.length = 1; // TypeError: can't delete non-configurable array element You will need to set the elements as configurable, if you intend to shorten the array. var arr = []; Object.defineProperty(arr, 0, {value: 0, configurable: true}); Object.defineProperty(arr, 1, {value: "1", configurable: true}); arr.length = 1; Seal-ed Arrays The Object.seal() function marks all existing elements as non-configurable. var arr = [1,2,3]; Object.seal(arr); arr.length = 1; // TypeError: can't delete non-configurable array element You either need to remove the Object.seal() call, or make a copy of it. In case of a copy, shortening the...
ReferenceError: reference to undefined property "x" - JavaScript
What went wrong? The script attempted to access an object property which doesn't exist. ...
TypeError: invalid 'instanceof' operand 'x' - JavaScript
oo() is called and returns undefined var x = new Foo(); x instanceof f; // TypeError: invalid 'instanceof' operand f x instanceof x; // TypeError: x is not a function To fix these errors, you will either need to replace the instanceof operator with the typeof operator, or to make sure you use the function name, instead of the result of its evaluation. typeof "test" == "string"; // true typeof 42 == "number" // true function Foo() {} var f = Foo; // Do not call Foo. var x = new Foo(); x instanceof f; // true x instanceof Foo; // true ...
Method definitions - JavaScript
before the generator property name. (That is, * g(){} will work, but g *(){} will not.) Non-generator method definitions cannot contain the yield keyword. This means that legacy generator functions won't work either, and will throw a SyntaxError. Always use yield in conjunction with the asterisk (*). // Using a named property const obj2 = { g: function* () { let index = 0 while (true) { yield index++ } } }; // The same object using shorthand syntax const obj2 = { * g() { let index = 0 while (true) { yield index++ } } }; const it = obj2.g() console.log(it.next().value) // 0 console.log(it.next().value) // 1 Async methods Async methods can also be defined using the shorthand syntax. // Using a named property const obj3 = { f: async fun...
arguments.callee - JavaScript
For example: [1, 2, 3, 4, 5].map(function factorial(n) { return !(n > 1) ? 1 : factorial(n - 1)*n; }); This has numerous benefits: the function can be called like any other...
getter - JavaScript
g Object.defineProperty() the property will be defined on the instance it is applied to. class Example { get hello() { return 'world'; } } const obj = new Example(); console.log(obj.hello); // "world" console.log(Object.getOwnPropertyDescriptor(obj, 'hello')); // undefined console.log( Object.getOwnPropertyDescriptor( Object.getPrototypeOf(obj), 'hello' ) ); // { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined } Specifications Specification ECMAScript (ECMA-262)The definition of 'Method definitions' in that specification. ...
AggregateError() constructor - JavaScript
e error. Syntax new AggregateError(errors[, message]) Parameters errors An iterable of errors, may not actually be Error instances. messageOptional An optional human-readable description of the aggregate error. Examples Creating an AggregateError try { throw new AggregateError([ new Error("some error"), ], 'Hello'); } catch (e) { console.log(e instanceof AggregateError); // true console.log(e.message); // "Hello" console.log(e.name); // "AggregateError" console.log(e.errors); // [ Error: "some error" ] } Specifications Specification Promise.anyThe definition of 'AggregateError()' in that specification. ...
Array.prototype.reduce() - JavaScript
s not present, // throw a TypeError exception. if (k >= len) { throw new TypeError( 'Reduce of empty array ' + 'with no initial value' ); } value = o[k++]; } // 8. Repeat, while k < len while (k < len) { // a. Let Pk be ! ToString(k). // b. Let kPresent be ? HasProperty(O, Pk). // c. If kPresent is true, then // i. Let kValue be ? Get(O, Pk). // ii. Let accumulator be ? Call( // callbackfn, undefined, // << accumulator, kValue, k, O >>). if (k in o) { value = callback(value, o[k], k, o); } // d. Increase k by 1. k++; } // 9. Return accumulator. return value; } }); } Cau...
Array.prototype.indexOf() - JavaScript
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len for (; k < len; k++) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of o with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of o with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in o && o[k] === searchElement) return k; ...
Array.prototype.length - JavaScript
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. Enumerable: If this attribute set to true, the property will be iterated over during for or for..in loops. Examples Iterating over an array In the following example, the array numbers is iterated through by looking at the length property. The value in each element is then doubled. var numbers = [1, 2, 3, 4, 5]; var length = numbers.length; for (var i = 0; i < length; i++) { numbers[i] *= 2; } // numbers is now [2, 4, 6, 8, 10] ...
ArrayBuffer - JavaScript
r creates a new ArrayBuffer of the given length in bytes. You can also get an array buffer from existing data, for example from a Base64 string or from a local file. Constructor ArrayBuffer() Creates a new ArrayBuffer object. Static properties get ArrayBuffer[@@species] The constructor function that is used to create derived objects. Static methods ArrayBuffer.isView(arg) Returns true if arg is one of the ArrayBuffer views, such as typed array objects or a DataView. Returns false otherwise. Instance properties ArrayBuffer.prototype.byteLength The read-only size, in bytes, of the ArrayBuffer. This is established when the array is constructed and cannot be changed. Instance methods ArrayBuffer.prototype.slice() Returns a new ArrayBuffer whose contents are a copy of t...
Atomics.notify() - JavaScript
ArrayBuffer object is used. Exceptions Throws a TypeError, if typedArray is not a Int32Array. Throws a RangeError, if index is out of bounds in the typedArray. Examples Using notify Given a shared Int32Array: const sab = new SharedArrayBuffer(1024); const int32 = new Int32Array(sab); A reading thread is sleeping and waiting on location 0 which is expected to be 0. As long as that is true, it will not go on. However, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123). Atomics.wait(int32, 0, 0); console.log(int32[0]); // 123 A writing thread stores a new value and notifies the waiting thread once it has written: console.log(int32[0]); // 0; Atomics.store(int32, 0, 123); Atomics.notify(int32, 0, 1); Specificat...
Atomics.wait() - JavaScript
qual", or "timed-out". Exceptions Throws a TypeError, if typedArray is not a shared Int32Array. Throws a RangeError, if index is out of bounds in the typedArray. Examples Using wait() Given a shared Int32Array: const sab = new SharedArrayBuffer(1024); const int32 = new Int32Array(sab); A reading thread is sleeping and waiting on location 0 which is expected to be 0. As long as that is true, it will not go on. However, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123). Atomics.wait(int32, 0, 0); console.log(int32[0]); // 123 A writing thread stores a new value and notifies the waiting thread once it has written: console.log(int32[0]); // 0; Atomics.store(int32, 0, 123); Atomics.notify(int32, 0, 1); Specificat...
Boolean() constructor - JavaScript
us a pull request. Syntax new Boolean([value]) Parameters value Optional The initial value of the Boolean object. 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([]); var bObjProto = new Boolean({}); Specifications Specification ECMAScript (ECMA-262)The definition of 'Boolean constructor' in that specification. ...
Boolean.prototype.toString() - JavaScript
ject object; it does not inherit Object.prototype.toString(). For Boolean objects, the toString method returns a string representation of the object. JavaScript calls the toString() method automatically when a Boolean is to be represented as a text value or when a Boolean is referred to in a string concatenation. For Boolean objects and values, the built-in toString() method returns the string "true" or "false" depending on the value of the boolean object. Examples Using toString() In the following code, flag.toString() returns "true": var flag = new Boolean(true); var myVar = flag.toString(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Boolean.prototype.toString' in that specification. ...
DataView - JavaScript
ianness. Description Endianness Multi-byte number formats are represented in memory differently depending on machine architecture -- see Endianness for an explanation. DataView accessors provide explicit control of how data is accessed, regardless of the executing computer's endianness. var littleEndian = (function() { var buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 256, true /* littleEndian */); // Int16Array uses the platform's endianness. 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. As a workaround, you could implement your own getUint64() function to o...
Date.prototype.toLocaleString() - JavaScript
n, and allowed by the specification. Most notably, the IE and Edge browsers insert bidirectional control characters around dates, so the output text will flow properly when concatenated with other text. For this reason, you cannot expect to be able to 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. Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.toLocaleString' in that specification. ECMAScript Internationalization API (ECMA-402)The definition of 'Date.prototype.toLocaleString' in that specification. ...
Error - JavaScript
ew Error(message, fileName, lineNumber); instance.name = 'CustomError'; instance.foo = foo; Object.setPrototypeOf(instance, Object.getPrototypeOf(this)); if (Error.captureStackTrace) { Error.captureStackTrace(instance, CustomError); } return instance; } CustomError.prototype = Object.create(Error.prototype, { constructor: { value: Error, enumerable: false, writable: true, configurable: true } }); if (Object.setPrototypeOf){ Object.setPrototypeOf(CustomError, Error); } else { CustomError.__proto__ = Error; } try { throw new CustomError('baz', 'bazMessage'); } catch(e){ console.error(e.name); //CustomError console.error(e.foo); //baz console.error(e.message); //bazMessage } Specifications Specification ECMAScript (ECMA-26...
EvalError() constructor - JavaScript
of the code that caused the exception Examples EvalError is not used in the current ECMAScript specification and will thus not be thrown by the runtime. However, the object itself remains for backwards compatibility with earlier versions of the specification. ...
EvalError - JavaScript
k Stack trace. Inherited from Error. Examples EvalError is not used in the current ECMAScript specification and will thus not be thrown by the runtime. However, the object itself remains for backwards compatibility with earlier versions of the specification. ...
Function.prototype.apply() - JavaScript
In these cases you have to use the Function.prototype.bind method. For example, imagine having an array like the following, to be used with Date constructor: [2012, 11, 4]; in this case you have to write...
Function.caller - JavaScript
the caller thus allowing to reconstruct the stack, was removed for security reasons. Notes Note that in case of recursion, you can't reconstruct the call stack using this property. Consider: function f(n) { g(n - 1); } function g(n) { if (n > 0) { f(n); } else { stop(); } } f(2); At the moment stop() is called the call stack will be: f(2) -> g(1) -> f(1) -> g(0) -> stop() The following is true: stop.caller === g && f.caller === g && g.caller === f so if you tried to get the stack trace in the stop() function like this: var f = stop; var stack = 'Stack trace:'; while (f) { stack += '\n' + f.name; f = f.caller; } the loop would never stop. Examples Checking the value of a function's caller property The following code checks the value a function's caller property. function m...
Function.length - JavaScript
es parameters before the first one with a default value. By contrast, arguments.length is local to a function and provides the number of arguments actually passed to the function. Data property of the Function constructor The Function constructor is itself a Function object. Its length data property has a value of 1. The property attributes are: Writable: false, Enumerable: false, Configurable: true. Property of the Function prototype object The length property of the Function prototype object has a value of 0. Examples Using function length console.log(Function.length); /* 1 */ console.log((function() {}).length); /* 0 */ console.log((function(a) {}).length); /* 1 */ console.log((function(a, b) {}).length); /* 2 etc. */ console.log((function(...args) {}).length); // 0...
Function.name - JavaScript
th a static method property name(): class Foo { constructor() {} static name() {} } With a static name() method Foo.name no longer holds the actual class name but a reference to the name() function object. Above class definition in ES2015 syntax will behave in Chrome or Firefox similar to the following snippet in ES5 syntax: function Foo() {} Object.defineProperty(Foo, 'name', { writable: true }); Foo.name = function() {}; Trying to obtain the class of fooInstance via fooInstance.constructor.name won't give us the class name at all but a reference to the static class method. Example: let fooInstance = new Foo(); console.log(fooInstance.constructor.name); // logs function name() You may also see from the ES5 syntax example that in Chrome or Firefox our static definition of Foo.name...
Function - JavaScript
Constructor Function() Creates a new Function object. Calling the constructor directly can create functions dynamically but suffers from security and similar (but far less significant) performance issues to eval. However, unlike eval, the Function constructor creates functions that execute in the global scope only. Instance properties Function.arguments An array corresponding to the arguments passed to a function. This is deprecated as a property of Function. ...
Generator - JavaScript
stance methods Generator.prototype.next() Returns a value yielded by the yield expression. Generator.prototype.return() Returns the given value and finishes the generator. Generator.prototype.throw() Throws an error to a generator (also finishes the generator, unless caught from within that generator). Examples An infinite iterator function* infinite() { let index = 0; while (true) { yield index++; } } const generator = infinite(); // "Generator { }" console.log(generator.next().value); // 0 console.log(generator.next().value); // 1 console.log(generator.next().value); // 2 // ... Specifications Specification ECMAScript (ECMA-262)The definition of 'Generator objects' in that specification. ...
Intl.DateTimeFormat() constructor - JavaScript
ion, see the Intl page. timeZone The time zone to use. The only value implementations must recognize is "UTC"; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as "Asia/Shanghai", "Asia/Kolkata", "America/New_York". hour12 Whether to use 12-hour time (as opposed to 24-hour time). Possible values are true and false; the default is locale dependent. This option overrides the hc language tag and/or the hourCycle option in case both are present. hourCycle The hour cycle to use. Possible values are "h11", "h12", "h23", or "h24". This option overrides the hc language tag, if both are present, and the hour12 option takes precedence in case both options have been specified. formatMatcher The form...
Intl.DateTimeFormat.prototype.format() - JavaScript
ated with other text. For this reason you cannot expect to be able to compare the results of format() to a static value: let d = new Date("2019-01-01T00:00:00.000000Z"); let formattedDate = Intl.DateTimeFormat(undefined, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }).format(d); "1.1.2019, 01:00:00" === formattedDate; // true in Firefox and others // false in IE and Edge Note: See also this StackOverflow thread for more details and examples. Specifications Specification ECMAScript Internationalization API (ECMA-402)The definition of 'Intl.DateTimeFormat.format' in that specification. ...
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
in the proposal repository. Examples DateTimeFormat outputs localized, opaque strings that cannot be manipulated directly: var date = Date.UTC(2012, 11, 17, 3, 0, 42); var formatter = new Intl.DateTimeFormat('en-us', { weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', fractionalSecondDigits: 3, hour12: true, timeZone: 'UTC' }); formatter.format(date); // "Monday, 12/17/2012, 3:00:42.000 AM" However, in many User Interfaces there is a desire to customize the formatting of this string. The formatToParts method enables locale-aware formatting of strings produced by DateTimeFormat formatters by providing you the string in parts: formatter.formatToParts(date); // return value: [ { type: 'weekday...
Intl.NumberFormat() constructor - JavaScript
ere is no default value; if the style is "unit", the unit property must be provided. unitDisplay The unit formatting style to use in unit formatting, the defaults is "short". "long" (e.g., 16 litres) "short" (e.g., 16 l) "narrow" (e.g., 16l) useGrouping Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators. Possible values are true and false; the default is true. The following properties fall into two groups: minimumIntegerDigits, minimumFractionDigits, and maximumFractionDigits in one group, minimumSignificantDigits and maximumSignificantDigits in the other. If at least one property from the second group is defined, then the first group is ignored. minimumIntegerDigits The minimum number of integer digits to ...
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
...
JSON - JavaScript
) // throws a SyntaxError in old engines Other differences include allowing only double-quoted strings and having no provisions for undefined or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is JSON5, used by the Babel compiler, and the more commonly used YAML. 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 . Digits or DecimalNumber . Digits ExponentPart or DecimalNumber ExponentPart DecimalNumber = 0 or OneToNine Digits ExponentPart = e Exponent or ...
Map.prototype.clear() - JavaScript
this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax myMap.clear(); Return value undefined. Examples Using clear() var myMap = new Map(); myMap.set('bar', 'baz'); myMap.set(1, 'foo'); myMap.size; // 2 myMap.has('bar'); // true myMap.clear(); myMap.size; // 0 myMap.has('bar') // false Specifications Specification ECMAScript (ECMA-262)The definition of 'Map.prototype.clear' in that specification. ...
Map.prototype.delete() - JavaScript
emoves the specified element from a Map object by key. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax myMap.delete(key); Parameters key The key of the element to remove from the Map object. Return value true if an element in the Map object existed and has been removed, or false if the element does not exist. Examples Using delete() var myMap = new Map(); myMap.set('bar', 'foo'); myMap.delete('bar'); // Returns true. Successfully removed. myMap.has('bar'); // Returns false. The "bar" element is no longer present. Specifications Specification ECMAScript (ECMA-262)The def...
Map.prototype.has() - JavaScript
an element with the specified key exists or not. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax myMap.has(key) Parameters key The key of the element to test for presence in the Map object. 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.fround() - JavaScript
round toward zero. ...
Number.MAX_SAFE_INTEGER - JavaScript
ion). The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(253 - 1) and 253 - 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect. See Number.isSafeInteger() for more information. This field does not exist in old browsers. Using it without checking its existence, such as Math.max(Number.MAX_SAFE_INTEGER, 2), will yield undesired results such as NaN. Because MAX_SAFE_INTEGER is a static property of Number, you always use it as Number.MAX_SAFE_INTEGER, rather than as a property of a Number...
Number() constructor - JavaScript
The Number() constructor creates a Number object. Syntax new Number(value) Parameters value The numeric value of the object being created. 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.parseFloat() - JavaScript
ed. Return value A floating point number parsed from the given string. Or NaN when the first non-whitespace character cannot be converted to a number. Polyfill if (Number.parseFloat === undefined) { Number.parseFloat = parseFloat; } Examples Number.parseFloat vs parseFloat This method has the same functionality as the global parseFloat() function: Number.parseFloat === parseFloat; // true This method is also part of ECMAScript 2015. (Its purpose is modularization of globals.) See parseFloat() for more detail and examples. Specifications Specification ECMAScript (ECMA-262)The definition of 'Number.parseFloat' in that specification. ...
Number.parseInt() - JavaScript
from the given string. If the radix is smaller than 2 or bigger than 36, and the first non-whitespace character cannot be converted to a number, NaN is returned. Polyfill if (Number.parseInt === undefined) { Number.parseInt = window.parseInt } Examples Number.parseInt vs parseInt This method has the same functionality as the global parseInt() function: Number.parseInt === parseInt // true and is part of ECMAScript 2015 (its purpose is modularization of globals). Please see parseInt() for more detail and examples. Specifications Specification ECMAScript (ECMA-262)The definition of 'Number.parseInt' in that specification. ...
Object.getOwnPropertyNames() - JavaScript
us giving only the non-enumerable keys as output. var target = myObject; var enum_and_nonenum = Object.getOwnPropertyNames(target); var enum_only = Object.keys(target); var nonenum_only = enum_and_nonenum.filter(function(key) { var indexInEnum = enum_only.indexOf(key); if (indexInEnum == -1) { // Not found in enum_only keys, // meaning that the key is non-enumerable, // so return true so we keep this in the filter return true; } else { return false; } }); console.log(nonenum_only); Specifications Specification ECMAScript (ECMA-262)The definition of 'Object.getOwnPropertyNames' in that specification. ...
Object.getPrototypeOf() - JavaScript
ps://github.com/mdn/interactive-examples and send us a pull request. Syntax Object.getPrototypeOf(obj) Parameters obj The object whose prototype is to be returned. Return value The prototype of the given object. If there are no inherited properties, null is returned. Examples Using getPrototypeOf var proto = {}; var obj = Object.create(proto); Object.getPrototypeOf(obj) === proto; // true Non-object coercion In ES5, it will throw a TypeError exception if the obj parameter isn't an object. In ES2015, the parameter will be coerced to an Object. Object.getPrototypeOf('foo'); // TypeError: "foo" is not an object (ES5 code) Object.getPrototypeOf('foo'); // String.prototype (ES2015 code) Specifications Specification ECMAScript (ECMA-262)The ...
Object.isExtensible() - JavaScript
iption Objects are extensible by default: they can have new properties added to them, and (in engines that support __proto__) their __proto__ property can be modified. An object can be marked as non-extensible using Object.preventExtensions(), Object.seal(), or Object.freeze(). Examples Using Object.isExtensible // New objects are extensible. var empty = {}; Object.isExtensible(empty); // === true // ...but that can be changed. 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 th...
Object.seal() - JavaScript
es in objects frozen with Object.freeze() are made immutable. Objects sealed with Object.seal() can have their existing properties changed. Examples Using Object.seal var obj = { prop: function() {}, foo: 'bar' }; // New properties may be added, existing properties // may be changed or removed. obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; var o = Object.seal(obj); o === obj; // true Object.isSealed(obj); // === true // Changing property values on a sealed object // still works. obj.foo = 'quux'; // But you can't convert data properties to accessors, // or vice versa. Object.defineProperty(obj, 'foo', { get: function() { return 'g'; } }); // throws a TypeError // Now any changes, other than to property values, // will fail. obj.quaxxor = 'the friendly duck'; // silently ...
Object.prototype.valueOf() - JavaScript
...
Promise.prototype.finally() - JavaScript
will be resolved with 2. Similarly, unlike Promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with undefined), Promise.reject(3).finally(() => {}) will be rejected with 3. Note: A throw (or returning a rejected promise) in the finally callback will reject the new promise with the rejection reason specified when calling throw. ...
Promise - JavaScript
ue}`); } } catch(msg) { reject(`Error in callback ${msg}`); } resolve(value); return; }, 500); // To experiment with error at set-up, uncomment the following 'throw'. // throw new Error("Bad setup"); } catch(err) { reject(`Error during setup: ${err}`); } return; } function determineParity(value) { const isOdd = value % 2 ? 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. var tetheredGe...
handler.getOwnPropertyDescriptor() - JavaScript
f Object.getOwnPropertyDescriptor(target) can be applied to the target object using Object.defineProperty() and will not throw an exception. Examples Trapping of getOwnPropertyDescriptor The following code traps Object.getOwnPropertyDescriptor(). const p = new Proxy({ a: 20}, { getOwnPropertyDescriptor: function(target, prop) { console.log('called: ' + prop); return { configurable: true, enumerable: true, value: 10 }; } }); console.log(Object.getOwnPropertyDescriptor(p, 'a').value); // "called: a" // 10 The following code violates an invariant. const obj = { a: 10 }; Object.preventExtensions(obj); const p = new Proxy(obj, { getOwnPropertyDescriptor: function(target, prop) { return undefined; } }); Object.
handler.has() - JavaScript
, if it exists as a non-configurable own property of the target object. A property cannot be reported as non-existent, if it exists as an own property of the target object and the target object is not extensible. Examples Trapping the in operator The following code traps the in operator. const p = new Proxy({}, { has: function(target, prop) { console.log('called: ' + prop); return true; } }); console.log('a' in p); // "called: a" // true The following code violates an invariant. const obj = { a: 10 }; Object.preventExtensions(obj); const p = new Proxy(obj, { has: function(target, prop) { return false; } }); 'a' in p; // TypeError is thrown Specifications Specification ECMAScript (ECMA-262)The definition of '[[HasPr...
handler.isExtensible() - JavaScript
tensible() Reflect.isExtensible() Invariants If the following invariants are violated, the proxy will throw a TypeError: Object.isExtensible(proxy) must return the same value as Object.isExtensible(target). Examples Trapping of isExtensible The following code traps Object.isExtensible(). const p = new Proxy({}, { isExtensible: function(target) { console.log('called'); return true; } }); console.log(Object.isExtensible(p)); // "called" // true The following code violates the invariant. const p = new Proxy({}, { isExtensible: function(target) { return false; } }); Object.isExtensible(p); // TypeError is thrown Specifications Specification ECMAScript (ECMA-262)The definition of '[[IsExtensible]]' in...
handler.setPrototypeOf() - JavaScript
ithub.com/mdn/interactive-examples and send us a pull request. Syntax const p = new Proxy(target, { setPrototypeOf: function(target, prototype) { } }); Parameters The following parameters are passed to the setPrototypeOf() method. this is bound to the handler. target The target object. prototype The object's new prototype or null. Return value The setPrototypeOf() method returns true if the [[Prototype]] was successfully changed, otherwise false. Description The handler.setPrototypeOf() method is a trap for Object.setPrototypeOf(). Interceptions This trap can intercept these operations: Object.setPrototypeOf() Reflect.setPrototypeOf() Invariants If the following invariants are violated, the proxy will throw a TypeError: If target is not extensible, the prototype...
Reflect.defineProperty() - JavaScript
t.defineProperty which is similar. One key difference: Object.defineProperty returns the object or throws a TypeError if the property has not been successfully defined. Reflect.defineProperty, however, simply returns a Boolean indicating whether or not the property was successfully defined. Examples Using Reflect.defineProperty() let obj = {} Reflect.defineProperty(obj, 'x', {value: 7}) // true obj.x // 7 Checking if property definition has been successful With Object.defineProperty, which returns an object if successful, or throws a TypeError otherwise, you would use a try...catch block to catch any error that occurred while defining a property. ] Because Reflect.defineProperty returns a Boolean success status, you can just use an if...else b...
Reflect.isExtensible() - JavaScript
xceptions A TypeError, if target is not an Object. Description The Reflect.isExtensible method allows you determine if an object is extensible (whether it can have new properties added to it). It is the same method as Object.isExtensible(). Examples Using Reflect.isExtensible() See also Object.isExtensible(). // New objects are extensible. let empty = {} Reflect.isExtensible(empty) // === true // ...but that can be changed. 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...
Reflect.preventExtensions() - JavaScript
bject. Description The Reflect.preventExtensions() method allows you to prevent new properties from ever being added to an object (i.e., prevents future extensions to the object). It is similar to Object.preventExtensions(). Examples Using Reflect.preventExtensions() See also Object.preventExtensions(). // Objects are extensible by default. let empty = {} Reflect.isExtensible(empty) // === true // ...but that can be changed. 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. With Object.preventExtensions(), a non-object target will be coerced to an object. Reflect.preventExtensions(1) // TypeError: 1 is not an objec...
RegExp.prototype.flags - JavaScript
operty attributes of RegExp.prototype.flags Writable no Enumerable no Configurable yes Description Flags in the flags property are sorted alphabetically (from left to right, e.g. "gimsuy"). Polyfill if (RegExp.prototype.flags === undefined) { Object.defineProperty(RegExp.prototype, 'flags', { configurable: true, get: function() { return this.toString().match(/[gimsuy]*$/)[0]; } }); } Examples Using flags /foo/ig.flags; // "gi" /bar/myu.flags; // "muy" Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.prototype.flags' in that specification. ...
RegExp.prototype.source - JavaScript
console.log(regex.source); // "fooBar", doesn't contain /.../ and "ig". Empty regular expressions and escaping Starting with ECMAScript 5, the source property no longer returns an empty string for empty regular expressions. Instead, the string "(?:)" is returned. In addition, line terminators (such as "\n") are escaped now. new RegExp().source; // "(?:)" new RegExp('\n').source === '\n'; // true, prior to ES5 new RegExp('\n').source === '\\n'; // true, starting with ES5 Specifications Specification ECMAScript (ECMA-262)The definition of 'RegExp.prototype.source' in that specification. ...
RegExp - JavaScript
my day!' s.match(/yes.*day/); // Returns null s.match(/yes[^]*day/); // Returns ["yes\nmake my day"] Using a regular expression with the sticky flag The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at RegExp.prototype.lastIndex. ...
Set.prototype.clear() - JavaScript
e for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax mySet.clear(); Return value undefined. Examples Using the clear method var mySet = new Set(); mySet.add(1); mySet.add('foo'); mySet.size; // 2 mySet.has('foo'); // true mySet.clear(); mySet.size; // 0 mySet.has('bar') // false Specifications Specification ECMAScript (ECMA-262)The definition of 'Set.prototype.clear' in that specification. ...
Set.prototype.delete() - JavaScript
delete() method removes the specified element from a Set object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax mySet.delete(value); Parameters value The value to remove from mySet. 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. No "bar" element found to be deleted. mySet.delete('foo'); // Returns true. Successfully removed. mySet.has('foo'); // Returns false. The "foo" element is no longer present. Let's checkout below how to delete...
String.prototype.codePointAt() - JavaScript
if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return first; }; if (defineProperty) { defineProperty(String.prototype, 'codePointAt', { 'value': codePointAt, 'configurable': true, 'writable': true }); } else { String.prototype.codePointAt = codePointAt; } }()); } Examples Using codePointAt() 'ABC'.codePointAt(1) // 66 '\uD800\uDC00'.codePointAt(0) // 65536 'XYZ'.codePointAt(42) // undefined Looping with codePointAt() for (let codePoint of '\ud83d\udc0e\ud83d\udc71\u2764') { console.log(codePoint.codePointAt(0).t...
String.prototype.concat() - JavaScript
at() method. Examples Using concat() The following example combines strings into a new string. let hello = 'Hello, ' console.log(hello.concat('Kevin', '. Have a nice day.')) // Hello, Kevin. Have a nice day. let greetList = ['Hello', ' ', 'Venkat', '!'] "".concat(...greetList) // "Hello Venkat!" "".concat({}) // [object Object] "".concat([]) // "" "".concat(null) // "null" "".concat(true) // "true" "".concat(4, 5) // "45" Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.concat' in that specification. ...
String.fromCodePoint() - JavaScript
} if (codeLen >= 0x3fff) { result += stringFromCharCode.apply(null, codeUnits); codeUnits.length = 0; } } return result + stringFromCharCode.apply(null, codeUnits); }; try { // IE 8 only supports `Object.defineProperty` on DOM elements Object.defineProperty(String, "fromCodePoint", { "value": fromCodePoint, "configurable": true, "writable": true }); } catch(e) { String.fromCodePoint = fromCodePoint; } }(String.fromCharCode)); Examples Using fromCodePoint() Valid input: String.fromCodePoint(42); // "*" String.fromCodePoint(65, 90); // "AZ" String.fromCodePoint(0x404); // "\u0404" == "?" String.fromCodePoint(0x2F804); // "\uD87E\uDC04" String.fromCodePoint(194564); // "\uD87E\uDC04" ...
String.prototype.toLocaleLowerCase() - JavaScript
rCase() does not affect the value of the string itself. In most cases, this will produce the same result as toLowerCase(), but for some locales, such as Turkish, whose case mappings do not follow the default case mappings in Unicode, there may be a different result. 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. ECMAScript Internationalization API (ECMA-402)The definition o...
String.prototype.toUpperCase() - JavaScript
e. Examples Basic usage console.log('alphabet'.toUpperCase()); // 'ALPHABET' Conversion of non-string this values to strings This method will convert any non-string value to a string, when you set its this to a value that is not a string: const a = String.prototype.toUpperCase.call({ toString: function toString() { return 'abcdef'; } }); const b = String.prototype.toUpperCase.call(true); // prints out 'ABCDEF TRUE'. console.log(a, b); Specifications Specification ECMAScript (ECMA-262)The definition of 'String.prototype.toUpperCase' in that specification. ...
Symbol.prototype[@@toPrimitive] - JavaScript
data type. The hint argument is not used. JavaScript calls the [@@toPrimitive]() method to convert an object to a primitive value. You rarely need to invoke the [@@toPrimitive]() method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. Examples Using @@toPrimitive const sym = Symbol("example"); sym === sym[Symbol.toPrimitive](); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.prototype.@@toPrimitive' in that specification. ...
Symbol.for() - JavaScript
n the global symbol registry Field name Value [[key]] A string key used to identify a symbol. [[symbol]] A symbol that is stored globally. ...
Symbol.isConcatSpreadable - JavaScript
ymbol.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.isConcatSpreadable needs to be set to true in order to get a flattened array: let x = [1, 2, 3] let fakeArray = { [Symbol.isConcatSpreadable]: true, length: 2, 0: 'hello', 1: 'world' } x.concat(fakeArray) // [1, 2, 3, "hello", "world"] Note: The length property is used to control the number of object properties to be added. In the above example, length:2 indicates two properties has to be added. Specifications S...
Symbol.match - JavaScript
// Throws TypeError, as /bar/ is a regular expression // and Symbol.match is not modified. 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. The methods startsWith and endsWith won't throw a TypeError as a consequence. var re = /foo/; re[Symbol.match] = false; '/foo/'.startsWith(re); // true '/baz/'.endsWith(re); // false Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.match' in that specification. ...
Symbol.species - JavaScript
methods to return a parent Array object, instead of the MyArray object. The species symbol lets you do this: class MyArray extends Array { // Overwrite species to the parent Array constructor static get [Symbol.species]() { return Array; } } let a = new MyArray(1,2,3); let mapped = a.map(x => x * x); console.log(mapped instanceof MyArray); // false console.log(mapped instanceof Array); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.species' in that specification. ...
Symbol.toPrimitive - JavaScript
t. // An object without Symbol.toPrimitive property. var obj1 = {}; console.log(+obj1); // NaN console.log(`${obj1}`); // "[object Object]" console.log(obj1 + ''); // "[object Object]" // An object with Symbol.toPrimitive property. var obj2 = { [Symbol.toPrimitive](hint) { if (hint == 'number') { return 10; } if (hint == 'string') { return 'hello'; } return true; } }; console.log(+obj2); // 10 -- hint is "number" console.log(`${obj2}`); // "hello" -- hint is "string" console.log(obj2 + ''); // "true" -- hint is "default" Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.toPrimitive' in that specification. ...
Symbol.toStringTag - JavaScript
and more Built-in toStringTag symbols Object.prototype.toString.call(new Map()); // "[object Map]" Object.prototype.toString.call(function* () {}); // "[object GeneratorFunction]" Object.prototype.toString.call(Promise.resolv...
Symbol.prototype.valueOf() - JavaScript
of Symbol returns the primitive value of a Symbol object as a Symbol data type. JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to invoke the valueOf method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected. Examples Using valueOf const sym = Symbol("example"); sym === sym.valueOf(); // true Specifications Specification ECMAScript (ECMA-262)The definition of 'Symbol.prototype.valueOf' in that specification. ...
Symbol - JavaScript
typeof operator can help you to identify symbols. typeof Symbol() === 'symbol' typeof Symbol('foo') === 'symbol' typeof Symbol.iterator === 'symbol' Symbol type conversions Some things to note when working with type conversion of symbols. When trying to convert a symbol to a number, a TypeError will be thrown (e.g. +sym or sym | 0). When using loose equality, Object(sym) == sym returns true. Symbol("foo") + "bar" throws a TypeError (can't convert symbol to string). This prevents you from silently creating a new string property name from a symbol, for example. The "safer" String(sym) conversion works like a call to Symbol.prototype.toString() with symbols, but note that new String(sym) will throw. Symbols and for...in iteration Symbols are not enumerable in for...in iterations. ...
SyntaxError() constructor - JavaScript
ry { eval('hoo bar'); } catch (e) { console.error(e instanceof SyntaxError); console.error(e.message); console.error(e.name); console.error(e.fileName); console.error(e.lineNumber); console.error(e.columnNumber); console.error(e.stack); } Creating a SyntaxError try { throw new SyntaxError('Hello', 'someFile.js', 10); } catch (e) { console.error(e instanceof SyntaxError); // true console.error(e.message); // Hello console.error(e.name); // SyntaxError console.error(e.fileName); // someFile.js console.error(e.lineNumber); // 10 console.error(e.columnNumber); // 0 console.error(e.stack); // @debugger eval code:3:9 } Specifications Specification ECMAScri...
SyntaxError - JavaScript
ry { eval('hoo bar'); } catch (e) { console.error(e instanceof SyntaxError); console.error(e.message); console.error(e.name); console.error(e.fileName); console.error(e.lineNumber); console.error(e.columnNumber); console.error(e.stack); } Creating a SyntaxError try { throw new SyntaxError('Hello', 'someFile.js', 10); } catch (e) { console.error(e instanceof SyntaxError); // true console.error(e.message); // Hello console.error(e.name); // SyntaxError console.error(e.fileName); // someFile.js console.error(e.lineNumber); // 10 console.error(e.columnNumber); // 0 console.error(e.stack); // @debugger eval code:3:9 } Specifications Specification ECMAScri...
TypedArray.prototype.filter() - JavaScript
rce for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax typedarray.filter(callback[, thisArg]) Parameters callback Function to test each element of the typed array. Invoked with arguments (element, index, typedarray). Return true to keep the element, false otherwise. thisArg Optional Value to use as this when executing callback. Return value A new typed array with the elements that pass the test. Description The filter() method calls a provided callback function once for each element in a typed array, and constructs a new typed array of all the values for which callback returns a true value. callback is invoked onl...
TypedArray.prototype.find() - JavaScript
lement being processed in the typed array. array The array find was called upon. thisArg Optional. Object to use as this when executing callback. Return value A value in the array if an element passes the test; otherwise, undefined. Description The find method executes the callback function once for each element present in the typed array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element. Otherwise, find returns undefined. callback is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element, a...
TypedArray.prototype.findIndex() - JavaScript
ng processed in the typed array. array The typed array findIndex was called upon. thisArg Optional. Object to use as this when executing callback. Return value An index in the array if an element passes the test; otherwise, -1. Description The findIndex method executes the callback function once for each element present in the typed array until it finds one where callback returns a true value. If such an element is found, findIndex immediately returns the index of that element. Otherwise, findIndex returns -1. callback is invoked only for indexes of the typed array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. callback is invoked with three arguments: the value of the element, the index of the element...
WeakMap() constructor - JavaScript
o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps! 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.delete() - JavaScript
removes the specified element from a WeakMap object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax wm.delete(key); Parameters key The key of the element to remove from the WeakMap object. Return value true if an element in the WeakMap object has been removed successfully. false if the key is not found in the WeakMap or if the key is not an object. Examples Using the delete method var wm = new WeakMap(); wm.set(window, 'foo'); wm.delete(window); // Returns true. Successfully removed. wm.has(window); // Returns false. The window object is no longer in the WeakMap. Specifications S...
WeakMap.prototype.has() - JavaScript
Map object or not. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax wm.has(key); Parameters key Required. The key of the element to test for presence in the WeakMap object. Return value Boolean Returns true if an element with the specified key exists in the WeakMap object; otherwise false. Examples Using the has method var wm = new WeakMap(); wm.set(window, 'foo'); wm.has(window); // returns true wm.has('baz'); // returns false Specifications Specification ECMAScript (ECMA-262)The definition of 'WeakMap.prototype.has' in that specification. ...
WeakSet() constructor - JavaScript
ructor lets you create WeakSet objects that store weakly held objects in a collection. Syntax new WeakSet([iterable]); Parameters iterable If an iterable object is passed, all of its elements will be added to the new WeakSet. null is treated as undefined. 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. While they are similar objects, they are not the same object. And so they are both added to the set. Specifications Specification ECMAScript (ECMA-262)The definition of 'WeakSet constructor' in that...
WeakSet.prototype.add() - JavaScript
ke to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax ws.add(value); Parameters value Required. The object to add to the WeakSet collection. Return value The WeakSet object. Examples Using add var ws = new WeakSet(); ws.add(window); // add the window object to the WeakSet ws.has(window); // true // Weakset only takes objects as arguments ws.add(1); // results in "TypeError: Invalid value used in weak set" in Chrome // and "TypeError: 1 is not a non-null object" in Firefox Specifications Specification ECMAScript (ECMA-262)The definition of 'WeakSet.prototype.add' in that specification. ...
WeakSet.prototype.clear() - JavaScript
...
WeakSet.prototype.delete() - JavaScript
d removes the specified element from a WeakSet object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax ws.delete(value); Parameters value Required. The object remove from the WeakSet object. Return value true if an element in the WeakMap object has been removed successfully. false if the key is not found in the WeakMap or if the key is not an object. Examples Using the delete method var ws = new WeakSet(); var obj = {}; ws.add(window); ws.delete(obj); // Returns false. No obj found to be deleted. ws.delete(window); // Returns true. Successfully removed. ws.has(window); // Returns false. T...
WeakSet.prototype.has() - JavaScript
bject exists in a WeakSet or not. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax ws.has(value); Parameters value Required. The object to test for presence in the WeakSet. 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 object. WeakSet.prototype.delete(value) Removes value from the WeakSet. WeakSet.prototype.has(value) will return false afterwards. WeakSet.prototype.has(value) Returns a boolean asserting whether value is present in the WeakSet object or not. 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. While they are similar objects, they are not the same object. And so they are both added to the set. Specifications Specification ECMAScript (ECMA-262)The definition of 'WeakSet' in that specifi...
WebAssembly.CompileError() constructor - JavaScript
containing the code that caused the exception. lineNumber Optional The line number of the code that caused the exception. ...
WebAssembly.CompileError - JavaScript
Assembly.CompileError.prototype.toString() Returns a string representing the specified Error object.. Inherited from Error. ...
WebAssembly.Global() constructor - JavaScript
function assertEq(msg, got, expected) { output.innerHTML += `Testing ${msg}: `; if (got !== expected) output.innerHTML += `FAIL!<br>Got: ${got}<br>Expected: ${expected}<br>`; else output.innerHTML += `SUCCESS! ...
WebAssembly.Global - JavaScript
function assertEq(msg, got, expected) { output.innerHTML += `Testing ${msg}: `; if (got !== expected) output.innerHTML += `FAIL!<br>Got: ${got}<br>Expected: ${expected}<br>`; else output.innerHTML += `SUCCESS! ...
WebAssembly.LinkError() constructor - JavaScript
of the file containing the code that caused the exception. lineNumber Optional The line number of the code that caused the exception. ...
WebAssembly.LinkError - JavaScript
rom Error. WebAssembly.LinkError.prototype.toString() Returns a string representing the specified Error object.. Inherited from Error. ...
WebAssembly.Memory - JavaScript
alues. WebAssembly.instantiateStreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new Uint32Array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); Creating a shared memory By default, WebAssembly memories are unshared. You can create a shared memory by passing shared: true in the constructor's initialization object: let memory = new WebAssembly.Memory({initial:10, maximum:100, shared: true}); This memory's buffer property will return a SharedArrayBuffer. Specifications Specification WebAssembly JavaScript InterfaceThe definition of 'Memory' in that specification. Browser compatibility The compatibility table on this page is genera...
WebAssembly.RuntimeError() constructor - JavaScript
containing the code that caused the exception. lineNumber Optional The line number of the code that caused the exception. ...
WebAssembly.RuntimeError - JavaScript
Assembly.RuntimeError.prototype.toString() Returns a string representing the specified Error object.. Inherited from Error. ...
WebAssembly - JavaScript
ompile() Compiles a WebAssembly.Module from WebAssembly binary code, leaving instantiation as a separate step. WebAssembly.compileStreaming() compiles a WebAssembly.Module directly from a streamed underlying source, leaving instantiation as a separate step. WebAssembly.validate() Validates a given typed array of WebAssembly binary code, returning whether the bytes are valid WebAssembly code (true) or not (false). Examples Stream a .wasm module then compile and instantiate it The following example (see our instantiate-streaming.html demo on GitHub, and view it live also) directly streams a .wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a ResultObject. Because the instantiateStreaming() function accepts a promise for a Response obj...
eval() - JavaScript
0;"; console.log('z is ', eval(str)); If you define multiple values then the last value is returned. var x = 5; var str = "if (x == 5) {console.log('z is 42'); z = 42; x = 420; } else z = 0;"; console.log('x is ', eval(str)); // z is 42 x is 420 Last expression is evaluated eval() returns the value of the last expression evaluated. ...
null - JavaScript
or value: var foo = null; foo; //null Examples Difference between null and undefined When checking for null or undefined, beware of the differences between equality (==) and identity (===) operators, as the former performs type-conversion. 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
umeric operands or string concatenation. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
Addition assignment (+=) - JavaScript
s possible. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
Conditional (ternary) operator - JavaScript
colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax condition ? exprIfTrue : exprIfFalse Parameters condition An expression whose value is used as a condition. exprIfTrue An expression which is evaluated if the condition evaluates to a truthy value (one which equals or can be converted to true). 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 fal...
Nullish coalescing operator (??) - JavaScript
ated console.log( B() ?? 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 ??. A SyntaxError will be thrown in such cases. ...
Operator precedence - JavaScript
more examples follow. a || (b * c); // evaluate `a` first, then produce `a` if `a` is "truthy" a && (b < c); // evaluate `a` first, then produce `a` if `a` is "falsy" a ?? (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. Adding parentheses makes things clear: (3 > 2) > 1. Table The following table is ordered from highest (21) to lowest (1) precedence. Precedence Operator type Associativity Individual operators 21 Grouping...
Spread syntax (...) - JavaScript
n the array literal, and may be used more than once. Copy an array const arr = [1, 2, 3]; const arr2 = [...arr]; // like arr.slice() arr2.push(4); // arr2 becomes [1, 2, 3, 4] // arr remains unaffected Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays, as the following example shows. (The same is true with Object.assign() and spread syntax.) const a = [[1], [2], [3]]; const b = [...a]; b.shift().shift(); // 1 // Oh no! Now array 'a' is affected as well: a // [[], [2], [3]] A better way to concatenate arrays Array.prototype.concat() is often used to concatenate an array to the end of an existing array. Without spread syntax, this is done as: const arr1 = [0, 1, 2]; const arr2 = [3, ...
class expression - JavaScript
h class statements. The constructor method is optional. Classes generated with class expressions will always respond to typeof with the value "function". 'use strict'; let Foo = class {}; // constructor property is optional Foo = class {}; // Re-declaration is allowed typeof Foo; // returns "function" typeof class {}; // returns "function" Foo instanceof Object; // true Foo instanceof Function; // true class Foo {} // Throws SyntaxError (class declarations do not allow re-declaration) Examples A simple class expression This is just a simple anonymous class expression which you can refer to using the variable Foo. const Foo = class { constructor() {} bar() { return 'Hello World!'; } }; const instance = new Foo(); instance.bar(); // "He...
Function expression - JavaScript
itted, it will be the variable name (implicit name). If function name is present, it will be the function name (explicit name). This also applies to arrow functions (arrows don't have a name so you can only give the variable an implicit name). 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. The function returns the square of its argument: var x = function(y) { return y * y; }; Using a function as a callback More commonly it is used as a callback: button.addEv...
super - JavaScript
delete() { delete super.foo; // this is bad } } new Derived().delete(); // ReferenceError: invalid delete involving 'super'. super.prop cannot overwrite non-writable properties When defining non-writable properties with e.g. Object.defineProperty, super cannot overwrite the value of the property. 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. } } var y = new Y(); y.foo(); // TypeError: "prop" is read-only console.log(y.prop); // 1 Using super.prop in object literals Super can also be used in the object initializer / literal notation. In this example, two objec...
void operator - JavaScript
returning the result of a function call that previously returned nothing. To be safe, when the return value of a function is not intended to be used, it can be passed to the void operator to ensure that (for example) changing APIs do not cause arrow functions' behaviors to change. button.onclick = () => void doSomething(); This ensures the return value of doSomething changing from undefined to true will not change the behavior of this code. Specifications Specification ECMAScript (ECMA-262)The definition of 'The void Operator' in that specification. ...
empty - JavaScript
idea to comment intentional use of the empty statement, as it is not really obvious to distinguish from a normal semicolon. In the following example, the usage is probably not intentional: if (condition); // Caution, this "if" does nothing! killTheUniverse() // So this always gets executed!!! In the next example, an if...else statement without curly braces ({}) is used. If three is true, nothing will happen, four does not matter, and also the launchRocket() function in the else case will not be executed. if (one) doOne(); else if (two) doTwo(); else if (three) ; // nothing here else if (four) doFour(); else launchRocket(); Specifications Specification ECMAScript (ECMA-262)The definition of 'Empty statement' in that specification. ...
block - JavaScript
t before the block. In non-strict code, function declarations inside blocks behave strangely. Do not use them. Block scoping rules with let, const or function declaration in strict mode By contrast, identifiers declared with let and const do have block scope: let x = 1; { let x = 2; } console.log(x); // logs 1 The x = 2 is limited in scope to the block in which it was defined. The same is true of const: const c = 1; { const c = 2; } console.log(c); // logs 1 and does not throw SyntaxError... Note that the block-scoped const c = 2 does not throw a SyntaxError: Identifier 'c' has already been declared because it can be declared uniquely within the block. In strict mode, starting with ES2015, functions inside blocks are scoped to that block. Prior to ES2015, block-level functions wer...
do...while - JavaScript
at least once. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax do statement while (condition); statement A statement that is executed at least once and is re-executed each time the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. condition An expression evaluated after each pass through the loop. If condition evaluates to true, the statement is re-executed. When condition evaluates to false, control passes to the statement following the do...while. Examples Using do...while In the following example, the do.
function declaration - JavaScript
${typeof foo}`); if (false) { function foo(){ return 1; } } // In Chrome: // 'foo' name is hoisted. typeof foo is undefined // // In Firefox: // 'foo' name is hoisted. typeof foo is undefined // // In Edge: // 'foo' name is not hoisted. typeof foo is undefined // // In Safari: // 'foo' name is hoisted. typeof foo is function The results are exactly the same for a condition that evaluates to true var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); if (true) { function foo(){ return 1; } } // In Chrome: // 'foo' name is hoisted. typeof foo is undefined // // In Firefox: // 'foo' name is hoisted. typeof foo is undefined // // In Edge: // 'foo' name is not hoisted. typeof foo is undefined // // In Safari: // 'foo' name...
if...else - JavaScript
1 else if (condition2) statement2 else if (condition3) ... To execute multiple statements within a clause, use a block statement ({ ... }) to group those statements. 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) { ...
label - JavaScript
== 1) { break loop1; } console.log('i = ' + i + ', j = ' + j); } } // Output is: // "i = 0, j = 0" // "i = 0, j = 1" // "i = 0, j = 2" // "i = 1, j = 0" // Notice the difference with the previous continue example Using a labeled break statement Given an array of items and an array of tests, this example determines whether all items pass all tests. 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. foo: { console.log('face'); break foo; console.log('this will not be executed'); } console...
return - JavaScript
on is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x, where x is a number. function square(x) { return x * x; } var demo = square(3); // demo will equal 9 If the value is omitted, undefined is returned instead. 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). No line terminator is allowed between the return keyword and the expression. return a + b; is transformed by ASI into: return; a + b; The console will warn "unreachable code after return statement". Starting with Firefox 40, a warning is shown...
throw - JavaScript
us a pull request. Syntax throw expression; expression The expression to throw. Description Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception: throw 'Error2'; // generates an exception with a string value throw 42; // generates an exception with the value 42 throw true; // generates an exception with the value true throw new Error('Required'); // generates an error object with the message of Required Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed. Examples Throw an object You can specify an object when you throw an exception. You can th...
try...catch - JavaScript
; // re-throw the error unchanged } } The exception identifier When an exception is thrown in the try-block, exception_var (i.e., the e in catch (e)) holds the exception value. You can use this identifier to get information about the exception that was thrown. This identifier is only available in the catch-block's scope. function isValidJSON(text) { try { JSON.parse(text); 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. Note that the finally-block executes regardless of whether an exception is thrown. Also, if an exception is thrown, the statements in the finally-block execute even if no catc...
Trailing commas - JavaScript
As JSON is based on JavaScript's syntax prior to ES5, trailing commas are not allowed in JSON. Both lines will throw a SyntaxError: ...
JavaScript reference - JavaScript
arguments Arrow functions Default parameters Rest parameters Additional reference pages Lexical grammar Data types and data struc...
prefer_related_applications - Web app manifests
Type Boolean Mandatory No The prefer_related_applications member is a boolean value that specifies that applications listed in related_applications should be preferred over the web application. If the prefer_related_applications member is set to true, the user agent might suggest installing one of the related applications instead of this web app. If omitted, prefer_related_applications defaults to false. Examples "prefer_related_applications": true Specification Specification Status Comment Feedback Web App ManifestThe definition of 'prefer_related_applications' in that specification. Working Draft Initial definition. Web App Manifest Working Group drafts ...
related_applications - Web app manifests
lying platform -- for example, a native Android application obtainable through the Google Play Store. Such applications are intended to be alternatives to the manifest's website that provides similar/equivalent functionality -- like the native app equivalent. Note: Developer can specify that the native applications are preferred over the web application by setting prefer_related_applications to true. Examples "related_applications": [ { "platform": "play", "url": "https://play.google.com/store/apps/details?id=com.example.app1", "id": "com.example.app1" }, { "platform": "itunes", "url": "https://itunes.apple.com/app/example-app1/id123456789" } ] Related application values Application objects may contain the following values: Member Description ...
MathML attribute reference - MathML
tches to the size of the adjacent element. subscriptshift <mmultiscripts>, <msub>, <msubsup> The minimum space by which to shift the subscript below the baseline of the expression. supscriptshift <mmultiscripts>, <msup>, <msubsup> The minimum space by which to shift the superscript above the baseline of the expression. symmetric <mo> If stretchy is true, this attribute specifies whether the operator should be vertically symmetric around the imaginary math axis (centered fraction line). voffset <mpadded> Sets the vertical position of the child content. width <mglyph>, <mpadded>, <mspace>, <mtable> Specifies the desired width. See lengths for possible values. xlink:href All Can be used to set a hyperl...
Authoring MathML - MathML
nstant messaging clients can integrate a Javascript-based text-to-MathML converter (mentioned below) and then render the MathML expressions generated from the (plaintext) instant messages. For example, there is an Instantbird add-on that handles LaTeX expressions. Conversion from a Simple Syntax There are many simple notations (e.g. wiki or markdown syntaxes) to generate HTML pages. The same is true for MathML: for example ASCII syntaxes as used in calculators or the more powerful LaTeX language, very popular among the scientific community. In this section, we present some of these tools to convert from a simple syntax to MathML. pros: Writing mathematical expressions may only require a standard text editor. Many tools are available, some of them are compatible with the classical...
<msubsup> - MathML
seline of the expression, as a length value. This attribute is deprecated and will be removed in the future. superscriptshift The minimum space by which to shift the superscript above the baseline of the expression, as a length value. This attribute is deprecated and will be removed in the future. Examples Sample rendering: Rendering in your browser: ? 0 1 <math displaystyle="true"> <msubsup> <mo> &#x222B;<!--Integral --> </mo> <mn> 0 </mn> <mn> 1 </mn> </msubsup> </math> Specifications Specification Status Comment MathML 3.0The definition of 'msubsup' in that specification. Recommendation Current specification MathML 2.0The definition of 'msubsup' in that specification. Recommendation Initial specifica...
Media container formats (file types) - Web media technologies
Yes1 H.263 No MPEG-4 Part 2 Visual No VP9 Yes [1] Firefox support for H.264 relies upon the operating system's media infrastructure, so it is available as long as the OS supports it. [2] Firefox support for AV1 is currently disabled by default; it can be enabled by setting the preference media.av1.enabled to true. Audio codecs supported by MPEG-4 Codec Browser support Chrome Edge Firefox Safari AAC Yes1 FLAC Yes MPEG-1 Audio Layer III (MP3) Yes Opus Yes [1] Firefox support for H.264 relies upon the operating system's media infrastructure, so it is available as long as ...
OpenSearch description format
ugins including only Atom or RSS URL types (which is valid, but Firefox doesn't support) will also generate the "could not download the search plugin" error. Remotely fetched favicons must not be larger than 10KB (see bug 361923). In addition, the search plugin service provides a logging mechanism that may be useful to plugin developers. Use about:config to set the pref 'browser.search.log' to true. Then, logging information will appear in Firefox's Error Console (Tools > Error Console) when search plugins are added. Reference Material OpenSearch Documentation Safari 8.0 Release Notes: Quick Website Search Microsoft Edge Dev Guide: Search provider discovery The Chromium Projects: Tab to Search imdb.com has a working osd.xml OpenSearch Plugin Generator Ready2Search - create OpenSea...
Mobile first - Progressive web apps (PWAs)
First things first -- mobile as a default You may think that concentrating on the mobile experience first sounds pointless, as we are more used to dealing with desktop sites, and we surely need to consider the full gamut of features for the overall experience across desktop, mobile, etc., before then paring it down to a mobile experience that is simpler, more streamlined, or whatever. This rings true, yes, but in our experience mobile first is more about having the mobile implementation as a default layer to build on. We consider the overall experience during the planning stage, look at what subset of features will be available on mobile, desktop, etc. in tandem and how they will be implemented. Then at implementation stage, we present the mobile layout and functionality as the default confi...
Applying SVG effects to HTML content - SVG: Scalable Vector Graphics
0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0"/> </filter> </svg> And some more filters: <svg height="0"> <filter id="f3"> <feConvolveMatrix filterRes="100 100" style="color-interpolation-filters:sRGB" order="3" kernelMatrix="0 -1 0 -1 4 -1 0 -1 0" preserveAlpha="true"/> </filter> <filter id="f4"> <feSpecularLighting surfaceScale="5" specularConstant="1" specularExponent="10" lighting-color="white"> <fePointLight x="-5000" y="-10000" z="20000"/> </feSpecularLighting> </filter> <filter id="f5"> <feColorMatrix values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 ...
SVG Conditional Processing Attributes - SVG: Scalable Vector Graphics
The SVG conditional processing attributes are all the attributes that can be specified on some SVG elements to control whether or not the element on which it appears should be rendered. externalResourcesRequired requiredExtensions requiredFeatures systemLanguage Attributes externalResourcesRequired Deprecated since SVG 2 If set to true, it indicates that the browser must wait for all the external resources necessary to render that element to be loaded before processing the associated element. Value: false|true; Animatable: No requiredExtensions List all the browser specific capabilities that must be supported by the borwser to be allowed to render the associated element. Value: A list of space-separated URI; Animatable: No requiredFeatures Deprecated since SVG 2 Lis...
image-rendering - SVG: Scalable Vector Graphics
Note: As a presentation attribute, image-rendering can be used as a CSS property. See the css image-rendering property for more information. ...
panose-1 - SVG: Scalable Vector Graphics
The PANOSE system consists of a set of ten numbers that categorize the key attributes of a Latin typeface, a classification procedure for creating those numbers, and mapper software that determines the closest possible font match given a set of typefaces. ...
string - SVG: Scalable Vector Graphics
Web › SVG › Attribute › string
d by the parent <font-face-uri> element supports. Only one element is using this attribute: <font-face-format> Usage notes Value <anything> Default value None Animatable No <anything> This value specifies a list of formats that are supported by the font referenced by the parent <font-face-uri> element. The available types are: "woff", "woff2", "truetype", "opentype", "embedded-opentype", and "svg". See the src descriptor of the @font-face at-rule for more information. Specifications Specification Status Comment Scalable Vector Graphics (SVG) 1.1 (Second Edition)The definition of 'string' in that specification. Recommendation Initial definition ...
<switch> - SVG: Scalable Vector Graphics
Web › SVG › Element › switch
The <switch> SVG element evaluates any requiredFeatures, requiredExtensions and systemLanguage attributes on its direct child elements in order, and then renders the first child where these attributes evaluate to true. Other direct children will be bypassed and therefore not rendered. If a child element is a container element, like <g>, then its subtree is also processed/rendered or bypassed/not rendered. The display and visibility properties have no effect on <switch> element processing. In particular, setting display:none on a child has no effect on the true/false testing for <switch> processing. Usage context CategoriesContainer elementPermitted contentAny number of the following elements, in any order:Animation elementsDescriptive elementsShape elements<a>, <foreignObject>, <g>, <ima...
SVG and CSS - SVG: Scalable Vector Graphics
But you can use CSS for general-purpose XML documents, where there is no predefined way to display the elements. The next page demonstrates this: XML data ...
Tools for SVG - SVG: Scalable Vector Graphics
bility. Apache Batik URL: xmlgraphics.apache.org/batik/ Batik is a set of open source tools under the roof of the Apache Software Foundation. The toolkit is written in Java and offers almost complete SVG 1.1 support, as well as some features that were originally planned for SVG 1.2. Batik offers a viewer (Squiggle), a rasterizer for PNG output, an SVG pretty printer to format SVG files, and a TrueType-to-SVG-Font converter. Together with Apache FOP Batik can transform SVG to PDF. Other renderers Several projects exist that can create a raster image from an SVG source. ImageMagick is one of the most famous command-line image processing tools. The Gnome library rsvg is used by the Wikipedia to raster their SVG graphics. Usage of headless browsers such as SlimerJS and PhantomJS are also po...
Web Components
r not the Node is connected (directly or indirectly) to the context object, e.g. the Document object in the case of the normal DOM, or the ShadowRoot in the case of a shadow DOM. 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). Event.composedPath: Returns the event's path (objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with ShadowRoot.mode closed. HTML templates <template> Contains an HTML fragment that is not rendered when a containing document is initially loaded, but can be displayed at runtime using JavaScript, ma...
boolean - XPath
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The boolean function evaluates an expression and returns true or false. Syntax boolean( expression ) Arguments expression The expression to be evaluated. The expression can refer to numbers and node-sets as well as booleans. Returns Boolean true or false after evaluating expression. Notes A number evaluates to false if it is positive or negative zero or NaN. Otherwise, it evaluates true. A node-set evaluates to true if it is non-empty. A string evaluates to false if it an empty string. Otherwise, it evaluates to true. An object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type. Defined XPath 1.0 4.3 Gecko support S...
choose - XPath
ased on a boolean parameter. Note: This method should be used instead of if(), which has been deprecated. Syntax choose( boolean , object1, object2 ) Arguments boolean The boolean operation to use when determining which object to return. object1 The first object to consider returning. object2 The second object to consider returning. Returns If the boolean parameter is true, the first object is returned; otherwise, the second object is returned. Note: All parameters are evaluated, even the one that's not returned. Defined XForms 1.1 Gecko support Supported. ...
contains - XPath
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The contains function determines whether the first argument string contains the second argument string and returns boolean true or false. Syntax contains(haystack, needle) Arguments haystack The string to be searched needle The string to look for as a substring of haystack Returns true if haystack contains needle. Otherwise, false. Defined XPath 1.0 4.2 Gecko support Supported. ...
false - XPath
Web › XPath › Functions › 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. Syntax function-available(name ) Arguments name The name of the function to test. Returns Boolean true or false. Defined XPath 1.0 15 Gecko support Supported. ...
not - XPath
Web › XPath › Functions › not
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The not function evaluates a boolean expression and returns the opposite value. Syntax not(expression ) Arguments expression The expression is evaluated exactly as if it were passed as an argument to the boolean() function. Returns True for an expression that evaluates to false; false for an expression that evaluates to true. Notes This function should behave similarly to the boolean() function except that it returns the opposite value. You can test if an element doesn't have some attribute. <xsl:for-each match="//a[not(@name and @name = 'badname')]"> <!-- iterates over any <a> element in the document, that either has no 'name' attribute at all, or it has one, ...
number - XPath
o be converted to a number. If this argument is omitted, the current context node will be used. Returns The resulting number after converting the object. Notes Strings are converted to a number by stripping the leading whitespace in the string before the number and ignoring whitespace after the number. If the string does not match this pattern, then the string is converted to NaN. Boolean true is converted to 1. False is converted to 0. A node-set is first converted to a string as if by a call to the string() function and then converted in the same way as a string argument. An object of a type other than the four basic types is converted to a number in a way that is dependent on that type. Defined XPath 1.0 4.4 Gecko support Supported. ...
starts-with - XPath
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The starts-with checks whether the first string starts with the second string and returns true or false. Syntax starts-with(haystack, needle) Arguments haystack The string to look in. needle The string to look for. Returns true if haystack starts with needle. Otherwise, false. Defined XPath 1.0 4.2 Gecko support Supported. ...
string - XPath
s converted as follows: NaN is converted to the string NaN. Positive zero is converted to the string 0. Negative zero is converted to the string 0. Positive infinity is converted to the string Infinity. Negative infinity is converted to the string -Infinity. Decimal numbers between -1 and 1 are converted to a string with a single leading 0 before the decimal point. Boolean true is converted to the string true. Boolean false is converted to the string false. Defined XPath 1.0 4.2 Gecko support Supported. ...
Functions - XPath
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() true() unparsed-entity-url() XSLT-specific (not supported) ...
Introduction to using XPath in JavaScript - XPath
allowing us to access the individual nodes contained by using the iterateNext() method of the XPathResult. Once we have iterated over all of the individual matched nodes, iterateNext() will return null. Note however, that if the document is mutated (the document tree is modified) between iterations that will invalidate the iteration and the invalidIteratorState property of XPathResult is set to true, and a NS_ERROR_DOM_INVALID_STATE_ERR exception is thrown. Iterator Example var iterator = document.evaluate('//phoneNumber', documentNode, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null ); try { var thisNode = iterator.iterateNext(); while (thisNode) { alert( thisNode.textContent ); thisNode = iterator.iterateNext(); } } catch (e) { alert( 'Error: Document tree modifie...
<xsl:if> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › if
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:if> element contains a test attribute and a template. If the test evaluates to true, the template is processed. In this it is similar to an if statement in other languages. To achieve the functionality of an if-then-else statement, however, use the <xsl:choose> element with one <xsl:when> and one <xsl:otherwise> children. Syntax <xsl:if test=EXPRESSION> TEMPLATE </xsl:if> Required Attributes test Contains an XPath expression that can be evaluated (using the rules defined for boolean( ) if necessary) to a Boolean value. If the value is true, the template is processed; if it is not, no action is taken. Optional Attributes None. Type Instruction, appears within a template. Defin...
<xsl:when> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › when
XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes The <xsl:when> element always appears within an <xsl:choose> element, acting like a case statement. Syntax <xsl:when test=EXPRESSION> TEMPLATE </xsl:when> Required Attributes test Specifies a boolean expression to be evaluated. If true, the contents of the element are processed; if false, they are ignored. Optional Attributes None. Type Subinstruction, always appears within an <xsl:choose> element. Defined XSLT, section 9.2. Gecko support Supported. ...
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
strophe and quote characters. Examples Set the parameter 'color' to the string 'red': <?xslt-param name="color" value="red"?> Set the parameter 'columns' to the number 2: <?xslt-param name="columns" select="2"?> Set the parameter 'books' to a nodeset containing all <book> elements in the null namespace: <?xslt-param name="books" select="//book"?> Set the parameter 'show-toc' to boolean true: <?xslt-param name="show-toc" select="true()"?> The select attribute context The following context is used to parse and evaluate the expression in the select attribute. The context node is the node used as initial current node used when executing the stylesheet. The context position is the position of the context node in the initial current node list used when executing the stylesheet. ...
The Netscape XSLT/XPath Reference - XSLT: Extensible Stylesheet Language Transformations
mespace-uri() (supported) normalize-space() (supported) not() (supported) number() (supported) position() (supported) round() (supported) starts-with() (supported) string() (supported) string-length() (supported) substring() (supported) substring-after() (supported) substring-before() (supported) sum() (supported) system-property() (supported) translate() (supported) true() (supported) unparsed-entity-url() (not supported) ...
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
All rights reserved. Note: This reprinted article was originally part of the DevE...
Web technology for developers
HTML, CSS, and so on. Web Developer Guide The Web Developer Guide provides useful how-to content to help you actually use Web technologies to do what you want or need to do. Tutorials for Web developers A list of tutorials to take you step-by-step through learning APIs, technologies, or broad topic areas. Developing Web applications Documentation for Web application developers; Web apps are true write-once, deploy anywhere apps for mobile, desktop, and Firefox OS. Code snippets This is a quick list of useful code snippets (small code samples) available for developers of extensions for the various Mozilla applications. Many of these samples can also be used in XULRunner applications, as well as in actual Mozilla code itself. View All... Web technology references Web APIs Refere...