Search completed in 5.95 seconds.
:-moz-system-metric(windows-default-theme) - Archive of obsolete content
the :-moz-system-metric(windows-default-the
me) css pseudo-class matches an element if the user is currently using one of the following themes in windows: luna, royale, zune, or aero (i.e., vista basic, vista standard, or aero glass).
...</p> <p id="notsupported">theme detection is not supported.</p> css content #defaultthemes, #nondefaultthemes { background-color: #ffa0a0; } #defaultthemes:-moz-system-metric(windows-default-the
me) { background-color: #a0ffa0; } #nondefaultthemes:not(-moz-system-metric(windows-default-the
me)) { background-color: #a0ffa0; } #notsupported:-moz-system-metric(windows-default-the
me), #notsupported:not(:-moz-system-metric(windows-default-the
me)) { display: none; } specifications not part of any specification.
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
add_cert_to_db, save_cert_to_header, encrypt, decrypt, sign, verify, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4, pubkey = 5, lab = 6, certenc= 7, certvfy= 8, sig = 9 } headertype; /* * print usage message and exit */ static void usage(const char *progna
me) { fprintf(stderr, "\nusage: %s %s %s %s %s %s %s %s %s %s\n\n", progname, " -<g|a|h|e|ds|v> -d <dbdirpath> ", "[-p <dbpwd> | -f <dbpwdfile>] [-z <noisefilename>] [-a <\"\">]", "-s <subject> -r <csr> | ", "-n <nickname> -t <trust> -c <cert> [ -r <csr> -u <issuernickname> [-x <\"\">] -m <serialnumber> ] | ", "-n <n...
...ig verification [optional]\n\n", "-v"); exit(-1); } /* * validate the options used for generate csr command */ static void validategeneratecsrcommand(const char *progname, const char *dbdir, certname *subject, const char *subjectstr, const char *certreqfilena
me) { 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 (!certreqfilena
me) { pr_fprintf(pr_stderr, "%s -g -d %s -s %s -r: certificate request file name not found\n", prognam...
...; if (!nicknamestr) { pr_fprintf(pr_stderr, "%s -a -d %s -n : nick name is missing\n", progname, dbdir); validationfailed = pr_true; } if (!truststr) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t: trust flag is missing\n", progname, dbdir, nicknamestr); validationfailed = pr_true; } if (!certfilena
me) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t %s -c: certificate file name not found\n", progname, dbdir, nicknamestr, truststr, serialnumberstr, certreqfilena
me); validationfailed = pr_true; } if (pr_access(certfilename, pr_access_exists) == pr_failure) { if (!certreqfilena
me) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t %s -...
...And 38 more matches
sample2
rrortostring((err), pr_language_i_default) #endif /* sample 6 commands */ typedef enum { generate_csr, add_cert_to_db, save_cert_to_header, encrypt, decrypt, sign, verify, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4, pubkey = 5, lab = 6, certenc= 7, certvfy= 8, sig = 9 } headertype; /* * print usage message and exit */ static void usage(const char *progna
me) { fprintf(stderr, "\nusage: %s %s %s %s %s %s %s %s %s %s\n\n", progname, " -<g|a|h|e|ds|v> -d <dbdirpath> ", "[-p <dbpwd> | -f <dbpwdfile>] [-z <noisefilename>] [-a <\"\">]", "-s <subject> -r <csr> | ", "-n <nickname> -t <trust> -c <cert> [ -r <csr> -u <issuernickname> [-x <\"\">] -m <serialnumber> ] | ", "-n <nickname> -b <headerfilename> | ", "-b <headerfilename> -i <ipfilename> -e <encryptfil...
...\n", "-x"); fprintf(stderr, "%-30s - to enable ascii [optional]\n\n", "-a"); fprintf(stderr, "%-30s - to save certificate to header file as sig verification [optional]\n\n", "-v"); exit(-1); } /* * validate the options used for generate csr command */ static void validategeneratecsrcommand(const char *progname, const char *dbdir, certname *subject, const char *subjectstr, const char *certreqfilena
me) { 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 (!certreqfilena
me) { 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(std...
...ar *issuernamestr, const char *serialnumberstr, prbool selfsign) { prbool validationfailed = pr_false; if (!nicknamestr) { pr_fprintf(pr_stderr, "%s -a -d %s -n : nick name is missing\n", progname, dbdir); validationfailed = pr_true; } if (!truststr) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t: trust flag is missing\n", progname, dbdir, nicknamestr); validationfailed = pr_true; } if (!certfilena
me) { pr_fprintf(pr_stderr, "%s -a -d %s -n %s -t %s -c: certificate file name not found\n", progname, dbdir, nicknamestr, truststr, serialnumberstr, certreqfilena
me); validationfailed = pr_true; } if (pr_access(certfilename, pr_access_exists) == pr_failure) { if (!certreqfilena
me) { 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",...
...And 35 more matches
Enc Dec MAC Output Public Key as CSR
*/ #ifndef port_errortostring #ifndef sec_error_base #define sec_error_base (-0x2000) #define port_errortostring(err) pr_errortostring((err), pr_language_i_default) #endif #endif /* * print usage message and exit */ static void usage(const char *progna
me) { fprintf(stderr, "\nusage: %s -c -d [-z ] " "[-p | -f ] -s -r -i -o \n\n", progna
me); fprintf(stderr, "%-20s specify 'g' for generating rsa keypair for wrapping\n\n", "g"); fprintf(stderr, "%-20s specify 'e' for encrypt operation\n\n", "e"); fprintf(stderr, "%-20s specify 'd' for decrypt operation\n\n", "d"...
...item *item, prbool ishexdata) { secstatus rv; secitem filedata; secitem outbuf; unsigned char *nonbody; unsigned char *body; char *header; char *trailer; prfiledesc *file = null; outbuf.type = sibuffer; file = pr_open(filename, pr_rdonly, 0); if (!file) { pr_fprintf(pr_stderr, "failed to open %s\n", filena
me); return secfailure; } switch (type) { case pubkey: header = pubkey_header; trailer = pubkey_trailer; break; case symkey: header = enckey_header; trailer = enckey_trailer; break; case mackey: header = mackey_header; trailer = mackey_trailer; break; case iv: header = iv_header; tr...
...pubkey->u.rsa.modulus; cka_id = pk11_makeidfrompubkey(cka_id); privkey = pk11_findkeybykeyid(slot, cka_id, pwdata); cleanup: return privkey; } /* * generate the certificate request with subject */ static secstatus certreq(seckeyprivatekey *privk, seckeypublickey *pubk, keytype keytype, secoidtag hashalgtag, certname *subject, prbool ascii, const char *certreqfilena
me) { certsubjectpublickeyinfo *spki = null; certcertificaterequest *cr = null; secitem *encoding = null; secoidtag signalgtag; secitem result; secstatus rv = secsuccess; print32 numbytes; void *exthandle; prarenapool ...
...And 15 more matches
Old Proxy API - Archive of obsolete content
fundamental traps emulated javascript code handler method description object.getownpropertydescriptor(proxy, na
me) getownpropertydescriptor: function(na
me) -> propertydescriptor | undefined should return a valid property descriptor object, or undefined to indicate that no property with name exists in the emulated object.
... object.getpropertydescriptor(proxy, na
me) getpropertydescriptor: function(na
me) -> propertydescriptor | undefined this function doesn't exist in ecmascript 5.
... delete proxy.name delete: function(na
me) -> boolean delete the named property from the proxy.
...And 11 more matches
Encrypt Decrypt_MAC_Using Token
*/ static void usage(const char *progna
me) { fprintf(stderr, "\nusage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progna
me); fprintf(stderr, "%-20s specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s specify db directory path\n\n", "-d "); fprintf(stderr, "%-20s ...
...tem *item, prbool ishexdata) { secstatus rv; prfiledesc* file; secitem filedata; secitem outbuf; unsigned char *nonbody; unsigned char *body; char header[40]; char trailer[40]; outbuf.type = sibuffer; file = pr_open(filename, pr_rdonly, 0); if (!file) { pr_fprintf(pr_stderr, "failed to open %s\n", filena
me); return secfailure; } switch (type) { case symkey: strcpy(header, enckey_header); strcpy(trailer, enckey_trailer); break; case mackey: strcpy(header, mackey_header); strcpy(trailer, mackey_trailer); break; case iv: strcpy(header, iv_header); strcpy(trailer, iv_trailer); break; case mac: ...
... */ infile = pr_open(encryptedfilename, pr_rdonly , 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for writing.\n", encryptedfilena
me); return secfailure; } /* open the output file.
...And 9 more matches
Encrypt Decrypt MAC Keys As Session Objects
efine mac_trailer "-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" typedef enum { encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4 } headertype; /* * print usage message and exit */ static void usage(const char *progna
me) { fprintf(stderr, "\nusage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progna
me); fprintf(stderr, "%-20s specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s specify db directory path\n\n", "-d "); fprintf(stderr, "%-20s ...
...tem *item, prbool ishexdata) { secstatus rv; prfiledesc* file; secitem filedata; secitem outbuf; unsigned char *nonbody; unsigned char *body; char header[40]; char trailer[40]; outbuf.type = sibuffer; file = pr_open(filename, pr_rdonly, 0); if (!file) { pr_fprintf(pr_stderr, "failed to open %s\n", filena
me); return secfailure; } switch (type) { case symkey: strcpy(header, enckey_header); strcpy(trailer, enckey_trailer); break; case mackey: strcpy(header, mackey_header); strcpy(trailer, mackey_trailer); break; case iv: strcpy(header, iv_header); strcpy(trailer, iv_trailer); break; case mac: ...
... */ infile = pr_open(encryptedfilename, pr_rdonly , 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for writing.\n", encryptedfilena
me); return secfailure; } /* open the output file.
...And 8 more matches
Encrypt and decrypt MAC using token
efine mac_trailer "-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" typedef enum { encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4 } headertype; /* * print usage message and exit */ static void usage(const char *progna
me) { fprintf(stderr, "\nusage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progna
me); fprintf(stderr, "%-20s specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s specify db directory path\n\n", "-d "); fprintf(stderr, "%-20s ...
...tem *item, prbool ishexdata) { secstatus rv; prfiledesc* file; secitem filedata; secitem outbuf; unsigned char *nonbody; unsigned char *body; char header[40]; char trailer[40]; outbuf.type = sibuffer; file = pr_open(filename, pr_rdonly, 0); if (!file) { pr_fprintf(pr_stderr, "failed to open %s\n", filena
me); return secfailure; } switch (type) { case symkey: strcpy(header, enckey_header); strcpy(trailer, enckey_trailer); break; case mackey: strcpy(header, mackey_header); strcpy(trailer, mackey_trailer); break; case iv: strcpy(header, iv_header); strcpy(trailer, iv_trailer); break; case mac: ...
... */ infile = pr_open(encryptedfilename, pr_rdonly , 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for writing.\n", encryptedfilena
me); return secfailure; } /* open the output file.
...And 8 more matches
NSS Sample Code Sample_3_Basic Encryption and MACing
#define mac_trailer "-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" typedef enum { encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4 } headertype; /* print a usage message and exit */ static void usage(const char *progna
me) { fprintf(stderr, "\nusage: %s -c <a|b> -d <dbdirpath> [-z <noisefilename>] " "[-p <dbpwd> | -f <dbpwdfile>] -i <ipfilename> -o <opfilename>\n\n", progna
me); fprintf(stderr, "%-20s specify 'a' for encrypt operation\n\n", "-c <a|b>"); fprintf(stderr, "%-20s specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s spe...
...tem *item, prbool ishexdata) { secstatus rv; prfiledesc* file; secitem filedata; secitem outbuf; unsigned char *nonbody; unsigned char *body; char header[40]; char trailer[40]; outbuf.type = sibuffer; file = pr_open(filename, pr_rdonly, 0); if (!file) { pr_fprintf(pr_stderr, "failed to open %s\n", filena
me); return secfailure; } switch (type) { case symkey: strcpy(header, enckey_header); strcpy(trailer, enckey_trailer); break; case mackey: strcpy(header, mackey_header); strcpy(trailer, mackey_trailer); break; case iv: strcpy(header, iv_header); strcpy(trailer, iv_trailer); break; case mac: ...
... */ infile = pr_open(encryptedfilename, pr_rdonly , 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for writing.\n", encryptedfilena
me); return secfailure; } /* open the output file.
...And 8 more matches
EncDecMAC using token object - sample 3
iv_trailer "-----end iv-----" #define mac_header "-----begin mac-----" #define mac_trailer "-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" typedef enum { encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4 } headertype; /* * print usage message and exit */ static void usage(const char *progna
me) { fprintf(stderr, "\nusage: %s -c -d [-z ] " "[-p | -f ] -i -o \n\n", progna
me); fprintf(stderr, "%-20s specify 'a' for encrypt operation\n\n", "-c "); fprintf(stderr, "%-20s specify 'b' for decrypt operation\n\n", " "); fprintf(stderr, "%-20s specify db directory path\n\n", "-d "); fprintf(stderr, "%-20s specify db password [optional]\n\n", "-p "); fprintf(stderr, "%-20s specify db password file...
...rom the header file */ secstatus readfromheaderfile(const char *filename, headertype type, secitem *item, prbool ishexdata) { secstatus rv; prfiledesc* file; secitem filedata; secitem outbuf; unsigned char *nonbody; unsigned char *body; char header[40]; char trailer[40]; outbuf.type = sibuffer; file = pr_open(filename, pr_rdonly, 0); if (!file) { pr_fprintf(pr_stderr, "failed to open %s\n", filena
me); return secfailure; } switch (type) { case symkey: strcpy(header, enckey_header); strcpy(trailer, enckey_trailer); break; case mackey: strcpy(header, mackey_header); strcpy(trailer, mackey_trailer); break; case iv: strcpy(header, iv_header); strcpy(trailer, iv_trailer); break; case mac: strcpy(header, mac_header); strcpy(trailer, mac_trailer); break; case pad: strcpy(header, pad_header); strcpy(t...
...*/ infile = pr_open(encryptedfilename, pr_rdonly , 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for writing.\n", encryptedfilena
me); return secfailure; } /* open the output file.
...And 8 more matches
DOMException - Web APIs
(legacy code value: 25 and legacy constant name: data_clone_err) encodingerror the encoding or decoding operation failed (no legacy code value and constant na
me).
... notreadableerror the input/output read operation failed (no legacy code value and constant na
me).
...out of memory) (no legacy code value and constant na
me).
...And 7 more matches
jspage - Archive of obsolete content
(a-b+1)+b);}function $splat(b){var a=$type(b); return(a)?((a!="array"&&a!="arguments")?[b]:b):[];}var $time=date.now||function(){return +new date;};function $try(){for(var b=0,a=arguments.length;b<a; b++){try{return arguments[b]();}catch(c){}}return null;}function $type(a){if(a==undefined){return false;}if(a.$family){return(a.$family.name=="number"&&!isfinite(a))?false:a.$family.name; }if(a.nodena
me){switch(a.nodetype){case 1:return"element";case 3:return(/\s/).test(a.nodevalue)?"textnode":"whitespace";}}else{if(typeof a.length=="number"){if(a.callee){return"arguments"; }else{if(a.item){return"collection";}}}}return typeof a;}function $unlink(c){var b;switch($type(c)){case"object":b={};for(var e in c){b[e]=$unlink(c[e]); }break;case"hash":b=new hash(c);break;case"array":b=[];for(var d=0,a=c.l...
...ength;d<a;d++){b[d]=$unlink(c[d]);}break;default:return c;}return b;}var browser=$merge({engine:{name:"unknown",version:0},platform:{name:(window.orientation!=undefined)?"ipod":(navigator.platform.match(/mac|win|linux/i)||["other"])[0].tolowercase()},features:{xpath:!!(document.evaluate),air:!!(window.runti
me),query:!!(document.queryselector)},plugins:{},engines:{presto:function(){return(!window.opera)?false:((arguments.callee.caller)?960:((document.getelementsbyclassna
me)?950:925)); },trident:function(){return(!window.activexobject)?false:((window.xmlhttprequest)?((document.queryselectorall)?6:5):4);},webkit:function(){return(navigator.taintenabled)?false:((browser.features.xpath)?((browser.features.query)?525:420):419); },gecko:function(){return(!document.getboxobjectfor&&window.mozinnerscr...
...eenx==null)?false:((document.getelementsbyclassna
me)?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");});};browser.features.xhr=!!(browser.request());browser.plugins.flash=(function(){var a=($try(function(){return navigator.plugins["shockwave flash"].description; },function(){return new activexobject("shockwaveflash.shockwaveflash").getvariable("$version");})||"0 r0").match(/\d+/g)...
...And 6 more matches
nsIMsgFolder
deletesubfolders(in nsisupportsarray folders, in nsimsgwindow msgwindow); void propagatedelete(in nsimsgfolder folder, in boolean deletestorage,in nsimsgwindow msgwindow); void recursivedelete(in boolean deletestorage, in nsimsgwindow msgwindow); void createsubfolder(in astring foldername, in nsimsgwindow msgwindow); nsimsgfolder addsubfolder(in astring folderna
me); void createstorageifmissing(in nsiurllistener urllistener); void compact(in nsiurllistener alistener, in nsimsgwindow amsgwindow); void compactall(in nsiurllistener alistener, innsimsgwindow amsgwindow,in nsisupportsarray afolderarray, in boolean acompactofflinealso,in nsisupportsarray aofflinefolderarray); void compactallofflinestores(in nsimsgwindow amsgwind...
...in acstring command); boolean matchorchangefilterdestination(in nsimsgfolder folder,in boolean caseinsensitive); boolean confirmfolderdeletionforfilter(in nsimsgwindow msgwindow); void alertfilterchanged(in nsimsgwindow msgwindow); void throwalertmsg(in string msgname, in nsimsgwindow msgwindow); astring getstringwithfoldernamefrombundle(in string msgna
me); void notifycompactcompleted(); long comparesortkeys(in nsimsgfolder msgfolder); [noscript] void getsortkey(out octet_ptr key, out unsigned long length); boolean callfilterplugins(in nsimsgwindow amsgwindow); acstring getstringproperty(in string propertyna
me); void setstringproperty(in string propertyname, in acstring propertyvalue); ...
...boolean isancestorof(in nsimsgfolder folder); boolean containschildnamed(in astring na
me); nsimsgfolder getchildnamed(in astring ana
me); nsimsgfolder findsubfolder(in acstring escapedsubfolderna
me); void addfolderlistener(in nsifolderlistener listener); void removefolderlistener(in nsifolderlistener listener); void notifypropertychanged(in nsiatom property, in acstring oldvalue, in acstring newvalue); void notifyintpropertychanged(in nsiatom property, in long oldvalue, in long newvalue); void notifyboolpropertychanged(in nsiatom property, in boolean oldvalue, in boolean newvalue); void notifypropertyflagchanged(in nsimsgdbhdr item, in nsiatom property, in unsigned long oldvalue, in unsigned long newvalue); ...
...And 6 more matches
Search Extension Tutorial (Draft) - Archive of obsolete content
savedprefs[name] = [defaultprefs.getcharpref(na
me), value]; // change the default defaultprefs.setcharpref(name, value); // clear the user value if this is the first run, or the // new default is the same as the user value.
... if (firstrun || userprefs.getcharpref(na
me) == value) userprefs.clearuserpref(na
me); } function startup(data, reason) { firstrun = reason == addon_install; // change the default engine name.
... for (let [name, [origvalue, value]] in iterator(savedprefs)) { if (defaultprefs.getcharpref(na
me) == value) defaultprefs.setcharpref(name, origvalue); } } function install() {} function uninstall() {} changing the default search engine this change comes in two parts: 1) installing a new search engine (and removing it when your extension is disabled), and 2) setting it as a default (and restoring the previous default when your extension is uninstalled).
...And 5 more matches
2D maze game with device orientation - Game development
ript> <script src="src/howto.js"></script> <script src="src/game.js"></script> </head> <body> <script> (function() { var game = new phaser.game(320, 480, phaser.canvas, 'game'); game.state.add('boot', ball.boot); game.state.add('preloader', ball.preloader); game.state.add('mainmenu', ball.mainmenu); game.state.add('howto', ball.howto); game.state.add('game', ball.ga
me); game.state.start('boot'); })(); </script> </body> </html> so far we have a simple html website with some basic content in the <head> section: charset, title, css styling and the inclusion of the javascript files.
... var ball = { _width: 320, _height: 480 }; ball.boot = function(ga
me) {}; ball.boot.prototype = { preload: function() { this.load.image('preloaderbg', 'img/loading-bg.png'); this.load.image('preloaderbar', 'img/loading-bar.png'); }, create: function() { this.game.scale.scalemode = phaser.scalemanager.show_all; this.game.scale.pagealignhorizontally = true; this.game.scale.pagealignvertically = true; this.ga...
... preloader.js the preloader state takes care of loading all the assets: ball.preloader = function(ga
me) {}; ball.preloader.prototype = { preload: function() { this.preloadbg = this.add.sprite((ball._width-297)*0.5, (ball._height-145)*0.5, 'preloaderbg'); this.preloadbar = this.add.sprite((ball._width-158)*0.5, (ball._height-50)*0.5, 'preloaderbar'); this.load.setpreloadsprite(this.preloadbar); this.load.image('ball', 'img/ball.png'); // ...
...And 5 more matches
Index - Web APIs
238 baseaudiocontext.creategain() api, audio, audiocontext, baseaudiocontext, method, reference, volume control, web audio api, creategain, sound a gainnode which takes as input one or more audio sources and outputs audio whose volume has been adjusted in gain (volu
me) to a level specified by the node's gainnode.gain a-rate parameter.
... 653 compositionevent.locale api, compositionevent, deprecated, locale, property, reference the locale read-only property of the compositionevent interface returns the locale of current input method (for example, the keyboard layout locale if the composition is associated with i
me).
... 843 deviceorientationevent.absolute api, device orientation api, deviceorientationevent, needsexample, needsmarkupwork, property, reference indicates whether or not the device is providing orientation data absolutely (that is, in reference to the earth's coordinate fra
me) or using some arbitrary frame determined by the device.
...And 5 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
let sweeplength = 2; function playsweep() { let osc = audioctx.createoscillator(); osc.setperiodicwave(wave); osc.frequency.value = 440; let sweepenv = audioctx.creategain(); sweepenv.gain.cancelscheduledvalues(audioctx.currentti
me); sweepenv.gain.setvalueattime(0, audioctx.currentti
me); // set our attack sweepenv.gain.linearramptovalueattime(1, audioctx.currenttime + attackti
me); // set our release sweepenv.gain.linearramptovalueattime(0, audioctx.currenttime + sweeplength - releaseti
me); osc.connect(sweepenv).connect(audioctx.destination); osc.start(); osc.stop(audioctx.currenttime + sweepl...
...eep sound, except we won't use a wavetable to set a bespoke wave — we'll just use the default sine wave: let osc = audioctx.createoscillator(); osc.type = 'sine'; osc.frequency.value = 880; now we're going to create a gainnode, as it's the gain value that we will oscillate with our second, low frequency oscillator: let amp = audioctx.creategain(); amp.gain.setvalueattime(1, audioctx.currentti
me); creating the second, low frequency, oscillator we'll now create a second — square — wave (or pulse) oscillator, to alter the amplification of our first sine wave: let lfo = audioctx.createoscillator(); lfo.type = 'square'; lfo.frequency.value = 30; connecting the graph the key here is connecting the graph correctly, and also starting both oscillators: lfo.connect(amp.gain); osc.connect...
...(amp).connect(audioctx.destination); lfo.start(); osc.start(); osc.stop(audioctx.currenttime + pulseti
me); note: we also don't have to use the default wave types for either of these oscillators we're creating — we could use a wavetable and the periodic wave method as we did before.
...And 5 more matches
preferences/service - Archive of obsolete content
example: var name = "extensions.checkcompatibility.nightly"; var nightlycompatchk = require("sdk/preferences/service").get(na
me); has(na
me) parameters name : string preference name.
... defaultvalue example: var name = "extensions.checkcompatibility.nightly"; if (require("sdk/preferences/service").has(na
me)) { // ...
... isset(na
me) parameters name : string preference name.
...And 4 more matches
Using the Places annotation service
nents.interfaces.nsiioservice); var uri = ioservice.newuri("http://www.mozilla.org/", null, null); annotationservice.setpageannotation(uri, "my_extension/some_annotation", "this is the annotation value", 0, 0); retrieving annotations there are corresponding getters for the setters above (see nsiannotationservice.idl for the exact declarations): from c++: getpageannotationstring(auri, ana
me); getpageannotationint32(auri, ana
me); getpageannotationint64(auri, ana
me); getpageannotationdouble(auri, ana
me); getpageannotationbinary(auri, aname, adata, adatalen, amimetype); getitemannotationstring(aitemid, ana
me); getitemannotationint32(aitemid, ana
me); getitemannotationint64(aitemid, ana
me); getitemannotationdouble(aitemid, ana
me); getitemannotationbinary(aitemid, aname, adata,...
... adatalen, amimetype); from javascript: getpageannotation(auri, ana
me); getitemannotation(aitemid, ana
me); these functions will return/throw ns_error_not_available if the annotation requested does not exist.
...four functions are provided to get this information: getpageannotationinfo(auri, aname, aflags, aexpiration, amimetype, atype) getitemannotationinfo(aitemid, aname, aflags, aexpiration, amimetype, atype) getpageannotationtype(auri, ana
me); getitemannotationtype(aitemid, ana
me); the returned type will be one of the value_type constants in mozistoragevaluearray.idl: after bug 377066 the value_type_* type handling was changed to this: type_int32 = 1 type_double = 2 type_string = 3 type_binary = 4 type_int64 = 5 try { var value = annotationservice.getpageannotation(uri, "my_extension/some_annotation"); } catch(e) { //...
...And 4 more matches
nsIFile
void appendrelativenativepath(in acstring relativefilepath); void appendrelativepath(in astring relativefilepath); nsifile clone(); boolean contains(in nsifile infile); void copyto(in nsifile newparentdir, in astring newna
me); void copytofollowinglinks(in nsifile newparentdir, in astring newna
me); void copytofollowinglinksnative(in nsifile newparentdir, in acstring newna
me); native code only!
... void copytonative(in nsifile newparentdir, in acstring newna
me); native code only!
...void initwithpath(in astring filepath); boolean isdirectory(); boolean isexecutable(); boolean isfile(); boolean ishidden(); boolean isreadable(); boolean isspecial(); boolean issymlink(); boolean iswritable(); void launch(); prlibrarystar load(); void moveto(in nsifile newparentdir, in astring newna
me); void movetonative(in nsifile newparentdir, in acstring newna
me); native code only!
...And 4 more matches
Debugger.Object - Firefox Developer Tools
for example: function f() {} // display name: f (the given na
me) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; note that the display name may not be a proper javascript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property.
... getproperty(na
me) return the value of the referent's property namedname, or undefined if it has no such property.name must be a string.
... getownpropertydescriptor(na
me) return a property descriptor for the property namedname of the referent.
...And 4 more matches
Rendering and the WebXR frame animation callback - Web APIs
g off the renderer thus looks like this: let worldrefspace; async function runxr(xrsession) { worldrefspace = await xrsession.requestreferencespace("immersive-vr"); if (worldrefspace) { viewerrefspace = worldrefspace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, viewerstartorientation)); animationframerequestid = xrsession.requestanimationframe(mydrawfra
me); } } after getting a reference space for the immersive world, this creates an offset reference space representing the position and orientation of the viewer by creating an xrrigidtransform representing that position and orientation, then calling the xrreferencespace method getoffsetreferencespace().
... let lastframetime = 0; function mydrawframe(currentframetime, fra
me) { let session = frame.session; let viewerpose; // schedule the next frame to be painted when the time comes.
... animationframerequestid = session.requestanimationframe(mydrawfra
me); // get an xrviewerpose representing the position and // orientation of the viewer.
...And 4 more matches
core/heritage - Archive of obsolete content
reading or writing such code requires sharp eye and lot's of discipline, mainly due to code fragmentation and lots of machinery being exposed: // defining a simple class function dog(na
me) { // classes are for creating instances, calling them without `new` changes // behavior, which in majority cases you need to handle, so you end up // with additional boilerplate.
... if (!(this instanceof dog)) return new dog(na
me); this.name = name; }; // to define methods you need to make a dance with a special 'prototype' // property of the constructor function.
...ruff!' }; // subclassing a `dog` function pet(name, breed) { // once again we do our little dance if (!(this instanceof pet)) return new pet(name, breed); dog.call(this, na
me); this.breed = breed; } // to subclass, you need to make another special dance with special // 'prototype' properties.
...And 3 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
ref: bug 690370 available functions are (see prefcalls.js file for details): function getprefbranch() function pref(prefname, value) function defaultpref(prefname, value) function lockpref(prefname, value) function unlockpref(prefna
me) function getpref(prefna
me) function getldapattributes(host, base, filter, attribs) function getldapvalue(str, key) function displayerror(funcname, message) function getenv(na
me) configure autoconfig two directives ask thunderbird to use autoconfig at startup: # cat /usr/lib/thunderbird/defaults/pref/tb-autoconf.js // 20100526 - modification autoconfig jehan.
...in unix that would have been $home/nsmail/..., in windows it would have been a samba mount of that same unix path (ex: u:\nsmail ; with u: = samba mount: \\samba-server\%userna
me).
...that allows us first to encode (byte-shift) that file (netscape.cfg) -just once- because it will call a non-encoded javascript file config_file_system.jsc (or whatever na
me) on the web server.
...And 3 more matches
nsIDOMWindowUtils
oolean aflushlayout); void entermodalstate(); nsidomelement findelementwithviewid(in nsviewid aid); void focus(in nsidomelement aelement); void forceupdatenativemenuat(in astring indexstring); void garbagecollect([optional] in nsicyclecollectorlistener alistener); short getcursortype(); astring getdocumentmetadata(in astring ana
me); nsidomwindow getouterwindowwithid(in unsigned long long aouterwindowid); long getpccountscriptcount(); astring getpccountscriptsummary(in long ascript); astring getpccountscriptcontents(in long ascript); void getscrollxy(in boolean aflushlayout, out long ascrollx, out long ascrolly); astring getvisiteddependentcomputedstyle(in nsid...
...omelement aelement, in astring apseudoelement, in astring apropertyna
me); boolean isinmodalstate(); void leavemodalstate(); void loadsheet(in nsiuri sheeturi, in unsigned long type); nsidomnodelist nodesfromrect(in float ax, in float ay, in float atopsize, in float arightsize, in float abottomsize, in float aleftsize, in boolean aignorerootscrollframe, in boolean aflushlayout); void processupdates(); obsolete since gecko 13.0 void purgepccounts(); unsigned long redraw([optional] in unsigned long acount); void renderdocument(in nsconstrect arect, in pruint32 aflags, in nscolor abackgroundcolor, in gfxcontext athebescontext); native code only!
... apreventdefault); obsolete since gecko 15.0 boolean sendkeyevent(in astring atype, in long akeycode, in long acharcode, in long amodifiers, [optional] in unsigned long aadditionalflags); deprecated since gecko 38.0 void sendmouseevent(in astring atype, in float ax, in float ay, in long abutton, in long aclickcount, in long amodifiers, [optional] in boolean aignorerootscrollfra
me); void sendmouseeventtowindow(in astring atype, in float ax, in float ay, in long abutton, in long aclickcount, in long amodifiers, [optional] in boolean aignorerootscrollfra
me); void sendmousescrollevent(in astring atype, in float ax, in float ay, in long abutton, in long ascrollflags, in long adelta, in long amodifiers); obsolete since gecko 17.0 void sendwheelevent...
...And 3 more matches
Using IndexedDB - Web APIs
// the added records would be like: // key : 1 => value : "bill" // key : 2 => value : "donna" customerdata.foreach(function(customer) { objstore.add(customer.na
me); }); }; for more details about the key generator, please see "w3c key generators".
... console.log("name for ssn 444-44-4444 is " + request.result.na
me); }; that's a lot of code for a "simple" retrieval.
... here's how you can shorten it up a bit, assuming that you handle errors at the database level: db.transaction("customers").objectstore("customers").get("444-44-4444").onsuccess = function(event) { console.log("name for ssn 444-44-4444 is " + event.target.result.na
me); }; see how this works?
...And 3 more matches
Index - Archive of obsolete content
655 tamarin acceptance test template this is the test template for tamarin acceptance tests (placed in test/acceptance/feature_na
me): 656 actionscript performance tests performance tests for tamarin are located in the test/performance directory.
... 2107 -ms-ime-align css, css property, needsbrowsercompatibility, non-standard, reference, recipe:css-property the -ms-ime-align css property is a microsoft extension aligning the input method editor (i
me) candidate window box relative to the element on which the ime composition is active.
... 2138 :-moz-system-metric(mac-graphite-the
me) :-moz-system-metric, css, css:mozilla extensions, non-standard, reference, selector :-moz-system-metric(mac-graphite-the
me) will match an element if the user has chosen the "graphite" appearance in the "appearance" prefpane of the mac os x system preferences.
...And 2 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
note that when the data is available (a web page is loaded into the ifra
me) this will not affect the web page context because the iframe is not visible.
...to demonstrate how the callback mechanism is implemented, imagine the following html page loaded into the iframe as a result of a request (retrievedata method requested the html file in to be loaded in the ifra
me): <body onload="top.iframecallback(document);" > <mydata> this is the content that comes from the server </mydata> </body> note that when the page is loaded into the iframe, the onload event is fired and the parent.iframecallback function is called in the context of the parent document (the originator).
...cense block ***** */ //// /// calldevedge represents the inner-browsing function here // function calldevedge(loaddata,ele) { var x = new xmlremoterequest(); doc=x.getremotedocument(loaddata); document.getelementbyid("container").innerhtml=""; if(doc!=null) { tagname="article"; // ie fix if(document.all) tagname="nde:"+tagname; articles=doc.getelementsbytagname(tagna
me); for(i=0;i<articles.length;i++) { article=articles.item(i); tagname="title"; // ie fix if(document.all) tagname="nde:"+tagname; valuee=article.getelementsbytagname(tagna
me).item(0).firstchild.nodevalue; tagname="summary"; // ie fix if(document.all) tagname="nde:"+tagname; ...
...And 2 more matches
Space Manager Detailed Design - Archive of obsolete content
*/ class nsspacemanager { public: nsspacemanager(nsipresshell* apresshell, nsiframe* afra
me); ~nsspacemanager(); void* operator new(size_t asize); void operator delete(void* aptr, size_t asize); static void shutdown(); /* * get the frame that's associated with the space manager.
... * * returns ns_ok if successful and ns_error_invalid_arg if there is no region * tagged with aframe */ nsresult removeregion(nsiframe* afra
me); /** * clears the list of regions representing the unavailable space.
... pr_clist_is_empty((prcliststr*)this);} bandrect* head() const {return (bandrect*)pr_list_head(this);} bandrect* tail() const {return (bandrect*)pr_list_tail(this);} // operations void append(bandrect* abandrect) {pr_append_link(abandrect, this);} // remove and delete all the band rects in the list void clear(); }; frameinfo* getframeinfofor(nsiframe* afra
me); frameinfo* createframeinfo(nsiframe* aframe, const nsrect& arect); void destroyframeinfo(frameinfo*); void clearframeinfo(); void clearbandrects(); bandrect* getnextband(const bandrect* abandrect) const; void divideband(bandrect* aband, nscoord abottom); prbool canjoinbands(bandrect* aband, bandrect* aprevband); prbool joinbands(bandrect* aband,...
...And 2 more matches
Utilities for nss samples
d(pk11slotinfo *slot, int retry, void *pwdata); /* * generaterandom */ extern secstatus generaterandom(unsigned char *rbuf, int rsize); /* * filetoitem */ extern secstatus filetoitem(secitem *dst, prfiledesc *src); /* * seedfromnoisefile */ extern secstatus seedfromnoisefile(const char *noisefilena
me); /* * filesize */ extern long filesize(const char* filena
me); /* * readderfromfile */ extern secstatus readderfromfile(secitem *der, const char *infilename, prbool ascii); #endif /* _util_h */ util.c /* this source code form is subject to the terms of the mozilla public * license, v.
...fprintf(stderr, "no password file \"%s\" exists.\n", pwfile); port_free(phrases); return null; } nb = pr_read(fd, phrases, maxpwdfilesize); pr_close(fd); if (nb == 0) { fprintf(stderr,"password file contains no data\n"); port_free(phrases); return null; } if (slot) { tokenname = pk11_gettokenname(slot); if (tokenna
me) { tokenlen = port_strlen(tokenna
me); } } i = 0; do { int startphrase = i; int phraselen; /* handle the windows eol case */ while (phrases[i] != '\r' && phrases[i] != '\n' && i < nb) i++; /* terminate passphrase */ phrases[i++] = '\0'; /* clean up any eol before the start of the next passphrase */ whi...
...le ( (i<nb) && (phrases[i] == '\r' || phrases[i] == '\n')) { phrases[i++] = '\0'; } /* now analyze the current passphrase */ phrase = &phrases[startphrase]; if (!tokenna
me) break; if (port_strncmp(phrase, tokenname, tokenlen)) continue; phraselen = port_strlen(phrase); if (phraselen < (tokenlen+1)) continue; if (phrase[tokenlen] != ':') continue; phrase = &phrase[tokenlen+1]; break; } while (i<nb); phrase = port_strdup((char*)phrase); port_free(phrases); return phrase; } /* * getmodulepassword */ char* getmodulepassword(pk11slotinfo *slot, int retry, void *arg) { char prompt[255]; secupwdata *pwdata = (secupwdata *)arg; char *pw; if (pwdata == null) { ...
...And 2 more matches
NSS environment variables
3.12.3 nsrandfile string (file na
me) uses this file to seed the pseudo random number generator.
... 3.12.3 nss_debug_pkcs11_module string (module na
me) name the pkcs#11 module to be traced.
... 3.12.3 nss_output_file string (filena
me) output file path name for the pkcs #11 module logger.
...And 2 more matches
nsIAnnotationService
signed long adatalen, in autf8string amimetype, in long aflags, in unsigned short aexpiration); void setitemannotationbinary(in long long aitemid, in autf8string aname,[const, array, size_is(adatalen)] in octet adata, in unsigned long adatalen, in autf8string amimetype, in long aflags, in unsigned short aexpiration); nsivariant getpageannotation(in nsiuri auri, in autf8string ana
me); nsivariant getitemannotation(in long long aitemid, in autf8string ana
me); astring getpageannotationstring(in nsiuri auri, in autf8string ana
me); astring getitemannotationstring(in long long aitemid, in autf8string ana
me); long getpageannotationint32(in nsiuri auri, in autf8string ana
me); long getitemannotationint32(in long long aitemid, in autf8string...
... ana
me); long long getpageannotationint64(in nsiuri auri, in autf8string ana
me); long long getitemannotationint64(in long long aitemid, in autf8string ana
me); double getpageannotationdouble(in nsiuri auri, in autf8string ana
me); double getitemannotationdouble(in long long aitemid, in autf8string ana
me); void getpageannotationbinary(in nsiuri auri, in autf8string aname,[array, size_is(adatalen)] out octet adata, out unsigned long adatalen, out autf8string amimetype); void getitemannotationbinary(in long long aitemid, in autf8string aname,[array, size_is(adatalen)] out octet adata, out unsigned long adatalen, out autf8string amimetype); void getpageannotationinfo(in nsiuri auri, in autf8string aname, out print32 aflags, out unsigned...
... short aexpiration, out autf8string amimetype, out unsigned short atype); void getitemannotationinfo(in long long aitemid, in autf8string aname, out long aflags, out unsigned short aexpiration, out autf8string amimetype, out unsigned short atype); pruint16 getpageannotationtype(in nsiuri auri, in autf8string ana
me); pruint16 getitemannotationtype(in long long aitemid, in autf8string ana
me); void getpageswithannotation(in autf8string name, [optional] out unsigned long resultcount, [retval, array, size_is(resultcount)] out nsiuri results); void getitemswithannotation(in autf8string name, [optional] out unsigned long resultcount, [retval, array, size_is(resultcount)] out long long results); void getpageannotationnames(in nsiuri auri, [optiona...
...And 2 more matches
nsIMsgIdentity
inherits from: nsisupports method overview void clearallvalues(); void copy(in nsimsgidentity identity); astring getunicharattribute(in string na
me); void setunicharattribute(in string name, in astring value); acstring getcharattribute(in string na
me); void setcharattribute(in string name, in acstring value); boolean getboolattribute(in string na
me); void setboolattribute(in string name, in boolean value); long getintattribute(in string na
me); void setintattribute(in string name, ...
... astring getunicharattribute(in string na
me); parameters name setunicharattribute() setter for unicode attributes.
... acstring getcharattribute(in string na
me); parameters name name of the attribute to get.
...And 2 more matches
nsIAbCard/Thunderbird3
same as home, but with `work' instead of `home' other contact: faxnumber, faxnumbertype pagernumber, pagernumbertype cellularnumber, cellularnumbertype jobtitle, department, company _aimscreenname dates: anniversaryyear, anniversarymonth, anniversaryday birthyear, birthmonth, birthday webpage1 (work), webpage2 (ho
me) custom1, custom2, custom3, custom4 notes integral properties: lastmodifieddate popularityindex prefermailformat (see nsiabprefermailformat) boolean properties: allowremotecontent inherits from: nsiabitem method overview nsivariant getproperty(in autf8string name, in nsivariant defaultvalue); [noscript] astring getpropertyasastring(in string...
... na
me); [noscript] autf8string getpropertyasautf8string(in string na
me); [noscript] pruint32 getpropertyasuint32(in string na
me); [noscript] boolean getpropertyasbool(in string na
me); void setproperty(in autf8string name, in nsivariant value); [noscript] void setpropertyasastring(in string name, in astring value); [noscript] void setpropertyasautf8string(in string name, in autf8string value); [noscript] void setpropertyasuint32(in string name, in pruint32 value); [noscript] void setpropertyasbool(in string name, in boolean value); void deleteproperty(in autf8string na
me); autf8string translateto(in autf8string atype); void copy(in nsiabcard srccard) boolean equals(in nsiabcard card) ...
... getpropertyasastring() getpropertyasautf8string() getpropertyasuint32() getpropertyasbool() [noscript] astring getpropertyasastring(in string na
me); [noscript] autf8string getpropertyasautf8string(in string na
me); [noscript] pruint32 getpropertyasuint32(in string na
me); [noscript] boolean getpropertyasbool(in string na
me); returns a property for the given name.
...And 2 more matches
EventTarget.addEventListener() - Web APIs
my_element.addeventlistener('click', function (e) { console.log(this.classna
me) // logs the classname of my_element console.log(e.currenttarget === this) // logs `true` }) as a reminder, arrow functions do not have their own this context.
... my_element.addeventlistener('click', (e) => { console.log(this.classna
me) // warning: `this` is not `my_element` console.log(e.currenttarget === this) // logs `false` }) if an event handler (for example, onclick) is specified on an element in the html source, the javascript code in the attribute value is effectively wrapped in a handler function that binds the value of this in a manner consistent with the addeventlistener(); an occurrence of this within the code represents a reference to the element.
... this is an example with and without bind(): const something = function(element) { // |this| is a newly created object this.name = 'something good'; this.onclick1 = function(event) { console.log(this.na
me); // undefined, as |this| is the element }; this.onclick2 = function(event) { console.log(this.na
me); // 'something good', as |this| is bound to newly created object }; element.addeventlistener('click', this.onclick1, false); element.addeventlistener('click', this.onclick2.bind(this), false); // trick } const s = new something(document.body); another solution is using a special fun...
...And 2 more matches
Classes - JavaScript
// unnamed let rectangle = class { constructor(height, width) { this.height = height; this.width = width; } }; console.log(rectangle.na
me); // output: "rectangle" // named let rectangle = class rectangle2 { constructor(height, width) { this.height = height; this.width = width; } }; console.log(rectangle.na
me); // output: "rectangle2" note: class expressions are subject to the same hoisting restrictions as described in the class declarations section.
... class animal { constructor(na
me) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); } } class dog extends animal { constructor(na
me) { super(na
me); // call the super class constructor and pass in the name parameter } speak() { console.log(`${this.name} barks.`); } } let d = new dog('mitzie'); d.speak(); // mitzie barks.
... one may also extend traditional function-based "classes": function animal (na
me) { this.name = name; } animal.prototype.speak = function () { console.log(`${this.name} makes a noise.`); } class dog extends animal { speak() { console.log(`${this.name} barks.`); } } let d = new dog('mitzie'); d.speak(); // mitzie barks.
...And 2 more matches
Function.name - JavaScript
let f = function() {}; let object = { somemethod: function() {} }; console.log(f.na
me); // "f" console.log(object.somemethod.na
me); // "somemethod" you can define a function with a name in a function expression: let object = { somemethod: function object_somemethod() {} }; console.log(object.somemethod.na
me); // logs "object_somemethod" try { object_somemethod } catch(e) { console.log(e); } // referenceerror: object_somemethod is not defined the name property is read-only a...
... let object = { // anonymous somemethod: function() {} }; object.somemethod.name = 'othermethod'; console.log(object.somemethod.na
me); // somemethod to change it, use object.defineproperty().
...t foo(x){} }; var descriptor = object.getownpropertydescriptor(o, "foo"); descriptor.get.name; // "get foo" descriptor.set.name; // "set foo"; function names in classes you can use obj.constructor.name to check the "class" of an object (but be sure to read the warnings below): function foo() {} // es2015 syntax: class foo {} var fooinstance = new foo(); console.log(fooinstance.constructor.na
me); // logs "foo" warning: the script interpreter will set the built-in function.name property only if a function does not have an own property called name (see section 9.2.11 of the ecmascript2015 language specification).
...And 2 more matches
fill - SVG: Scalable Vector Graphics
value freeze (keep the state of the last animation fra
me) | remove (keep the state of the first animation fra
me) default value remove animatable no animatecolor warning: as of svg animation 2 <animatecolor> is deprecated and shouldn't be used.
... value freeze (keep the state of the last animation fra
me) | remove (keep the state of the first animation fra
me) default value remove animatable no animatemotion for <animatemotion>, fill defines the final state of the animation.
... value freeze (keep the state of the last animation fra
me) | remove (keep the state of the first animation fra
me) default value remove animatable no animatetransform for <animatetransform>, fill defines the final state of the animation.
...And 2 more matches
JavaScript Daemons Management - Archive of obsolete content
date.parse(vdate) : vdate; if (isfinite(nti
me) && ntime > date.now()) { this.reversals = math.floor((ntime - date.now() - (this.backw ?
... this.index : this.length - this.index) * this.rate) / (this.length * this.rate)); this.start(this.isatend() !== this.backw); } }; daemon.prototype.spread = function (nti
me) { if (!isfinite(this.length)) { throw new typeerror("daemon.prototype.spread - the length is not a finite number.
... use daemon.prototype.adaptlength()."); } if (ntime > 0) { this.rate = math.floor(ntime / this.length); this.synchronize(); } return this.rate; }; daemon.prototype.adaptlength = function (nti
me) { this.length = math.floor(ntime / this.rate); return this.length; }; daemon.prototype.playuntil = function (vdate) { var ntime = vdate.constructor === date ?
...date.parse(vdate) : vdate; if (isfinite(nti
me) && ntime > date.now()) { this.length = math.floor((ntime - date.now()) / this.rate) + this.index; this.pause(); this.start(); } return this.length; }; manual the constructor syntax var mydaemon = new daemon(thisobject, callback[, rate[, length[, init[, onstart]]]]); description constructs a javascript object containing all information needed by an animation (like the this object, the callback function, the length, the frame rate, the number of cycles, and the init and onstart functions).
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
you can use it to help debug firefox extensions as well as to inspect and learn how the firefox ui (chro
me) is constructed.
... listing 19: content for save method save: function(event) { event.stoppropagation(); var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); var state = ss.getbrowserstate(); var filename = "session_" + date.now() + ".js"; var file = this._dir.clone(); file.append(filena
me); this._writefile(file, state); }, restore method listing 20 shows the event handler for the dynamically generated menu items, which were created using the createmenu method (which we’ll get to shortly).
... listing 20: content for restore method restore: function(event) { var filename = event.target.getattribute("filename"); var file = this._dir.clone(); file.append(filena
me); var state = this._readfile(file); var ss = components.classes["@mozilla.org/browser/sessionstore;1"] .getservice(components.interfaces.nsisessionstore); ss.setwindowstate(window, state, false); }, clear method this uses the directoryentries property of the nslfile interface to delete all files within the directory you got earlier.
...h - 1; i >= 0; i--) { var node = menupopup.childnodes[i]; if (node.hasattribute("filename")) menupopup.removechild(node); } var fileenum = this._dir.directoryentries; while (fileenum.hasmoreelements()) { var file = fileenum.getnext().queryinterface(components.interfaces.nsifile); var re = new regexp("^session_(\\d+)\.js$"); if (!re.test(file.leafna
me)) continue; var datetime = new date(parseint(regexp.$1, 10)).tolocalestring(); var menuitem = document.createelement("menuitem"); menuitem.setattribute("label", dateti
me); menuitem.setattribute("filename", file.leafna
me); menupopup.insertbefore(menuitem, menupopup.firstchild.nextsibling.nextsibling); } }, operations check this completes the functional...
Using Dependent Libraries In Extension Components - Archive of obsolete content
static void* lookupsymbol(const mach_header* alib, const char* asymbolna
me); extern "c" ns_export nsresult nsgetmodule(nsicomponentmanager* acompmgr, nsifile* alocation, nsimodule* *aresult) { nsresult rv; // this is not the real component.
... nsaddimage(path.get(), nsaddimage_option_return_on_error | nsaddimage_option_with_searching | nsaddimage_option_match_filename_by_installna
me); // 1) we don't care if this failed!
... } library->setnativeleafname(ns_literal_cstring(krealcomponent)); rv = library->getnativepath(path); if (ns_failed(rv)) return rv; const mach_header * componentlib = nsaddimage(path.get(), nsaddimage_option_return_on_error | nsaddimage_option_with_searching | nsaddimage_option_match_filename_by_installna
me); if (componentlib == null) return ns_error_unexpected; //find the nsgetmodule procedure of the real component and “pass the buck”.
...static void* lookupsymbol(const mach_header* alib, const char* asymbolna
me) { nssymbol sym = nsnull; if (alib) { sym = nslookupsymbolinimage(alib, asymbolname, nslookupsymbolinimage_option_bind | nslookupsymbolinimage_option_return_on_error); } if (!sym) return nsnull; return nsaddressofsymbol(sym); } notes code samples are licensed under the mit license.
JXON - Archive of obsolete content
| oparentobj.constructor === boolean) { oparentel.appendchild(onewdoc.createtextnode(oparentobj.tostring())); /* verbosity level is 0 or 1 */ if (oparentobj === oparentobj.valueof()) { return; } } else if (oparentobj.constructor === date) { oparentel.appendchild(onewdoc.createtextnode(oparentobj.togmtstring())); } for (var sname in oparentobj) { if (isfinite(sna
me)) { continue; } /* verbosity level is 0 */ vvalue = oparentobj[sname]; if (sname === "keyvalue") { if (vvalue !== null && vvalue !== true) { oparentel.appendchild(onewdoc.createtextnode(vvalue.constructor === date ?
...name === "keyattributes") { /* verbosity level is 3 */ for (var sattrib in vvalue) { oparentel.setattribute(sattrib, vvalue[sattrib]); } } else if (sname.charat(0) === "@") { oparentel.setattribute(sname.slice(1), vvalue); } else if (vvalue.constructor === array) { for (var nitem = 0; nitem < vvalue.length; nitem++) { ochild = onewdoc.createelement(sna
me); loadobjtree(ochild, vvalue[nitem]); oparentel.appendchild(ochild); } } else { ochild = onewdoc.createelement(sna
me); if (vvalue instanceof object) { loadobjtree(ochild, vvalue); } else if (vvalue !== null && vvalue !== true) { ochild.appendchild(onewdoc.createtextnode(vvalue.tostring())); } oparentel.ap...
...n) { oparentel.appendchild(oxmldoc.createtextnode(oparentobj.tostring())); /* verbosity level is 0 or 1 */ if (oparentobj === oparentobj.valueof()) { return; } } else if (oparentobj.constructor === date) { oparentel.appendchild(oxmldoc.createtextnode(oparentobj.togmtstring())); } for (var sname in oparentobj) { vvalue = oparentobj[sname]; if (isfinite(sna
me) || vvalue instanceof function) { continue; } /* verbosity level is 0 */ if (sname === svalprop) { if (vvalue !== null && vvalue !== true) { oparentel.appendchild(oxmldoc.createtextnode(vvalue.constructor === date ?
...ame === sattrprop) { /* verbosity level is 3 */ for (var sattrib in vvalue) { oparentel.setattribute(sattrib, vvalue[sattrib]); } } else if (sname.charat(0) === sattrspref) { oparentel.setattribute(sname.slice(1), vvalue); } else if (vvalue.constructor === array) { for (var nitem = 0; nitem < vvalue.length; nitem++) { ochild = oxmldoc.createelement(sna
me); loadobjtree(oxmldoc, ochild, vvalue[nitem]); oparentel.appendchild(ochild); } } else { ochild = oxmldoc.createelement(sna
me); if (vvalue instanceof object) { loadobjtree(oxmldoc, ochild, vvalue); } else if (vvalue !== null && vvalue !== true) { ochild.appendchild(oxmldoc.createtextnode(vvalue.tostring())); } ...
calICalendarViewController - Archive of obsolete content
interface code [scriptable, uuid(1f783898-f4c2-4b2d-972e-360e0de38237)] interface calicalendarviewcontroller : nsisupports { void createnewevent (in calicalendar acalendar, in calidatetime astarttime, in calidatetime aendti
me); void modifyoccurrence (in caliitemoccurrence aoccurrence, in calidatetime anewstarttime, in calidatetime anewendti
me); void deleteoccurrence (in caliitemoccurrence aoccurrence); }; methods createnewevent void createnewevent (in calicalendar acalendar, in calidatetime astarttime, in calidatetime aendti
me); the createnewevent method is used for cre...
... modifyoccurrence void modifyoccurrence (in caliitemoccurrence aoccurrence, in calidatetime anewstarttime, in calidatetime anewendti
me); the modifyoccurrence method is used to change the attributes of an already existing caliitem.
...view calidecoratedview example code var myviewcontroller = { queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.calicalendarviewcontroller) && !aiid.equals(components.interfaces.nsisupports)) { throw components.results.ns_error_no_interface; } return this; }, createnewevent: function (acalendar, astarttime, aendti
me) { // if we're given both times, skip the dialog if (astarttime && aendtime && !astarttime.isdate && !aendtime.isdate) { var event = createevent(); event.startdate = astarttime; event.enddate = aendtime; event.title = "new event"; acalendar.additem(event, null); } else if (astarttime && astarttime.isdate) { ...
... var event = createevent(); event.startdate = astarttime; acalendar.additem(event, null); } else { createeventwithdialog(acalendar, astarttime, aendti
me); } }, modifyoccurrence: function (aoccurrence, anewstarttime, anewendti
me) { // if we can modify this thing directly (e.g.
React interactivity: Events and state - Learn web development
handling form submission via callbacks inside the top of our app() component function, create a function named addtask() which has a single parameter of name: function addtask(na
me) { alert(na
me); } next, we'll pass addtask() into <form /> as a prop.
...as a matter of good practice, you should clear the input after your form submits, so we'll call setname() again with an empty string to do so: function handlesubmit(e) { e.preventdefault(); props.addtask(na
me); setname(""); } at last, you can type something into the input field in your browser and click add — whatever you typed will appear in an alert dialog.
... your form.js file should now read like this: import react, { usestate } from "react"; function form(props) { const [name, setname] = usestate(""); function handlechange(e) { setname(e.target.value); } function handlesubmit(e) { e.preventdefault(); props.addtask(na
me); setname(""); } return ( <form onsubmit={handlesubmit}> <h2 classname="label-wrapper"> <label htmlfor="new-todo-input" classname="label__lg"> what needs to be done?
... putting that all together, your addtask() function should read like so: function addtask(na
me) { const newtask = { id: "id", name: name, completed: false }; settasks([...tasks, newtask]); } now you can use the browser to add a task to our data!
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
put the following contents inside it: <script> import { createeventdispatcher } from 'svelte' const dispatch = createeventdispatcher() let name = '' const addtodo = () => { dispatch('addtodo', na
me) name = '' } const oncancel = () => name = '' </script> <form on:submit|preventdefault={addtodo} on:keydown={e => e.key === 'escape' && oncancel()}> <h2 class="label-wrapper"> <label for="todo-0" class="label__lg">what needs to be done?</label> </h2> <input bind:value={name} type="text" id="todo-0" autocomplete="off" class="input input__lg" /> <button type="submit" disabled=...
... add the following import statement below the others inside todos.svelte: import newtodo from './newtodo.svelte' and update the addtodo() function like so: function addtodo(na
me) { todos = [...todos, { id: newtodoid, name, completed: false }] } addtodo() now receives the name of the new todo directly, so we no longer need the newtodoname variable to give it its value.
... update the contents of newtodo.svelte like so: <script> import { createeventdispatcher } from 'svelte' const dispatch = createeventdispatcher() let name = '' let nameel // reference to the name input dom node const addtodo = () => { dispatch('addtodo', na
me) name = '' nameel.focus() // give focus to the name input } const oncancel = () => { name = '' nameel.focus() // give focus to the name input } </script> <form on:submit|preventdefault={addtodo} on:keydown={e => e.key === 'escape' && oncancel()}> <h2 class="label-wrapper"> <label for="todo-0" class="label__lg">what needs to be done?</label> </...
...ree declarations are props, and the rest are exported values: <script> export let bar = 'optional default initial value' // prop export let baz = undefined // prop export let format = n => n.tofixed(2) // prop // these are readonly export const thisis = 'readonly' // read-only export export function greet(na
me) { // read-only export alert(`hello ${name}!`) } export const greet = (na
me) => alert(`hello ${name}!`) // read-only export </script> with this in mind, let's go back to our use case.
TraceMalloc
if you run with --trace-malloc -, your code can call ns_tracemallocdumpallocations(pathna
me) at opportune times, and a human-readable listing of the current heap, including stack traces for every allocation, will be written to pathname.
... tracemallocopenlogfile(filena
me) - open a new log file and return its log file descriptor (or -1 on error).
... tracemallocdumpallocations(pathna
me) - dump a human-readable listing of all traced, live allocations.
...<script type="text/javascript"> var filename = window.prompt("filename to log: "); if (filena
me) tracemallocdumpallocations(filena
me); </script> one can then use the script tools/trace-malloc/diffbloatdump.pl to compare trace-malloc dumps before and after doing an action that might leak.
NSS Sample Code Sample1
// // the servers must be started int comparekeys(server *peer); // create a server - the name distiguish the keys in the // shared database in this example server(const char *serverna
me); ~server(); private: int getprivatekey(seckeyprivatekey **prvkey); int getpublickey(seckeypublickey **pubkey); int wrapkey(pk11symkey *key, seckeypublickey *pubkey, secitem **data); // export raw key (unwrapped) do not use int rawexportkey(pk11symkey *key, secitem **data); char *mservername; // these items represent data that might be stored // in files or in a configuration...
... file secitem *mwrappedenckey; secitem *mwrappedmackey; // these are the runtime keys as loaded from the files pk11symkey *menckey; pk11symkey *mmackey; }; server::server(const char *serverna
me) : mservername(0), mwrappedenckey(0), mwrappedmackey(0), menckey(0), mmackey(0) { // copy the server name mservername = pl_strdup(serverna
me); } server::~server() { if (mserverna
me) pl_strfree(mserverna
me); if (mwrappedenckey) secitem_freeitem(mwrappedenckey, pr_true); if (mwrappedmackey) secitem_freeitem(mwrappedmackey, pr_true); if (menckey) pk11_freesymkey(menckey); if (mmackey) pk11_freesymkey(mmackey); } int server::init() { int rv = 0; seckeyprivatekey *prvkey = 0; seckeypublickey *pubkey = 0; pk11slotinfo *slot = 0; pk11rsagenparams rsaparams; secstatus ...
... s = pk11_setprivatekeynickname(prvkey, mserverna
me); if (s != secsuccess) { rv = 1; goto done; } done: if (slot) pk11_freeslot(slot); if (pubkey) seckey_destroypublickey(pubkey); if (prvkey) seckey_destroyprivatekey(prvkey); return rv; } int server::generatekeys() { int rv = 0; seckeypublickey *pubkey = 0; pk11slotinfo *slot = 0; // choose a slot to use slot = pk11_getinternalkeyslot(); if (!slot) { rv = 1; goto done; } ...
... // bug: xxxxx list = pk11_listprivkeysinslot(slot, mservername, 0); cout << "getprivatekey: list = " << list << endl; if (!list) { rv = 1; goto done; } for(n = privkey_list_head(list); !privkey_list_end(n, list); n = privkey_list_next(n)) { nickname = pk11_getprivatekeynickname(n->key); if (pl_strcmp(nickname, mserverna
me) == 0) break; } if (privkey_list_end(n, list)) { rv = 1; goto done; } *prvkey = seckey_copyprivatekey(n->key); done: if (list) seckey_destroyprivatekeylist(list); return rv; } int server::getpublickey(seckeypublickey **pubkey) { int rv; seckeyprivatekey *prvkey = 0; rv = getprivatekey(&prvkey); if (rv) goto done; *pubkey = seckey_converttopublickey(prvkey); if (!*pubkey...
NSS Sample Code Sample_1_Hashing
* returns null if the name is not a supported algorithm */ static secoidtag hashnametooidtag(const char *hashna
me) { int i, nhashes = sizeof(hash_names); secoidtag hashtag = sec_oid_unknown; for (i = 0; i < nhashes; i++) { if (port_strcasecmp(hashname, hash_names[i].hashna
me) == 0) { hashtag = hash_names[i].oid; break; } } return hashtag; } /* * newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printashex */ void ...
... } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* * prints a usage message and exits */ static void usage(const char *progna
me) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progna
me); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < hash_algtotal; htype++) { fprintf(stderr, hash_names[htype].hashn...
...a
me); if (htype == (hash_algtotal - 2)) fprintf(stderr, " or "); else if (htype != (hash_algtotal - 1)) fprintf(stderr, ", "); } fprintf(stderr, " (case ignored))\n"); fprintf(stderr, "%-20s define an input file to use (default is stdin)\n", "< input"); fprintf(stderr, "%-20s define an output file to use (default is stdout)\n", "> output"); exit(-1); } /* * check for the missing arguments */ static void printmsgandexit(const char *progname, char opt) { fprintf(stderr, "%s: option -%c requires an argument\n", progname, opt); usage(progna
me); } #define require_arg(opt,value) if (!(value)) printmsgandexit(progname, opt) /* * digests a file according to the specified algorithm.
.../tmp"); return -1; } /* parse command line arguments */ optstate = pl_createoptstate(argc, argv, "t:"); while ((status = pl_getnextopt(optstate)) == pl_opt_ok) { switch (optstate->option) { case 't': require_arg(optstate->option, optstate->value); hashname = strdup(optstate->value); break; } } if (!hashna
me) usage(progna
me); /* convert and validate */ hashoidtag = hashnametooidtag(hashna
me); if (hashoidtag == sec_oid_unknown) { fprintf(stderr, "%s: invalid digest type - %s\n", progname, hashna
me); usage(progna
me); } /* digest it and print the result */ rv = digestfile(pr_stdout, pr_stdin, hashoidtag); if (rv != secsuccess) { fprintf(stderr...
Hashing - sample 1
* returns null if the name if not a supported algorithm */ static secoidtag hashnametooidtag(const char *hashna
me) { int i, nhashes = sizeof(hash_names); secoidtag hashtag = sec_oid_unknown; for (i = 0; i < nhashes; i++) { if (port_strcasecmp(hashname, hash_names[i].hashna
me) == 0) { hashtag = hash_names[i].oid; break; } } return hashtag; } /* * newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printashex */ v...
... } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* * prints a usage message and exits */ static void usage(const char *progna
me) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progna
me); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < hash_algtotal; htype++) { fprintf(stderr, hash_names[htype].hashn...
...a
me); if (htype == (hash_algtotal - 2)) fprintf(stderr, " or "); else if (htype != (hash_algtotal - 1)) fprintf(stderr, ", "); } fprintf(stderr, " (case ignored))\n"); fprintf(stderr, "%-20s define an input file to use (default is stdin)\n", "< input"); fprintf(stderr, "%-20s define an output file to use (default is stdout)\n", "> output"); exit(-1); } /* * check for the missing arguments */ static void printmsgandexit(const char *progname, char opt) { fprintf(stderr, "%s: option -%c requires an argument\n", progname, opt); usage(progna
me); } #define require_arg(opt,value) if (!(value)) printmsgandexit(progname, opt) /* * digests a file according to the specified algorithm.
.../tmp"); return -1; } /* parse command line arguments */ optstate = pl_createoptstate(argc, argv, "t:"); while ((status = pl_getnextopt(optstate)) == pl_opt_ok) { switch (optstate->option) { case 't': require_arg(optstate->option, optstate->value); hashname = strdup(optstate->value); break; } } if (!hashna
me) usage(progna
me); /* convert and validate */ hashoidtag = hashnametooidtag(hashna
me); if (hashoidtag == sec_oid_unknown) { fprintf(stderr, "%s: invalid digest type - %s\n", progname, hashna
me); usage(progna
me); } /* digest it and print the result */ rv = digestfile(pr_stdout, pr_stdin, hashoidtag); if (rv != secsuccess) { fprintf(stderr...
sample1
* returns null if the name is not a supported algorithm */ static secoidtag hashnametooidtag(const char *hashna
me) { int i, nhashes = sizeof(hash_names); secoidtag hashtag = sec_oid_unknown; for (i = 0; i < nhashes; i++) { if (port_strcasecmp(hashname, hash_names[i].hashna
me) == 0) { hashtag = hash_names[i].oid; break; } } return hashtag; } /* newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* ...
...{ pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* prints a usage message and exits */ static void usage(const char *progna
me) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progna
me); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (htype = 0; htype < hash_algtotal; htype++) { fprintf(stderr, hash_names[ht...
...ype].hashna
me); if (htype == (hash_algtotal - 2)) fprintf(stderr, " or "); else if (htype != (hash_algtotal - 1)) fprintf(stderr, ", "); } fprintf(stderr, " (case ignored))\n"); fprintf(stderr, "%-20s define an input file to use (default is stdin)\n", "< input"); fprintf(stderr, "%-20s define an output file to use (default is stdout)\n", "> output"); exit(-1); } /* check for the missing arguments */ static void printmsgandexit(const char *progname, char opt) { fprintf(stderr, "%s: option -%c requires an argument\n", progname, opt); usage(progna
me); } #define require_arg(opt,value) if (!(value)) printmsgandexit(progname, opt) /* digests a file according to the specified algo...
... return -1; } /* parse command line arguments */ optstate = pl_createoptstate(argc, argv, "t:"); while ((status = pl_getnextopt(optstate)) == pl_opt_ok) { switch (optstate->option) { case 't': require_arg(optstate->option, optstate->value); hashname = strdup(optstate->value); break; } } if (!hashna
me) usage(progna
me); /* convert and validate */ hashoidtag = hashnametooidtag(hashna
me); if (hashoidtag == sec_oid_unknown) { fprintf(stderr, "%s: invalid digest type - %s\n", progname, hashna
me); usage(progna
me); } /* digest it and print the result */ rv = digestfile(pr_stdout, pr_stdin, hashoidtag); if (rv != secsuccess) { f...
Rhino shell
defineclass(classna
me) define an extension using the java class named with the string argument classname.
... deserialize(filena
me) restore from the specified file an object previously written by a call to serialize.
... loadclass(classna
me) load and execute the class named by the string argument classname.
... serialize(object, filena
me) serialize the given object to the specified file.
Animated PNG graphics
if the default image is the first frame: sequence number chunk (none) 'actl' 0 'fctl' (first fra
me) (none) 'idat' (first frame -- used as the default image) 1 'fctl' (second fra
me) 2 'fdat' (first 'fdat' for second fra
me) 3 'fdat' (second 'fdat' for second fra
me) ...
... if the default image is not part of the animation: sequence number chunk (none) 'actl' (none) 'idat' (default image) 0 'fctl' (first fra
me) 1 first 'fdat' for first frame 2 second 'fdat' for first frame ...
... for the first frame excluding the default image (which may be either the first or second fra
me), the 'fctl' chunk must appear after all 'idat' chunks and before the 'fdat' chunks for the frame.
... dispose_op specifies how the output buffer should be changed at the end of the delay (before rendering the next fra
me).
nsIDBFolderInfo
delta); boolean getbooleanproperty(in string propertyname, in boolean defaultvalue); void getcharacterset(out acstring charset, out boolean overriden); void getcharactersetoverride(out boolean charactersetoverride); obsolete since gecko 1.8 string getcharptrcharacterset(); string getcharptrproperty(in string propertyna
me); void getlocale(in nsstring result); native code only!
... obsolete since gecko 1.8 void getmailboxname(in nsstring boxna
me); native code only!
... obsolete since gecko 1.8 astring getproperty(in string propertyna
me); nsidbfolderinfo gettransferinfo(); unsigned long getuint32property(in string propertyname, in unsigned long defaultvalue); void initfromtransferinfo(in nsidbfolderinfo transferinfo); long orflags(in long flags); void setbooleanproperty(in string propertyname, in boolean apropertyvalue); void setcharacterset(in string charset); void setcharactersetoverride(in boolean charactersetoverride); obsolete since gecko 1.8 void setcharptrproperty(in string apropertyname, in string apropertyvalue); void sethighwater(in nsmsgkey highwater, in boolean force); voi...
...obsolete since gecko 1.8 void setmailboxname(in nsstring newboxna
me); native code only!
nsIMsgDBHdr
method overview astring getproperty(in string propertyna
me); void setproperty(in string propertyname, in astring propertystr); void setstringproperty(in string propertyname, in string propertyvalue); string getstringproperty(in string propertyna
me); unsigned long getuint32property(in string propertyna
me); void setuint32property(in string propertyname, in unsigned long propertyval); void markread(in boo...
...(new in 3.1?) methods getproperty() astring getproperty(in string propertyna
me); parameters propertyname the name of the property to retrieve.
... getstringproperty() string getstringproperty(in string propertyna
me); parameters propertyname the name of the property to retrieve.
... unsigned long getuint32property(in string propertyna
me); parameters propertyname the name of the property to retrieve.
DevTools API - Firefox Developer Tools
unregistertheme(the
me) unregisters the given theme.
... theme-unregistered(the
me) a theme has been unregistered.
... {toolid}-init(toolbox, ifra
me) a tool with the given id has began to load in the given toolbox to the given frame.
... {toolid}-init(fra
me) a tool is about to be loaded.
Recommended Drag Types - Web APIs
event)" ondragover="return checkdrag(event)" ondrop="dodrop(event)"/> <script> function checkdrag(event) { return event.datatransfer.types.contains("application/x-moz-file"); } function dodrop(event) { var file = event.datatransfer.mozgetdataat("application/x-moz-file", 0); if (file instanceof components.interfaces.nsifile) { event.currenttarget.appenditem(file.leafna
me); } } </script> in this example, the event returns false only if the data transfer contains the application/x-moz-file type.
...the following sample offers an overview of this advanced case: // currentevent is an existing drag operation event currentevent.datatransfer.setdata("text/x-moz-url", url); currentevent.datatransfer.setdata("application/x-moz-file-promise-url", url); currentevent.datatransfer.setdata("application/x-moz-file-promise-dest-filename", leafna
me); currentevent.datatransfer.mozsetdataat('application/x-moz-file-promise', new dataprovider(success,error), 0, components.interfaces.nsisupports); function dataprovider(){} dataprovider.prototype = { queryinterface : function(iid) { if (iid.equals(components.interfaces.nsiflavordataprovider) || iid.equals(components.interfaces.nsisuppor...
...interface(components.interfaces.nsisupportsstring).data; console.log("url file orignal is = " + url); var nameprimitive = {}; atransferable.gettransferdata('application/x-moz-file-promise-dest-filename', nameprimitive, datasize); var name = nameprimitive.value.queryinterface(components.interfaces.nsisupportsstring).data; console.log("target filename is = " + na
me); var dirprimitive = {}; atransferable.gettransferdata('application/x-moz-file-promise-dir', dirprimitive, datasize); var dir = dirprimitive.value.queryinterface(components.interfaces.nsilocalfile); console.log("target folder is = " + dir.path); var file = cc['@mozilla.org/file/local;1'].createinstance(components.interfaces.nsilocalfile); file.initwithp...
...ath(dir.path); file.appendrelativepath(na
me); console.log("output final path is =" + file.path); // now you can write or copy the file yourself… } } } see also html drag and drop api (overview) drag operations dragging and dropping multiple items html5 living standard: drag and drop ...
Movement, orientation, and motion: A WebXR example - Web APIs
= "viewer"; } mat4.fromtranslation(cubematrix, viewerstartposition); vec3.copy(cubeorientation, viewerstartorientation); xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, cubeorientation)); animationframerequestid = xrsession.requestanimationframe(drawfra
me); }); return xrsession; } after storing the newly-created xrsession object into xrsession, the label of the button is set to "exit webxr" to indicate its new function after starting the scene, and a handler is installed for the end event, so we get notified when the xrsession ends.
... let lastframetime = 0; function drawframe(time, fra
me) { let session = frame.session; let adjustedrefspace = xrreferencespace; let pose = null; animationframerequestid = session.requestanimationframe(drawfra
me); adjustedrefspace = applyviewercontrols(xrreferencespace); pose = frame.getviewerpose(adjustedrefspace); if (pose) { let gllayer = session.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer);...
... logglerror("bindframebuffer"); gl.clearcolor(0, 0, 0, 1.0); gl.cleardepth(1.0); // clear everything gl.clear(gl.color_buffer_bit | gl.depth_buffer_bit); logglerror("glclear"); const deltatime = (time - lastframeti
me) * 0.001; // convert to seconds lastframetime = time; for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); logglerror(`setting viewport for eye: ${view.eye}`); gl.canvas.width = viewport.width * pose.views.length; gl.canvas.height = viewport.height; drawscene(gl, view, programinfo, buffers, texture, deltati
me); } } } the first thing we do is call requestanimationframe() to request that drawframe() ...
... const normalmatrix = mat4.create(); const modelviewmatrix = mat4.create(); function renderscene(gl, view, programinfo, buffers, texture, deltati
me) { const xrotationfortime = (xrotationdegreespersecond * radians_per_degree) * deltatime; const yrotationfortime = (yrotationdegreespersecond * radians_per_degree) * deltatime; const zrotationfortime = (zrotationdegreespersecond * radians_per_degree) * deltatime; gl.enable(gl.depth_test); // enable depth testing gl.depthfunc(gl.lequal); // near things obscure far th...
XRSession.requestAnimationFrame() - Web APIs
// obtain xr object const xr = navigator.xr // request a new xrsession xr.requestsession("inline").then((xrsession) => { xrsession.requestanimationframe((time, xrfra
me) => { let viewer = xrframe.getviewerpose(xrreferencespace) gl.bindframebuffer(xrwebgllayer.framebuffer) for (xrview of viewer.views) { let xrviewport = xrwebgllayer.getviewport(xrview) gl.viewport(xrviewport.x, xrviewport.y, xrviewport.width, xrviewport.height) // webgl draw calls will now be rendered into the appropriate viewport.
... let xrsession = null function onwindowanimationframe(ti
me) { window.requestanimationframe(onwindowanimationfra
me) // this may be called while an immersive session is running on some devices, // such as a desktop with a tethered headset.
...window.requestanimationframe(onwindowanimationfra
me) function onxranimationframe(time, xrfra
me) { xrsession.requestanimationframe(onxranimationfra
me) renderframe(time, xrfra
me) } function renderframe(time, xrfra
me) { // shared rendering logic.
... xrsession.requestanimationframe(onxranimationfra
me) }) } function onxrsessionended() { xrsession = null } specifications specification status comment webxr device apithe definition of 'xrsession.requestanimationframe' in that specification.
Functions - JavaScript
var pet = function(na
me) { // the outer function defines a variable called "name" var getname = function() { return name; // the inner function has access to the "name" variable of the outer //function } return getname; // return the inner function, thereby exposing it to outer scopes } mypet = pet('vivie'); mypet(); // returns "vivie" ...
... var createpet = function(na
me) { var sex; return { setname: function(newna
me) { name = newname; }, getname: function() { return name; }, getsex: function() { return sex; }, setsex: function(newsex) { if(typeof newsex === 'string' && (newsex.tolowercase() === 'male' || newsex.tolowercase() === 'female')) { sex = newsex; } } } } var pet = createpet('vivie'); pet.getname(); // vivie pet.setname('oliver'); pet.setsex('male'); pet.getsex(); // male pet.getname(); // oliver in the code above, the name va...
... (the inner scope variable "overrides" the outer one, until the program exits the inner scope.) var createpet = function(na
me) { // the outer function defines a variable called "name".
... return { setname: function(na
me) { // the enclosed function also defines a variable called "name".
constructor - JavaScript
class person { constructor(na
me) { this.name = name; } introduce() { console.log(`hello, my name is ${this.name}`); } } const otto = new person('otto'); otto.introduce(); if you don't provide your own constructor, then a default constructor will be supplied for you.
...y arguments that were provided: constructor(...args) { super(...args); } that enables code like this to work: class validationerror extends error { printcustomermessage() { return `validation failed :-( (details: ${this.message})`; } } try { throw new validationerror("not a valid phone number"); } catch (error) { if (error instanceof validationerror) { console.log(error.na
me); // this is error instead of validationerror!
...uctor(message) { super(message); // call parent class constructor this.name = 'validationerror'; this.code = '42'; } printcustomermessage() { return `validation failed :-( (details: ${this.message}, code: ${this.code})`; } } try { throw new validationerror("not a valid phone number"); } catch (error) { if (error instanceof validationerror) { console.log(error.na
me); // now this is validationerror!
..."; } } class square extends polygon { constructor() { super(); } } class rectangle {} object.setprototypeof(square.prototype, rectangle.prototype); console.log(object.getprototypeof(square.prototype) === polygon.prototype); //false console.log(object.getprototypeof(square.prototype) === rectangle.prototype); //true let newinstance = new square(); console.log(newinstance.na
me); //polygon specifications specification ecmascript (ecma-262)the definition of 'constructor method' in that specification.
InternalError: too much recursion - JavaScript
message error: out of stack space (edge) internalerror: too much recursion (firefox) rangeerror: maximum call stack size exceeded (chro
me) error type internalerror.
... function loop(x) { // the base case is missing loop(x + 1); // recursive call } loop(0); // internalerror: too much recursion class error: too much recursion class person{ constructor(){} set name(na
me){ this.name = name; // recursive call } } const tony = new person(); tony.name = "tonisha"; // internalerror: too much recursion when a value is assigned to the property name (this.name = name;) javascript needs to set that property.
... set name(na
me){ this.name = name; // recursive call } in this example when the setter is triggered, it is told to do the same thing again: to set the same property that it is meant to handle.
... class person{ constructor(){} set name(na
me){ this._name = name; } get name(){ return this._name; } } const tony = new person(); tony.name = "tonisha"; console.log(tony); ...
context-menu - Archive of obsolete content
ments can't contain other elements, but in the example below, node.nodename is not guaranteed to be "p" - for example, it won't be "p" if the user context-clicked a link inside a paragraph: var cm = require("sdk/context-menu"); cm.item({ label: "a paragraph", context: cm.selectorcontext("p"), contentscript: 'self.on("context", function (node) {' + ' console.log(node.nodena
me);' + ' return true;' + '});' }); the content script is executed for every page that a context menu is shown for.
... for example, suppose your add-on looks like this: var script = "self.on('click', function (node, data) {" + " console.log('clicked: ' + node.nodena
me);" + "});"; var cm = require("sdk/context-menu"); cm.item({ label: "body context", context: cm.selectorcontext("body"), contentscript: script }); this add-on creates a context-menu item that uses selectorcontext to display the item whenever the context menu is activated on any descendant of the <body> element.
... if you run this add-on you'll see that it always logs "body", even if you click on a paragraph element inside the page: info: contextmenu-example: clicked: body by contrast, this add-on uses the pagecontext: var script = "self.on('click', function (node, data) {" + " console.log('clicked: ' + node.nodena
me);" + "});"; var cm = require("sdk/context-menu"); cm.item({ label: "body context", context: cm.pagecontext(), contentscript: script }); it will log the name of the actual node clicked: info: contextmenu-example: clicked: p the "data" argument data is the data property of the menu item that was clicked.
passwords - Archive of obsolete content
so if you pass in an empty set of properties, all stored credentials are returned: function show_all_passwords() { require("sdk/passwords").search({ oncomplete: function oncomplete(credentials) { credentials.foreach(function(credential) { console.log(credential.userna
me); console.log(credential.password); }); } }); } if you pass it a single property, only credentials matching that property are returned: function show_passwords_for_joe() { require("sdk/passwords").search({ username: "joe", oncomplete: function oncomplete(credentials) { credentials.foreach(function(credential) { console.log(credential.userna
me);...
...al.password); }); } }); } if you pass more than one property, returned credentials must match all of them: function show_google_password_for_joe() { require("sdk/passwords").search({ username: "joe", url: "https://www.google.com", oncomplete: function oncomplete(credentials) { credentials.foreach(function(credential) { console.log(credential.userna
me); console.log(credential.password); }); } }); } to retrieve only credentials associated with your add-on, use the url property, initialized from self.uri: function show_my_addon_passwords() { require("sdk/passwords").search({ url: require("sdk/self").uri, oncomplete: function oncomplete(credentials) { credentials.foreach(function(credential) { ...
...console.log(credential.userna
me); console.log(credential.password); }); } }); } parameters options : object required options: name type oncomplete function the callback function that is called once the function completes successfully.
url - Archive of obsolete content
for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.sche
me); // https userpass the username:password part of the url, null if not present.
...for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.hostna
me); // developer.mozilla.org pathname an initial '/' followed by the path of the url, as a string.
...for example: var url = require("sdk/url").url("https://developer.mozilla.org/add-ons?example=true&visible=yes#top"); console.log(url.pathna
me); // /add-ons hash a '#' followed by the fragment identifier of the url, as a string.
lang/functional - Archive of obsolete content
let { compose } = require("sdk/lang/functional"); let welcome = compose(exclaim, greet); welcome('moe'); // "hi: moe!"; function greet (na
me) { return "hi: " + name; } function exclaim (statement) { return statement + "!"; } parameters fn...
... let { wrap } = require("sdk/lang/functional"); let wrappedhello = wrap(hello, function (fn, na
me) { return "before, " + fn(na
me) + "after"; }); wrappedhello("moe"); // "before, hello: moe, after" function hello (na
me) { return "hello: " + name; } parameters fn : function the function to be passed into the wrapper function.
...our hash // function will just parse the last name, as our naive // implementation assumes that they will share the same lineage let getlineage = memoize(function (na
me) { // computes lineage return data; }, hasher); // hashing function takes a string of first and last name // and returns the last name.
Creating Event Targets - Archive of obsolete content
ils } = require("resource://gre/modules/xpcomutils.jsm"); var bookmarkservice = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); var bookmarkobserver = { onitemadded: function(aitemid, afolder, aindex) { console.log("added ", bookmarkservice.getbookmarkuri(aitemid).spec); }, onitemvisited: function(aitemid, avisitid, ti
me) { console.log("visited ", bookmarkservice.getbookmarkuri(aitemid).spec); }, queryinterface: xpcomutils.generateqi([ci.nsinavbookmarkobserver]) }; exports.main = function() { bookmarkservice.addobserver(bookmarkobserver, false); }; exports.onunload = function() { bookmarkservice.removeobserver(bookmarkobserver); } try running this add-on, adding and visiting bookmarks, and observin...
...ils }= require("resource://gre/modules/xpcomutils.jsm"); var bookmarkservice = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); var bookmarkobserver = { onitemadded: function(aitemid, afolder, aindex) { emit(exports, "added", bookmarkservice.getbookmarkuri(aitemid).spec); }, onitemvisited: function(aitemid, avisitid, ti
me) { emit(exports, "visited", bookmarkservice.getbookmarkuri(aitemid).spec); }, queryinterface: xpcomutils.generateqi([ci.nsinavbookmarkobserver]) }; bookmarkservice.addobserver(bookmarkobserver, false); exports.on = on.bind(null, exports); exports.once = once.bind(null, exports); exports.removelistener = function removelistener(type, listener) { off(exports, type, listener); }; this c...
...s.jsm"); var bookmarkservice = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); function createobserver(target) { var bookmarkobserver = { onitemadded: function(aitemid, afolder, aindex) { emit(target, "added", bookmarkservice.getbookmarkuri(aitemid).spec); }, onitemvisited: function(aitemid, avisitid, ti
me) { emit(target, "visited", bookmarkservice.getbookmarkuri(aitemid).spec); }, queryinterface: xpcomutils.generateqi([ci.nsinavbookmarkobserver]) }; bookmarkservice.addobserver(bookmarkobserver, false); } var bookmarkmanager = class({ extends: eventtarget, initialize: function initialize(options) { eventtarget.prototype.initialize.call(this, options); merge(this, ...
HTML to DOM - Archive of obsolete content
ody), you have all document object with its complete functions list, therefore you can retrieve info within div tag like this: var dompars = htmlparser("<div id='userinfo'>john was a mediocre programmer, but people liked him <strong>anyway</strong>.</div>"); alert(dompars.getelementbyid('userinfo').innerhtml); to parse a complete html page, load it into an iframe whose type is content (not chro
me).
... var frame = document.getelementbyid("sample-frame"); if (!fra
me) { // create frame frame = document.createelement("iframe"); // iframe (or browser on older firefox) frame.setattribute("id", "sample-frame"); frame.setattribute("name", "sample-frame"); frame.setattribute("type", "content"); frame.setattribute("collapsed", "true"); document.getelementbyid("main-window").appendchild(fra
me); // or // document.documentelement.appendchild(fra
me); ...
...nk" || doc.defaultview.frameelement) return; // do something with the dom of doc alert(doc.location.href); // when done remove frame or set location "about:blank" settimeout(function (){ var frame = document.getelementbyid("sample-frame"); // remove frame // frame.destroy(); // if using browser element instead of iframe frame.parentnode.removechild(fra
me); // or set location "about:blank" // frame.contentdocument.location.href = "about:blank"; },10); }, true); } // load a page frame.contentdocument.location.href = "http://www.mozilla.org/"; // or // frame.webnavigation.loaduri("http://www.mozilla.org/",components.interfaces.nsiwebnavigation,null,null,null); if you are starting with an html string, you can convert it to a...
Preferences - Archive of obsolete content
use this when the preference value may contain non-ascii characters (for example, a user's na
me).
... var prefservice = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice); this._branch = prefservice.getbranch(branch_na
me); this._branch.queryinterface(components.interfaces.nsiprefbranch2); this._callback = callback; } preflistener.prototype.observe = function(subject, topic, data) { if (topic == 'nspref:changed') this._callback(this._branch, data); }; /** * @param {boolean=} trigger if true triggers the registered function * on registration, that is, when this method is called.
... foreach(function (pref_leaf_na
me) { that._callback(that._branch, pref_leaf_na
me); }); } }; preflistener.prototype.unregister = function() { if (this._branch) this._branch.removeobserver('', this); }; var mylistener = new preflistener( "extensions.myextension.", function(branch, na
me) { switch (na
me) { case "pref1": // extensions.myextension.pref1 was changed break; case "pref2": // extensions.myextension.pref2 was changed break; } } ); mylistener.register(true); note: you need to keep a reference to the preference branch you are ob...
xml:base support in old browsers - Archive of obsolete content
var scheme = /(\w(\w|\d|\+|\- |\ .)*)\:\/\//; function getxmlbaselink (xlink, thisitem) { var xmlbase = ''; if (!xlink.match(sche
me)) { // only check for xml base if there is no protocol // tests for 'scheme' per http://www.ietf.org/rfc/rfc2396.txt' xmlbase = getxmlbase (thisitem); if (!xmlbase.match(/\/$/) && !xlink.match(/\/$/)) { // if no preceding slash on xlink or trailing slash on xml:base, add one in between xmlbase += '/'; } else if (xmlbase.match(/\/$/) && xlink.match(/\/$/)) { xmlbase = xmlbase.substrin...
...g(0, xmlbase.length-2); // strip off last slash to join with xlink path with slash } // alert(xmlbase + '::' + xlink); } var link = xmlbase + xlink; if (!link.match(sche
me)) { // if there is no domain, we'll need to use the current domain var loc = window.location; if (link.indexof('/') === 0 ) { // if link is an absolute url, it should be from the host only link = loc.protocol + '//' + loc.host + link; } else { // if link is relative, it should be from full path, minus the file var dirpath = loc.pathname.substring(0, loc.pathname.lastindexof('/')-1); if (link.lastindexof('/') !== link.length-1) { link += '/'; } link = loc.protocol + '//' + loc.host + dirpath + link; } } return link; } function getxmlbase (thisitem) { // fix: need ...
... // var ns = 'http://www.w3.org/xml/1998/namespace'; var att, protocolpos; var xmlbase = ''; var abs = false; // avoid loop if node is not present if (!thisitem || !thisitem.nodena
me) { return xmlbase; } // check present element and higher up for xml:base // now check for the next matching local name up in the hierarchy (until the document root) while (thisitem.nodename !== '#document' && thisitem.nodename !== '#document-fragment') { att = thisitem.getattribute('xml:base'); // xml: namespaces must use 'xml' prefix if (att) { protocolpos = att.indexof('//'); var protocolmatch = att.match(sche
me); if (protocolmatch) { // if has protocol, can stop if (abs) { var skipfile = (att.indexof('///') === protocolpo...
Style System Overview - Archive of obsolete content
cssstyleruleimpl ↓ ↓ ↓ ↓ h1 nscssdeclaration h2 ↙ ↘ nscsscolor — color: green nscsstext — text-align: right text-indent: 0 css style rule representation problem: the rule structures use too much memory (a few hundred kilobytes for all our chro
me), and require large numbers of allocations to construct.
... reresolvestylecontext is messy because it needs to create and parent style contexts correctly (sibling sharing may not be the sa
me) rather than just changing data.
...we could at least do what we do for sheet addition/removal, or slightly better, by searching the rule tree (only one rule this ti
me) instead of rebuilding it.
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
string getresponseheader(string headerna
me) returns the value of the specified header.
... variant getparameter(string namespaceuri, string localna
me) gets the value of a parameter in the imported xslt stylesheet.
... void removeparameter(string namespaceuri, string localna
me) removes all set parameters from the imported xslt stylesheet and makes them default to the xslt-defined defaults.
windowsShortcut - Archive of obsolete content
method of file object syntax int windowsshortcut( folderobject atarget, folderobject ashortcutpath, string adescription, folderobject aworkingpath, string aparams, folderobject aicon, number aiconid); parameters the windowsshortcut method has the following parameters: atarget a filespecobject representing the absolute path (including filena
me) to file that the shortcut will be created for.
... ashortcutpath a filespecobject representing the absolute path (not including filena
me) to where the shortcut is to be created.
... aicon a filespecobject representing the absolute path (including fiilena
me) to a file that contains icons.
MacFAQ - Archive of obsolete content
this command will place a copy of your application in /applications/(vendor)/(na
me) , where (vendor) is the vendor field in your application.ini and (na
me) is the name field.
... opening your application for ordinary work, you can just navigate via finder to /applications/(vendor)/(na
me).app and open the application.
... for command-line work, you would call on: /applications/(vendor)/(na
me).app/contents/macos/xulrunner ui notes menus to enable your application quit command to work with the application menu (the one to the right of the blue apple), you need to give your quit menu item an id of "menu_filequititem".
Building a Theme - Archive of obsolete content
chrome uris consist of several components: firstly, the uri scheme (chro
me) which tells firefox's networking library that this is a chrome uri.
... it indicates that the content of the uri should be handled as a (chro
me).
... compare (chro
me) to (http) which tells firefox to treat the uri as a web page.
Processing XML with E4X - Archive of obsolete content
they support javascript's regular dot and [] notation, but instead of accessing object properties e4x overloads these operators to access the element's children: var person = <person> <name>bob smith</name> <likes> <os>linux</os> <browser>firefox</browser> <language>javascript</language> <language>python</language> </likes> </person>; alert(person.na
me); // bob smith alert(person['name']); // bob smith alert(person.likes.browser); // firefox alert(person['likes'].browser); // firefox if you access something with more than one matching element, you get back an xmllist: alert(person.likes.language.length()); // 2 as with the dom, * can be used to access all child nodes: alert(person.likes.*.length()); // 4 while the .
...e contained within the current element: var people = <people> <person> <name>bob</name> <age>32</age> </person> <person> <name>joe</name> <age>46</age> </person> </people>; alert(people.person.(name == "joe").age); // alerts 46 filter expressions can even use javascript functions: function over40(i) { return i > 40; } alert(people.person.(over40(parseint(age))).na
me); // alerts joe handling namespaces e4x is fully namespace aware.
... here either non-default var xhtml = <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>embedded svg demo</title> </head> <body> <h1>embedded svg demo</h1> <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 100 100"> <circle cx="50" cy="50" r="20" stroke="orange" stroke-width="2px" fill="yellow" /> </svg> </body> </html>; alert(xhtml.name().localna
me); // alerts "html" alert(xhtml.name().uri); // alerts "http://www.w3.org/1999/xhtml" to access elements that are within a non-default namespace, first create a namespace object encapsulating the uri for that namespace: var svgns = new namespace('http://www.w3.org/2000/svg'); this can now be used in e4x queries by using namespace::localname in place of a normal element specifier: var svg = xh...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
157 forbidden header name fetch, glossary, http, headers, forbidden a forbidden header name is the name of any http header that cannot be modified programmatically; specifically, an http request header name (in contrast with a forbidden response header na
me).
... 233 input method editor glossary an input method editor (i
me) is a program that provides a specialized user interface for text input.
... 472 urn glossary, intro, navigation, urn urn (uniform resource na
me) is a uri in a standard format, referring to a resource without specifying its location or whether it exists.
Introducing asynchronous JavaScript - Learn web development
that means that the following (pseudocode) wouldn't work: let response = fetch('myimage.png'); let blob = response.blob(); // display your image blob in the ui somehow that's because you don't know how long the image will take to download, so when you come to run the second line it will throw an error (possibly intermittently, possibly every ti
me) because the response is not yet available.
...it is “called back” (hence the na
me) asynchronously somewhere inside the containing function’s body.
...' + eachna
me); }); in this example we loop through an array of greek gods and print the index numbers and values to the console.
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
the general pattern you'd use looks something like this: let starttime = null; function draw(timestamp) { if (!startti
me) { starttime = timestamp; } currenttime = timestamp - starttime; // do something based on current time requestanimationframe(draw); } draw(); browser support requestanimationframe() is supported in more recent browsers than setinterval()/settimeout().
...they will define the start time if it is not defined already (this will only happen on the first loop iteration), and set the rotatecount to a value to rotate the spinner by (the current timestamp, take the starting timestamp, divided by three so it doesn't go too fast): if (!startti
me) { starttime = timestamp; } rotatecount = (timestamp - startti
me) / 3; below the previous line inside draw(), add the following block — this checks to see if the value of rotatecount is above 359 (e.g.
...this is very similar to the version from the simple spinner example, earlier: function draw(timestamp) { if(!startti
me) { starttime = timestamp; } rotatecount = (timestamp - startti
me) / 3; if(rotatecount > 359) { rotatecount %= 360; } spinner.style.transform = 'rotate(' + rotatecount + 'deg)'; raf = requestanimationframe(draw); } now it is time to set up the initial state of the app when the page first loads.
Client-side storage - Learn web development
function init() { // loop through the video names one by one for(let i = 0; i < videos.length; i++) { // open transaction, get object store, and get() each video by name let objectstore = db.transaction('videos_os').objectstore('videos_os'); let request = objectstore.get(videos[i].na
me); request.onsuccess = function() { // if the result exists in the database (is not undefined) if(request.result) { // grab the videos from idb and display them using displayvideo() console.log('taking videos from idb'); displayvideo(request.result.mp4, request.result.webm, request.result.na
me); } else { // fetch the videos from the network ...
...etch('videos/' + video.name + '.mp4').then(response => response.blob() ); let webmblob = fetch('videos/' + video.name + '.webm').then(response => response.blob() ); // only run the next code when both promises have fulfilled promise.all([mp4blob, webmblob]).then(function(values) { // display the video fetched from the network with displayvideo() displayvideo(values[0], values[1], video.na
me); // store it in the idb using storevideo() storevideo(values[0], values[1], video.na
me); }); let's look at storevideo() first.
... function storevideo(mp4blob, webmblob, na
me) { // open transaction, get object store; make it a readwrite so we can write to the idb let objectstore = db.transaction(['videos_os'], 'readwrite').objectstore('videos_os'); // create a record to add to the idb let record = { mp4 : mp4blob, webm : webmblob, name : name } // add the record to the idb using add() let request = objectstore.add(record); ...
A first splash into JavaScript - Learn web development
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', resetga
me); } function resetgame() { guesscount = 1; const resetparas = document.queryselectorall('.resultparas p'); for(let i = 0 ; i < resetparas.length ; i++) { resetparas[i].textcontent = ''; } resetbutton.parentnode.removechild(resetbutton); guessfield.disabled = false; guesssubmit.disabled = false; guessfield.value = ''; guessfiel...
... the first three constants are each made to store a reference to the results paragraphs in our html, and are used to insert values into the paragraphs later on in the code (note how they are inside a <div> element, which is itself used to select all three later on for resetting, when we restart the ga
me): <div class="resultparas"> <p class="guesses"></p> <p class="lastresult"></p> <p class="loworhi"></p> </div> the next two constants store references to the form text input and submit button and are used to control submitting the guess later on.
...add this now, below the rest of your javascript: function setgameover() { guessfield.disabled = true; guesssubmit.disabled = true; resetbutton = document.createelement('button'); resetbutton.textcontent = 'start new game'; document.body.append(resetbutton); resetbutton.addeventlistener('click', resetga
me); } the first two lines disable the form text input and button by setting their disabled properties to true.
Object-oriented JavaScript for beginners - Learn web development
add this function within the script element: function createnewperson(na
me) { const obj = {}; obj.name = name; obj.greeting = function() { alert('hi!
... replace your previous function with the following: function person(na
me) { this.name = name; this.greeting = function() { alert('hi!
...each instance is created according to this definition: function person(na
me) { this.name = name; this.greeting = function() { alert('hi!
React interactivity: Editing, filtering, conditional rendering - Learn web development
add the edittask() function inside your app component, in the same place as the other functions: function edittask(id, newna
me) { const editedtasklist = tasks.map(task => { // if this task has the same id as the edited task if (id === task.id) { // return {...task, name: newname} } return task; }); settasks(editedtasklist); } pass edittask into our <todo /> components as a prop in the same way we did with deletetask: const tasklist = tasks.map(task => ( <todo id={task.id} name={...
...update it as follows: <input id={props.id} classname="todo-text" type="text" value={newname} onchange={handlechange} /> finally, we need to create a function to handle the edit form’s onsubmit event; add the following just below the previous function you added: function handlesubmit(e) { e.preventdefault(); props.edittask(props.id, newna
me); setnewname(""); setediting(false); } remember that our edittask() callback prop needs the id of the task we're editing as well as its new name.
... with all of that done, your filter() function should read like this: function filterbutton(props) { return ( <button type="button" classname="btn toggle-btn" aria-pressed={props.ispressed} onclick={() => props.setfilter(props.na
me)} > <span classname="visually-hidden">show </span> <span>{props.name}</span> <span classname="visually-hidden"> tasks</span> </button> ); } visit your browser again.
NSS Sample Code Utilities_1
fprintf(stderr, "no password file \"%s\" exists.\n", pwfile); port_free(phrases); return null; } nb = pr_read(fd, phrases, maxpwdfilesize); pr_close(fd); if (nb == 0) { fprintf(stderr,"password file contains no data\n"); port_free(phrases); return null; } if (slot) { tokenname = pk11_gettokenname(slot); if (tokenna
me) { tokenlen = port_strlen(tokenna
me); } } i = 0; do { int startphrase = i; int phraselen; /* handle the windows eol case */ while (phrases[i] != '\r' && phrases[i] != '\n' && i < nb) i++; /* terminate passphrase */ phrases[i++] = '\0'; /* clean up any eol before the start of the next passphrase */ whi...
...hile ((c = getc(stdin)) != '\n' && c != eof) ; if (c == eof) rv = secfailure; fprintf(stderr, "\n"); /* set back termio the way it was */ tio.c_lflag = orig_lflag; tio.c_cc[vmin] = orig_cc_min; tio.c_cc[vtime] = orig_cc_time; tcsetattr(fd, tcsaflush, &tio); return rv; } /* * seedfromnoisefile */ secstatus seedfromnoisefile(const char *noisefilena
me) { char buf[2048]; prfiledesc *fd; print32 count; fd = pr_open(noisefilename, pr_rdonly, 0); if (!fd) { fprintf(stderr, "failed to open noise file."); return secfailure; } do { count = pr_read(fd,buf,sizeof(buf)); if (count > 0) { pk11_randomupdate(buf,count); } } while (count > 0); pr_close(fd); return ...
...secsuccess; } /* * filesize */ long filesize(const char* filena
me) { struct stat stbuf; stat(filename, &stbuf); return stbuf.st_size; } /* * readderfromfile */ secstatus readderfromfile(secitem *der, const char *infilename, prbool ascii) { secstatus rv = secsuccess; prfiledesc *infile = null; infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "failed to open file \"%s\" (%ld, %ld).\n", infilename, pr_geterror(), pr_getoserror()); rv = secfailure; goto cleanup; } if (ascii) { /* first convert ascii to binary */ secitem filedata; char *asc, *body; /* read in ascii data */ rv = filetoitem(&filedata, infile); asc = (char *)fil...
JSAPI User Guide
* if there's no error it just keeps going.) */ jsbool compileandrepeat(jscontext *cx, const char *filena
me) { jsscript *script; script = js_compileutf8file(cx, js_getglobalobject(cx), filena
me); if (!script) return false; /* compilation error */ for (;;) { jsval result; if (!js_executescript(cx, js_getglobalobject(cx), script, &result)) break; js_maybegc(cx); } return false; } the lifetime of the compiled script is tied to the ...
... * if there's no error it just keeps going.) */ jsbool compileandrepeat(jscontext *cx, const char *filena
me) { jsscript *script; jsobject *scriptobj; script = js_compileutf8file(cx, js_getglobalobject(cx), filena
me); if (!script) return false; /* compilation error */ scriptobj = js_newscriptobject(cx, script); if (!scriptobj) { js_destroyscript(cx, script); return false; } if (!js_addnamedobjectroot(cx, &scriptobj, "compileandrepeat script obj...
...ed executing: void functransition(const jsfunction *func, const jsscript *scr, const jscontext *const_cx, jsbool entering) { jscontext *cx = const_cast<jscontext*>(const_cx); jsstring *name = js_getfunctionid((jsfunction*)func); const char *entexit; const char *namestr; /* build a c string for the function's name */ if (!na
me) { namestr = "unnamed function"; } else { namestr = js_encodestring(cx, na
me); } /* build a string for whether we're entering or exiting */ if (entering) { entexit = "entering"; } else { entexit = "exiting"; } /* output information about the trace */ printf("%s javascript function: %s at time: %ld", entexit, namestr, clock()); } void enabletracing(jscontext *cx...
nsIAccessibilityService
last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) inherits from: nsiaccessibleretrieval method overview nsiaccessible createouterdocaccessible(in nsidomnode anode); nsiaccessible createrootaccessible(in nsipresshell ashell, in nsidocument adocument); nsiaccessible createhtml4buttonaccessible(in nsisupports afra
me); nsiaccessible createhypertextaccessible(in nsisupports afra
me); nsiaccessible createhtmlbraccessible(in nsisupports afra
me); nsiaccessible createhtmlbuttonaccessible(in nsisupports afra
me); nsiaccessible createhtmlaccessiblebymarkup(in nsiframe aframe, in nsiweakreference aweakshell, in nsidomnode adomnode); nsiaccessible createhtmlliaccessible(in nsisupports aframe, in nsisupport...
...s abulletframe, in astring abullettext); nsiaccessible createhtmlcheckboxaccessible(in nsisupports afra
me); nsiaccessible createhtmlcomboboxaccessible(in nsidomnode anode, in nsiweakreference apresshell); nsiaccessible createhtmlgenericaccessible(in nsisupports afra
me); nsiaccessible createhtmlgenericaccessible(in nsisupports afra
me); nsiaccessible createhtmlhraccessible(in nsisupports afra
me); nsiaccessible createhtmlimageaccessible(in nsisupports afra
me); nsiaccessible createhtmllabelaccessible(in nsisupports afra
me); nsiaccessible createhtmllabelaccessible(in nsidomnode anode, in nsiweakreference apresshell); nsiaccessible createhtmlobjectframeaccessible(in nsobjectframe afra
me); nsiaccessible createhtmlradiobuttonaccessible(in nsisupports afra
me); nsiacces...
...sible createhtmlselectoptionaccessible(in nsidomnode anode, in nsiaccessible aaccparent, in nsiweakreference apresshell); nsiaccessible createhtmltableaccessible(in nsisupports afra
me); nsiaccessible createhtmltablecellaccessible(in nsisupports afra
me); nsiaccessible createhtmltableheadaccessible(in nsidomnode adomnode); nsiaccessible createhtmltextaccessible(in nsisupports afra
me); nsiaccessible createhtmltextfieldaccessible(in nsisupports afra
me); nsiaccessible createhtmlcaptionaccessible(in nsisupports afra
me); nsiaccessible getaccessible(in nsidomnode anode, in nsipresshell apresshell, in nsiweakreference aweakshell, inout nsiframe framehint, out boolean aishidden); nsiaccessible addnativerootaccessible(in voidptr aatkaccessible); void removenativerootaccessible...
nsIMessenger
unsigned long getredotransactiontype(); void undo(in nsimsgwindow msgwindow); void redo(in nsimsgwindow msgwindow); void sendunsentmessages(in nsimsgidentity aidentity, in nsimsgwindow amsgwindow); void setdocumentcharset(in acstring characterset); void saveas(in acstring auri, in boolean aasfile, in nsimsgidentity aidentity, in astring amsgfilena
me); void openattachment(in acstring contenttpe, in acstring url, in acstring displayname, in acstring messageuri, in boolean isexternalattachment); void saveattachment(in acstring contenttpe, in acstring url, in acstring displayname, in acstring messageuri, in boolean isexternalattachment); void saveallattachments(in unsigned long count, [array, size_is(count)] in string c...
... void saveas(in acstring auri, in boolean aasfile, in nsimsgidentity aidentity, in astring amsgfilena
me); parameters auri the url of the message to save.
...returns the actual file path (including the filena
me).
Component; nsIPrefBranch
method overview void addobserver(in string adomain, in nsiobserver aobserver, in boolean aholdweak); void clearuserpref(in string aprefna
me); void deletebranch(in string astartingat); boolean getboolpref(in string aprefname, requires gecko 54 [optional] in boolean adefaultvalue); string getcharpref(in string aprefname,requires gecko 54 [optional] in string adefaultvalue); requires gecko 58 utf8tring getstringpref(in string aprefname, [optional] in utf8string adefaultvalue); void getchildlis...
...t(in string astartingat, [optional] out unsigned long acount, [array, size_is(acount), retval] out string achildarray); void getcomplexvalue(in string aprefname, in nsiidref atype, [iid_is(atype), retval] out nsqiresult avalue); long getintpref(in string aprefname,requires gecko 54 [optional] in long adefaultvalue); long getpreftype(in string aprefna
me); void lockpref(in string aprefna
me); boolean prefhasuservalue(in string aprefna
me); boolean prefislocked(in string aprefna
me); void removeobserver(in string adomain, in nsiobserver aobserver); void resetbranch(in string astartingat); void setboolpref(in string aprefname, in long avalue); void setcharpref(in string aprefname, in string avalue); r...
...equires gecko 58 void setstringpref(in string aprefname, in utf8string avalue); void setcomplexvalue(in string aprefname, in nsiidref atype, in nsisupports avalue); void setintpref(in string aprefname, in long avalue); void unlockpref(in string aprefna
me); attributes attribute type description root string called to get the root on which this branch is based, such as "browser.startup." read only.
nsIWebContentHandlerRegistrar
(); if (adomwindow.gbrowser) { if (adomwindow.gbrowser.tabcontainer) { //adomwindow has tabs var tabs = adomwindow.gbrowser.tabcontainer.childnodes; for (var i = 0; i < tabs.length; i++) { console.log(tabs[i].linkedbrowser.contentwindow.location); if (tabs[i].linkedbrowser.contentwindow.location.hostname == myurihostna
me) { htmlcontentwindow = tabs[i].linkedbrowser.contentwindow; break; //break for loop } } if (htmlcontentwindow) { break; //break while loop } } else { //adomwindow doest have any tabs if (adomwindow.gbrowser.contentwindow.location.hostname == myurihostna
me) { ...
... htmlcontentwindow = adomwindow.contentwindow; break; } } } else { //adomwindow is a popup window if (adomwindow.location.hostname == myurihostna
me) { htmlcontentwindow = adomwindow; break; } } } // this section here is long and daunting, but its just finding a suitable contentwindow if (!htmlcontentwindow) { throw new error('no suitable content window found, will not reigsterprotocolhandler.
... must have a content window to pass to registerprotocolhandler as it prompts the user for permission'); } nsiwchr.registerprotocolhandler("mailto", registeruri, "outlook.com live mail", htmlcontentwindow); in this example the services.wm.getenumerator was used to find a window that had the same host name (contentwindow.location.hostna
me) as the uri (uri.host) we are trying to add.
nsIXULRuntime
to get an instance, use: var xulruntime = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulrunti
me); method overview void invalidatecachesonrestart(); attributes attribute type description accessibilityenabled boolean if true, the accessibility service is running.
... constants process type constants constant value description process_type_default 0 the default (chro
me) process.
... example display the user's operating system in an alert box: var xulruntime = components.classes["@mozilla.org/xre/app-info;1"] .getservice(components.interfaces.nsixulrunti
me); alert(xulruntime.os); see also nsixulappinfo - a related interface providing information about the host application, it's also implemented by xre/app-info.
Xray vision
2) trying to access properties on the object that shadow properties // on the prototype will show the original 'native' version console.log("2) property that shadows the prototype:"); console.log(sandbox.me.constructor); // -> function() // 3) value properties defined by assignment to this are visible: console.log("3) value property defined by assignment to this:"); console.log(sandbox.me.firstna
me); // -> "joe" // 4) value properties defined using defineproperty are visible: console.log("4) value property defined by defineproperty"); console.log(sandbox.me.lastna
me); // -> "smith" // 5) accessor properties are not visible console.log("5) accessor property"); console.log(sandbox.me.middlena
me); // -> undefined // 6) accessing a value property of a value-property object is fine console.log...
...ned object are not visible in the xray console.log("7) call a function defined on the object"); try { console.log(sandbox.me.fullname()); } catch (e) { console.error(e); } // -> typeerror: sandbox.me.fullname is not a function // now with waived xrays console.log("now with waived xrays"); console.log("1) property redefined in the prototype:"); console.log(components.utils.waivexrays(sandbox.
me).tosource()); // -> "not what you expected?" console.log("2) property that shadows the prototype:"); console.log(components.utils.waivexrays(sandbox.
me).constructor); // -> "not a constructor" console.log("3) accessor property"); console.log(components.utils.waivexrays(sandbox.
me).middlena
me); // -> "wait, is this really a getter?" console.log("4) call a function defined on the object"); consol...
...e.log(components.utils.waivexrays(sandbox.
me).fullname()); // -> "joe smith" ...
Debugger.Object - Firefox Developer Tools
for example: function f() {} // display name: f (the given na
me) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; note that the display name may not be a proper javascript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property.
... getownpropertydescriptor(na
me) return a property descriptor for the property namedname of the referent.
...(this function behaves like object.defineproperties, except that the target object is implicit, and in a different compartment from theproperties argument.) deleteproperty(na
me) remove the referent’s property namedname.
Intensive JavaScript - Firefox Developer Tools
st multiplier = 1000000000; function calculateprimes(iterations, multiplier) { var primes = []; for (var i = 0; i < iterations; i++) { var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (ispri
me) { primes.push(candidate); } } return primes; } function dopointlesscomputationswithblocking() { var primes = calculateprimes(iterations, multiplier); pointlesscomputationsbutton.disabled = false; console.log(primes); } we're just running a (very inefficient) primality test 50 times, for some quite large numbers.
...terations) { 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 (ispri
me) { primes.push(candidate); } // schedule the next var testfunction = testcandidate.bind(this, index + 1); window.requestanimationframe(testfunction); } var primes = []; var testfunction = testcandidate.bind(this, 0); window.requestanimationframe(testfunction); } let's test this version out: select the radio button labeled "use requestanimationframe" and capture anot...
... "primes": primes }); } function calculateprimes(iterations, multiplier) { var primes = []; for (var i = 0; i < iterations; i++) { var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (ispri
me) { primes.push(candidate); } } return primes; } in the worker, we have to listen for a message telling us to start, and send a "done" message back when we are done.
AudioListener.dopplerFactor - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.forwardX - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.forwardY - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.forwardZ - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.positionX - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.positionY - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.positionZ - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.setOrientation() - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.setPosition() - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.speedOfSound - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.upX - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.upY - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener.upZ - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
AudioListener - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
BaseAudioContext.createGain() - Web APIs
the creategain() method of the baseaudiocontext interface creates a gainnode, which can be used to control the overall gain (or volu
me) of the audio graph.
... syntax var gainnode = audiocontext.creategain(); return value a gainnode which takes as input one or more audio sources and outputs audio whose volume has been adjusted in gain (volu
me) to a level specified by the node's gainnode.gain a-rate parameter.
... gainnode.gain.setvalueattime(0, audioctx.currentti
me); mute.id = "activated"; mute.innerhtml = "unmute"; } else { gainnode.gain.setvalueattime(1, audioctx.currentti
me); mute.id = ""; mute.innerhtml = "mute"; } } specifications specification status comment web audio apithe definition of 'creategain()' in that specification.
BaseAudioContext.createPanner() - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
Console.table() - Web APIs
// an array of strings console.table(["apples", "oranges", "bananas"]); // an object whose properties are strings function person(firstname, lastna
me) { this.firstname = firstname; this.lastname = lastname; } var me = new person("john", "smith"); console.table(
me); collections of compound types if the elements in the array, or properties in the object, are themselves arrays or objects, then their elements or properties are enumerated in the row, one per column: // an array of arrays var people = [["john", "smith"], ["jane", "doe"], ...
...["emily", "jones"]] console.table(people); // an array of objects function person(firstname, lastna
me) { this.firstname = firstname; this.lastname = lastname; } var john = new person("john", "smith"); var jane = new person("jane", "doe"); var emily = new person("emily", "jones"); console.table([john, jane, emily]); note that if the array contains objects, then the columns are labeled with the property name.
...you can use the optional columns parameter to select a subset of columns to display: // an array of objects, logging only firstname function person(firstname, lastna
me) { this.firstname = firstname; this.lastname = lastname; } var john = new person("john", "smith"); var jane = new person("jane", "doe"); var emily = new person("emily", "jones"); console.table([john, jane, emily], ["firstname"]); sorting columns you can sort the table by a particular column by clicking on that column's label.
File drag and drop - Web APIs
the full source code is available in mdn's drag-and-drop repository (pull requests and/or issues are welco
me).
...file[' + i + '].name = ' + file.na
me); } } } else { // use datatransfer interface to access the file(s) for (var i = 0; i < ev.datatransfer.files.length; i++) { console.log('...
... file[' + i + '].name = ' + ev.datatransfer.files[i].na
me); } } } prevent the browser's default drag behavior the following dragover event handler calls preventdefault() to turn off the browser's default drag and drop handler.
IDBTransaction - Web APIs
(bug 888598) transactions can have one of three modes: constant value description read_only "readonly" (0 in chro
me) allows data to be read but not changed.
... read_write "readwrite" (1 in chro
me) allows reading and writing of data in existing data stores to be changed.
... version_change "versionchange" (2 in chro
me) allows any operation to be performed, including ones that delete and create object stores and indexes.
Timing element visibility with the Intersection Observer API - Web APIs
function handlerefreshinterval() { let redrawlist = []; visibleads.foreach(function(adbox) { let previoustime = adbox.dataset.totalviewtime; updateadtimer(adbox); if (previoustime != adbox.dataset.totalviewti
me) { redrawlist.push(adbox); } }); if (redrawlist.length) { window.requestanimationframe(function(ti
me) { redrawlist.foreach(function(adbox) { drawadtimer(adbox); }); }); } } the array redrawlist will be used to keep a list of all the ads which need to be redrawn during this refresh cycle, since it may not be exactly the same as the elapsed time due to s...
...here it is: function updateadtimer(adbox) { let laststarted = adbox.dataset.lastviewstarted; let currenttime = performance.now(); if (laststarted) { let diff = currenttime - laststarted; adbox.dataset.totalviewtime = parsefloat(adbox.dataset.totalviewti
me) + diff; } adbox.dataset.lastviewstarted = currenttime; } to track an element's visible time, we use two custom data attributes (see data-*) on every ad: lastviewstarted the time in milliseconds, relative to the time at which the document was created, at which the ad's visibility count was last updated, or the ad last became visible.
... function replacead(adbox) { let visibletime; updateadtimer(adbox); visibletime = adbox.dataset.totalviewtime console.log(" replacing ad: " + adbox.queryselector("h2").innertext + " - visible for " + visibleti
me) loadrandomad(adbox); } replacead() begins by calling updateadtimer() on the existing ad, to ensure that its timer is up-to-date.
Microdata DOM API - Web APIs
nameditem(domstring na
me); // shadows inherited nameditem() readonly attribute domstring[] names; }; typedef sequence<any> propertyvaluearray; interface propertynodelist : nodelist { propertyvaluearray getvalues(); }; collection .
...nameditem(na
me) returns a propertynodelist object containing any elements that add a property named name.
... the nameditem(na
me) method must return a propertynodelist object representing a live view of the htmlpropertiescollection object, further filtered so that the only nodes in the propertynodelist object are those that have a property name equal to name.
PannerNode.distanceModel - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
PannerNode.maxDistance - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
PannerNode.panningModel - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
PannerNode.setOrientation() - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
PannerNode.setPosition() - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
PannerNode.setVelocity() - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
PannerNode - Web APIs
kitaudiocontext; var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; panner.distancemodel = 'inverse'; panner.refdistance = 1; panner.maxdistance = 10000; panner.rollofffactor = 1; panner.coneinnerangle = 360; panner.coneouterangle = 0; panner.coneoutergain = 0; if(panner.orientationx) { panner.orientationx.setvalueattime(1, audioctx.currentti
me); panner.orientationy.setvalueattime(0, audioctx.currentti
me); panner.orientationz.setvalueattime(0, audioctx.currentti
me); } else { panner.setorientation(1,0,0); } var listener = audioctx.listener; if(listener.forwardx) { listener.forwardx.setvalueattime(0, audioctx.currentti
me); listener.forwardy.setvalueattime(0, audioctx.currentti
me); listener.forwardz.setvalueattime(-1, audioctx...
....currentti
me); listener.upx.setvalueattime(0, audioctx.currentti
me); listener.upy.setvalueattime(1, audioctx.currentti
me); listener.upz.setvalueattime(0, audioctx.currentti
me); } else { listener.setorientation(0,0,-1,0,1,0); } var source; var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); var boombox = document.queryselector('.boom-box'); var listenerdata = document.queryselector('.listener-data'); var pannerdata = document.queryselector('.panner-data'); leftbound = (-xpos) + 50; rightbound = xpos - 50; xiterator = width/150; // listener will always be in the same place for this demo if(listener.positionx) { listener.positionx.setvalueattime(xpos, audioctx.currentti
me); listener.positiony.setvalueattime(ypos, audioctx.currentti
me); li...
...stener.positionz.setvalueattime(300, audioctx.currentti
me); } else { listener.setposition(xpos,ypos,300); } listenerdata.innerhtml = 'listener data: x ' + xpos + ' y ' + ypos + ' z ' + 300; // panner will move as the boombox graphic moves around on the screen function positionpanner() { if(panner.positionx) { panner.positionx.setvalueattime(xpos, audioctx.currentti
me); panner.positiony.setvalueattime(ypos, audioctx.currentti
me); panner.positionz.setvalueattime(zpos, audioctx.currentti
me); } else { panner.setposition(xpos,ypos,zpos); } pannerdata.innerhtml = 'panner data: x ' + xpos + ' y ' + ypos + ' z ' + zpos; } note: in terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on ...
Using the Resource Timing API - Web APIs
resource" performance entries var resources = performance.getentriesbytype("resource"); if (resources === undefined || resources.length <= 0) { console.log("= calculate load times: there are no `resource` performance records"); return; } console.log("= calculate load times"); for (var i=0; i < resources.length; i++) { console.log("== resource[" + i + "] - " + resources[i].na
me); // redirect time var t = resources[i].redirectend - resources[i].redirectstart; console.log("...
...(resources[i].responseend - resources[i].startti
me) : "0"; console.log("...
... return; } var list = performance.getentriesbytype("resource"); if (list === undefined) { console.log("= display size data: performance.getentriesbytype() is not supported"); return; } // for each "resource", display its *size property values console.log("= display size data"); for (var i=0; i < list.length; i++) { console.log("== resource[" + i + "] - " + list[i].na
me); if ("decodedbodysize" in list[i]) console.log("...
User Timing API - Web APIs
removing performance marks to remove a specific mark from the performance timeline, call performance.clearmarks(na
me) where name is the name of the mark(s) you want removed.
... creating a performance measure a measure is created by calling performance.measure(measurename, startmarkname, endmarkna
me) where measurename is the measure's name and startmarkname and endmarkname are the start and end names, respectively, of the marks the measure will be placed between (in the performance timeline).
... removing performance measures to remove a specific measure from the performance timeline, call performance.clearmeasures(na
me) where name is the name of the measure(s) you want removed.
Signaling and video calling - Web APIs
function handleuserlistmsg(msg) { var i; var listelem = document.queryselector(".userlistbox"); while (listelem.firstchild) { listelem.removechild(listelem.firstchild); } msg.users.foreach(function(userna
me) { var item = document.createelement("li"); item.appendchild(document.createtextnode(userna
me)); item.addeventlistener("click", invite, false); listelem.appendchild(item); }); } after getting a reference to the <ul> which contains the list of user names into the variable listelem, we empty the list by removing each of its child elements.
... 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 === myuserna
me) { alert("i'm afraid i can't let you talk to yourself.
... function handlegetusermediaerror(e) { switch(e.na
me) { case "notfounderror": alert("unable to open your call because no camera and/or microphone" + "were found."); break; case "securityerror": case "permissiondeniederror": // do nothing; this is the same as the user canceling the call.
Using bounded reference spaces - Web APIs
it's also useful because the user may be engrossed in gameplay or other activity, not realize they're approaching the boundary, and could become confused or distressed if they wander out of tracking range (especially if doing so causes them to lose a ga
me).
... xrsession.requestanimationframe(ondrawfra
me); } if you compare this code to the code used in examples using unbounded reference spaces, you'll confirm that, indeed, the biggest difference is the reference space type bounded-floor.
...ction onrefspacecreated(refspace) { xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl) }); let startposition = vec3.fromvalues(0, 1.5, 0); const startorientation = vec3.fromvalues(0, 0, 1.0); xrreferencespace = xrreferencespace.getoffsetreferencespace( new xrrigidtransform(startposition, startorientation)); xrsession.requestanimationframe(ondrawfra
me); } in this code, executed after the reference space has been created, we create an xrrigidtransform representing the transform that will move the viewpoint upward by 1.5 meters.
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
the first is described above: applying a reference space to an offset (or vice-versa, since the result is the sa
me) to determine the transform matrix that represents the resulting location in the space's coordinate system.
... for example, given an xrsession whose reference space is worldrefspace, the following line of code would request the first frame of animation to be scheduled: animationframerequestid = xrsession.requestanimationframe(mydrawfra
me); then, the mydrawframe() function—the callback executed when it's time to draw the frame—might be something like this: function mydrawframe(currentframetime, fra
me) { let session = frame.session; let viewerpose = frame.getviewerpose(viewerrefspace); animationframerequestid = session.requestanimationframe(mydrawfra
me); if (viewerpose) { /* ...
... let previousviewerpose = null; function mydrawframe(currentframetime, fra
me) { let session = frame.session; let viewerpose = frame.getviewerpose(viewerrefspace); animationframerequestid = session.requestanimationframe(mydrawfra
me); if (viewerpose) { if (!previousviewerpose) { previousviewerpose = viewerpose; } let offsetmatrix = mat4.create(); mat4.sub(offsetmatrix, previousviewerpose.transform.matrix, viewerpose.transform.mat...
Using Web Workers - Web APIs
ener || function() {}; if (onerror) {worker.onerror = onerror;} this.postmessage = function(message) { worker.postmessage(message); } this.terminate = function() { worker.terminate(); } } then we add the methods of adding/removing listeners: this.addlisteners = function(name, listener) { listeners[name] = listener; } this.removelisteners = function(na
me) { delete listeners[name]; } here we let the worker handle two simple operations for illustration: getting the difference of two numbers and making an alert after three seconds.
...etc): calls a worker's queryable function * postmessage(string or json data): see worker.prototype.postmessage() * terminate(): terminates the worker * addlistener(name, function): adds a listener * removelistener(na
me): removes a listener queryableworker instances properties: * defaultlistener: the default listener executed only when the worker calls the postmessage() function directly */ function queryableworker(url, defaultlistener, onerror) { var instance = this, worker = new worker(url), listeners = {}; this.defaultlistener = defaultlistener || function() {}; ...
... if (onerror) {worker.onerror = onerror;} this.postmessage = function(message) { worker.postmessage(message); } this.terminate = function() { worker.terminate(); } this.addlistener = function(name, listener) { listeners[name] = listener; } this.removelistener = function(na
me) { delete listeners[name]; } /* this functions takes at least one argument, the method name we want to query.
Window.open() - Web APIs
an offset is universally implemented by browser manufacturers (it is 29 pixels in ie6 sp2 with the default the
me) and its purpose is to help users to notice new windows opening.
... you can also parameterize the function to make it versatile, functional in more situations, therefore re-usable in scripts and webpages: <script type="text/javascript"> var windowobjectreference = null; // global variable function openrequestedpopup(url, windowna
me) { if(windowobjectreference == null || windowobjectreference.closed) { windowobjectreference = window.open(url, windowname, "resizable,scrollbars,status"); } else { windowobjectreference.focus(); }; } </script> (...) <p><a href="http://www.spreadfirefox.com/" target="promotefirefoxwindow" onclick="openrequestedpopup(this.href, this.target); return false;" title="this...
...a script loaded in a window (or fra
me) from a distinct origin (domain na
me) cannot get nor set properties of another window (or fra
me) or the properties of any of its html objects coming from another distinct origin (domain na
me).
Using XMLHttpRequest - Web APIs
*/ for (nfile = 0; nfile < ofield.files.length; this.segments.push(ffilter(ofield.na
me) + "=" + ffilter(ofield.files[nfile++].na
me))); } } else if ((sfieldtype !== "radio" && sfieldtype !== "checkbox") || ofield.checked) { /* note: this will submit _all_ submit buttons.
.../* enctype is multipart/form-data */ "content-disposition: form-data; name=\"" + ofield.name + "\"\r\n\r\n" + ofield.value + "\r\n" : /* enctype is application/x-www-form-urlencoded or text/plain or method is get */ ffilter(ofield.na
me) + "=" + ffilter(ofield.value) ); } } processstatus(this); } return function (oformelement) { if (!oformelement.action) { return; } new submitrequest(oformelement); }; })(); </script> </head> <body> <h1>sending forms with pure ajax</h1> <h2>using the get method</h2> <form action="register.php" method="get" onsubmit="ajaxsubmit(this); return false;"> <fie...
... ofield.getattribute("type").touppercase() : "text"; if (sfieldtype === "file") { for (nfile = 0; nfile < ofield.files.length; ssearch += "&" + escape(ofield.na
me) + "=" + escape(ofield.files[nfile++].na
me)); } else if ((sfieldtype !== "radio" && sfieldtype !== "checkbox") || ofield.checked) { ssearch += "&" + escape(ofield.na
me) + "=" + escape(ofield.value); } } oreq.open("get", oformelement.action.replace(/(?:\?.*)?$/, ssearch.replace(/^&/, "?")), true); oreq.send(null); } } </script> </head> <body> <h1>sending forms wit...
Using media queries - CSS: Cascading Style Sheets
the not is evaluated last in the following query: @media not all and (monochro
me) { ...
...so that the above query is evaluated like this: @media not (all and (monochro
me)) { ...
...rather than like this: @media (not all) and (monochro
me) { ...
Getting Started - Developer guides
inter; text-decoration: underline"> make a request </span> we'll also add a line to our event handler to get the user's data from the text box and send it to the makerequest() function along with the url of our server-side script: document.getelementbyid("ajaxbutton").onclick = function() { var username = document.getelementbyid("ajaxtextbox").value; makerequest('test.php',userna
me); }; we need to modify makerequest() to accept the user data and pass it along to the server.
... we'll change the request method from get to post, and include our data as a parameter in the call to httprequest.send(): function makerequest(url, userna
me) { ...
... httprequest.onreadystatechange = alertcontents; httprequest.open('post', url); httprequest.setrequestheader('content-type', 'application/x-www-form-urlencoded'); httprequest.send('username=' + encodeuricomponent(userna
me)); } the function alertcontents() can be written the same way it was in step 3 to alert our computed string, if that's all the server returns.
Introduction - JavaScript
it is useful if you want to implement standards-compliant language features in your ecmascript implementation or engine (such as spidermonkey in firefox, or v8 in chro
me).
...for the sake of simplicity, it can be imagined that every time something is entered into the console, it is actually surrounded by console.log around eval, like so: function greetme(yourna
me) { alert("hello " + yourna
me) } console.log(eval('3 + 5')) multi-line input in the web console the single-line input mode of the web console is great for quick testing of javascript expressions, but although you can execute multiple lines, it's not very convenient for that.
... hello world to get started with writing javascript, open the web console in multi-line mode, and write your first "hello world" javascript code: (function(){ "use strict"; /* start of your code */ function greetme(yourna
me) { alert('hello ' + yourna
me); } greetme('world'); /* end of your code */ })(); press cmd+enter or ctrl+enter (or click the run button) to watch it unfold in your browser!
Working with objects - JavaScript
this notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runti
me).
...to illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function: function showprops(obj, objna
me) { var result = ``; for (var i in obj) { // obj.hasownproperty() is used to filter out properties from the object's prototype chain if (obj.hasownproperty(i)) { result += `${objname}.${i} = ${obj[i]}\n`; } } return result; } so, the function call showprops(mycar, "mycar") would return the following: mycar.make = ford mycar.model = mustang mycar.year = 1969 enumerate t...
... const manager = { name: "john", age: 27, job: "software engineer" } const intern= { name: "ben", age: 21, job: "software engineer intern" } function sayhi() { console.log('hello, my name is', this.na
me) } // add sayhi function to both objects manager.sayhi = sayhi; intern.sayhi = sayhi; manager.sayhi() // hello, my name is john' intern.sayhi() // hello, my name is ben' the this refers to the object that it is in.
TypeError: Reduce of empty array with no initial value - JavaScript
similarly, the same issue can happen if there is a typo in a selector, or an unexpected number of elements in a list: var names = document.getelementsbyclassname("names"); var name_list = array.prototype.reduce.call(names, (acc, na
me) => acc + ", " + na
me); valid cases these problems can be solved in two different ways.
... var names = document.getelementsbyclassname("names"); var name_list1 = ""; if (names1.length >= 1) name_list1 = array.prototype.reduce.call(names, (acc, na
me) => acc + ", " + na
me); // name_list1 == "" when names is empty.
... var name_list2 = array.prototype.reduce.call(names, (acc, na
me) => { if (acc == "") // initial value return name; return acc + ", " + name; }, ""); // name_list2 == "" when names is empty.
Intl.Locale.prototype.minimize() - JavaScript
description this method carries out the reverse of maximize(), removing any language, script, or region subtags from the locale language identifier (essentially the contents of basena
me).
... examples using minimize let mylocale = new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basena
me); // prints "fr-latn-fr" console.log(mylocale.tostring()); // prints "fr-latn-fr-u-ca-gregory-hc-h24" let mylocminimized = mylocale.minimize(); // prints "fr", since french is only written in the latin script // and is most likely to be spoken in france.
... console.log(mylocminimized.basena
me); // prints "fr-u-ca-gregory-hc-h24".
Object - JavaScript
for example: var person = function(na
me) { this.name = name; this.cantalk = true; }; person.prototype.greet = function() { if (this.cantalk) { console.log('hi, i am ' + this.na
me); } }; var employee = function(name, title) { person.call(this, na
me); this.title = title; }; employee.prototype = object.create(person.prototype); employee.prototype.constructor = employee; //if you don't set object.prototype.constructor to ...
... employee.prototype.greet = function() { if (this.cantalk) { console.log('hi, i am ' + this.name + ', the ' + this.title); } }; var customer = function(na
me) { person.call(this, na
me); }; customer.prototype = object.create(person.prototype); customer.prototype.constructor = customer; //if you don't set object.prototype.constructor to customer, //it will take prototype.constructor of person (parent).
... var mime = function(na
me) { person.call(this, na
me); this.cantalk = false; }; mime.prototype = object.create(person.prototype); mime.prototype.constructor = mime; //if you don't set object.prototype.constructor to mime, //it will take prototype.constructor of person (parent).
Function expression - JavaScript
if function name is omitted, it will be the variable name (implicit na
me).
... if function name is present, it will be the function name (explicit na
me).
... this also applies to arrow functions (arrows don't have a name so you can only give the variable an implicit na
me).
The "codecs" parameter in common media types - Web media technologies
the default value is 0 (not monochro
me).
...ining the chroma subsampling format subsampling_x subsampling_y monochrome flag chroma subsampling format 0 0 0 yuv 4:4:4 1 0 0 yuv 4:2:2 1 1 0 yuv 4:2:0 1 1 1 yuv 4:0:0 (monochro
me) the third digit in ccc indicates the chroma sample position, with a value of 0 indicating that the position is unknown and must be separately provided during decoding; a value of 1 indicating that the sample position is horizontally colocated with the (0, 0) luma sample; and a value of 2 indicating that the sample position is colocated with (0, 0) luma.
...the option to encode each frame as three separate color planes (that is, each color's data is stored as if it were a single monochrome fra
me).
Progressive web app structure - Progressive web apps (PWAs)
/a></li>\n\ <li><span>github:</span> <a href='https://github'>github</a></li>\n\ <li><span>more:</span> <a href='http://js13kgames.com/entries/slug'>js13kgames.com/entries/slug</a></li>\n\ </ul>\n\ </article>"; var content = ''; for(var i=0; i<games.length; i++) { var entry = template.replace(/pos/g,(i+1)) .replace(/slug/g,games[i].slug) .replace(/name/g,games[i].na
me) .replace(/author/g,games[i].author) .replace(/twitter/g,games[i].twitter) .replace(/website/g,games[i].website) .replace(/github/g,games[i].github); entry = entry.replace('<a href=\'http:///\'></a>','-'); content += entry; }; document.getelementbyid('content').innerhtml = content; next, it registers a service worker: if('serviceworker' in navigator) { ...
...s = []; for(var i=0; i<games.length; i++) { gamesimages.push('data/img/'+games[i].slug+'.jpg'); } var contenttocache = appshellfiles.concat(gamesimages); the next block installs the service worker, which then actually caches all the files contained in the above list: self.addeventlistener('install', function(e) { console.log('[service worker] install'); e.waituntil( caches.open(cachena
me).then(function(cache) { console.log('[service worker] caching all: app shell and content'); return cache.addall(contenttocache); }) ); }); last of all, the service worker fetches content from the cache if it is available there, providing offline functionality: self.addeventlistener('fetch', function(e) { e.respondwith( caches.match(e.request).then(function(r) { cons...
...ole.log('[service worker] fetching resource: '+e.request.url); return r || fetch(e.request).then(function(response) { return caches.open(cachena
me).then(function(cache) { console.log('[service worker] caching new resource: '+e.request.url); cache.put(e.request, response.clone()); return response; }); }); }) ); }); the javascript data the games data is present in the data folder in a form of a javascript object (games.js): var games = [ { slug: 'lost-in-cyberspace', name: 'lost in cyberspace', author: 'zosia and bartek', twitter: 'bartaz', website: '', github: 'github.com/bartaz/lost-in-cyberspace' }, { slug: 'vernissage', name: 'vernissage', au...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
var gamesimages = []; for(var i=0; i<games.length; i++) { gamesimages.push('data/img/'+games[i].slug+'.jpg'); } var contenttocache = appshellfiles.concat(gamesimages); then we can manage the install event itself: self.addeventlistener('install', (e) => { console.log('[service worker] install'); e.waituntil( caches.open(cachena
me).then((cache) => { console.log('[service worker] caching all: app shell and content'); return cache.addall(contenttocache); }) ); }); there are two things that need an explanation here: what extendableevent.waituntil does, and what the caches object is.
...if the file is not in the cache, the app adds it there first before then serving it: self.addeventlistener('fetch', (e) => { e.respondwith( caches.match(e.request).then((r) => { console.log('[service worker] fetching resource: '+e.request.url); return r || fetch(e.request).then((response) => { return caches.open(cachena
me).then((cache) => { console.log('[service worker] caching new resource: '+e.request.url); cache.put(e.request, response.clone()); return response; }); }); }) ); }); here, we respond to the fetch event with a function that tries to find the resource in the cache and return the response if it's there.
...it can be used to clear out the old cache we don't need anymore: self.addeventlistener('activate', (e) => { e.waituntil( caches.keys().then((keylist) => { return promise.all(keylist.map((key) => { if(key !== cachena
me) { return caches.delete(key); } })); }) ); }); this ensures we have only the files we need in the cache, so we don't leave any garbage behind; the available cache space in the browser is limited, so it is a good idea to clean up after ourselves.
Structural overview of progressive web apps - Progressive web apps (PWAs)
n\ <li><span>github:</span> <a href='https://github'>github</a></li>\n\ <li><span>more:</span> <a href='http://js13kgames.com/entries/slug'> js13kgames.com/entries/slug</a></li>\n\ </ul>\n\ </article>"; var content = ''; for(var i=0; i<games.length; i++) { var entry = template.replace(/pos/g,(i+1)) .replace(/slug/g,games[i].slug) .replace(/name/g,games[i].na
me) .replace(/author/g,games[i].author) .replace(/twitter/g,games[i].twitter) .replace(/website/g,games[i].website) .replace(/github/g,games[i].github); entry = entry.replace('<a href=\'http:///\'></a>','-'); content += entry; }; document.getelementbyid('content').innerhtml = content; then it registers a service worker: if ("serviceworker" in navigator) { ...
... self.addeventlistener('install', function(e) { console.log('[service worker] install'); e.waituntil( caches.open(cachena
me).then(function(cache) { console.log('[service worker] caching all: app shell and content'); return cache.addall(contenttocache); }) ); }); with that done, we implement the service worker's fetch event handler; its job is to return the contents of the specified file, either from the cache or by loading it over the network (caching it upon doing so): self.addeventlistener('fetch...
...', function(e) { e.respondwith( caches.match(e.request).then(function(r) { console.log('[service worker] fetching resource: '+e.request.url); return r || fetch(e.request).then(function(response) { return caches.open(cachena
me).then(function(cache) { console.log('[service worker] caching new resource: '+e.request.url); cache.put(e.request, response.clone()); return response; }); }); }) ); }); auxiliary javascript file: games.js the games data for this app example is provided in a javascript source file called games.js.
Caching compiled WebAssembly modules - WebAssembly
function opendatabase() { return new promise((resolve, reject) => { var request = indexeddb.open(dbname, dbversion); request.onerror = reject.bind(null, 'error opening wasm cache database'); request.onsuccess = () => { resolve(request.result) }; request.onupgradeneeded = event => { var db = request.result; if (db.objectstorenames.contains(storena
me)) { console.log(`clearing out version ${event.oldversion} wasm cache`); db.deleteobjectstore(storena
me); } console.log(`creating version ${event.newversion} wasm cache`); db.createobjectstore(storena
me) }; }); } looking up modules in the database our next function — lookupindatabase() — provides a simple promise-based operation for ...
... function lookupindatabase(db) { return new promise((resolve, reject) => { var store = db.transaction([storename]).objectstore(storena
me); var request = store.get(url); request.onerror = reject.bind(null, `error getting wasm module ${url}`); request.onsuccess = event => { if (request.result) resolve(request.result); else reject(`module ${url} was not found in wasm cache`); } }); } storing and instantiating modules next, we define a function storeindatabase() that fires off an async operation to store a given wasm module in a given database.
... function storeindatabase(db, module) { var store = db.transaction([storename], 'readwrite').objectstore(storena
me); var request = store.put(module, url); request.onerror = err => { console.log(`failed to store in wasm cache: ${err}`) }; request.onsuccess = err => { console.log(`successfully stored ${url} in wasm cache`) }; } using our helper functions with all the promise-based helper functions defined, we can now express the core logic of an indexeddb cache lookup.
indexed-db - Archive of obsolete content
on(e) { var db = e.target.result; e.target.transaction.onerror = database.onerror; if(db.objectstorenames.contains("items")) { db.deleteobjectstore("items"); } var store = db.createobjectstore("items", {keypath: "time"}); }; request.onsuccess = function(e) { database.db = e.target.result; }; request.onerror = database.onerror; }; function additem(na
me) { var db = database.db; var trans = db.transaction(["items"], "readwrite"); var store = trans.objectstore("items"); var time = new date().gettime(); var request = store.put({ "name": name, "time": time }); request.onerror = database.onerror; }; function getitems(callback) { var cb = callback; var db = database.db; var trans = db.transaction(["items"], "readwrite"); ...
... var store = trans.objectstore("items"); var items = new array(); trans.oncomplete = function() { cb(items); } var keyrange = idbkeyrange.lowerbound(0); var cursorrequest = store.opencursor(keyrange); cursorrequest.onsuccess = function(e) { var result = e.target.result; if(!!result == false) return; items.push(result.value.na
me); result.continue(); }; cursorrequest.onerror = database.onerror; }; function listitems(itemlist) { console.log(itemlist); } open("1"); var add = require("sdk/ui/button/action").actionbutton({ id: "add", label: "add", icon: "./add.png", onclick: function() { additem(require("sdk/tabs").activetab.title); } }); var list = require("sdk/ui/button/action").actionbutton({ id: "list", label: "list", icon...
self - Archive of obsolete content
methods data.load(na
me) the data.load() method returns the contents of an embedded data file, as a string.
... data.url(na
me) the data.url() method returns a resource:// url that points at an embedded data file.
simple-prefs - Archive of obsolete content
this is used to access the preference from your add-on: console.log(require("sdk/simple-prefs").prefs.mysettingna
me); this means that it must be a valid javascript identifier.
... example: function onprefchange(prefna
me) { console.log("the preference " + prefname + " value has changed!"); } require("sdk/simple-prefs").on("somepreference", onprefchange); require("sdk/simple-prefs").on("someotherpreference", onprefchange); // `""` listens to all changes in the extension's branch require("sdk/simple-prefs").on("", onprefchange); parameters prefname : string the name of the preferenc...
system - Archive of obsolete content
og("platform = " + system.platform); // processor architecture console.log("architecture = " + system.architecture); // compiler used to build host application console.log("compiler = " + system.compiler); // host application build identifier console.log("build = " + system.build); // host application uuid console.log("id = " + system.id); // host application name console.log("name = " + system.na
me); // host application version console.log("version = " + system.version); // host application vendor console.log("vendor = " + system.vendor); // host application profile directory console.log("profile directory = " + system.pathfor("profd")); quit the host application to quit the host application, use the exit() function.
... var system = require("sdk/system"); console.log("name = " + system.na
me); version the version of the host application.
frame/hidden-frame - Archive of obsolete content
functions add(hiddenfra
me) register a hidden frame, preparing it to load content.
... parameters hiddenframe : hiddenframe the frame to add remove(hiddenfra
me) unregister a hidden frame, unloading any content that was loaded in it.
remote/parent - Archive of obsolete content
= 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", (fra
me) => { console.log(frame.frameelement.currenturi.host + ": pageshow"); }); globals functions remoterequire(id, module = null) loads a module in any existing and future child processes.
... const { frames } = require("sdk/remote/parent"); frames.on("attach", function(fra
me) { console.log("frame is attached: " + frame.frameelement); }); methods forevery(callback) calls the callback for every existing frame and any new frames created in the future.
console - Archive of obsolete content
console.log(object[, object, ...]) logs the arguments to the console, preceded by "info:" and the name of your add-on: console.log("this is an informational message"); info: my-addon: this is an informational message console.time(na
me) starts a timer with a name specified as an input parameter.
... console.timeend(na
me) stops the specified timer and logs the elapsed time in seconds since its start.
QuerySelector - Archive of obsolete content
t xulelement] ]]></script> document.prototype.$ = function (selector) { // only for plain xml return this.queryselector(selector); }; var foo = document.implementation.createdocument('somens', 'foo', null); // create an xml document <foo xmlns="somens"/> var bar = foo.createelementns('somens', 'bar'); // add <bar xmlns="somens"/> foo.documentelement.appendchild(bar); alert(foo.$('bar').nodena
me); // gives 'bar' element.prototype.$ = function (selector) { // works for html, xul, and plain xml return this.queryselector(selector); }; html example: <h1><a>test!<a/></h1> <script> element.prototype.$ = function (selector) { return this.queryselector(selector); }; alert(document.getelementsbytagname('h1')[0].$('a').nodena
me); // 'a' xul example: <hbox><vbox/></hbox> <script type="tex...
...t/javascript"><![cdata[ element.prototype.$ = function (selector) { return this.queryselector(selector); }; var xulns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; alert(document.getelementsbytagnamens(xulns, 'hbox')[0].$('vbox').nodena
me); // vbox ]]></script> xml example: <foo xmlns="somens"><bar/></foo> in document earlier var foo = document.getelementsbytagnamens('somens', 'foo')[0]; alert(foo.$('bar')); note that for plain xml, the # 'id' selector will not work with an 'id' attribute (since a such-named attribute need not necessarily be of type id in xml, though it is in html and xul), nor will it work with xml:id.
Connecting to Remote Content - Archive of obsolete content
request.onload = function(aevent) { let text = aevent.target.responsetext; let jsobject = json.parse(text); window.alert(jsobject.shops[1].na
me); // => "orange" window.alert(jsobject.total); // => 2; }; the javascript object can also be serialized back with the stringify method.
... request.onload = function(aevent) { let responsexml = aevent.target.responsexml; let rootelement = responsexml.documentelement; if (rootelement && "parseerror" != rootelement.tagna
me) { let shopelements = rootelement.getelementsbytagname("shop"); let totalelement = rootelement.getelementsbytagname("total")[0]; window.alert(shopelements[1].getelementsbytagname("name")[0].firstchild.nodevalue); // => orange window.alert(totalelement.firstchild.nodevalue); // => 2 } }; using dom functions is good for simple xml documents, b...
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
json templating jsontodom.namespaces = { html: "http://www.w3.org/1999/xhtml", xul: "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" }; jsontodom.defaultnamespace = jsontodom.namespaces.html; function jsontodom(jsontemplate, doc, nodes) { function namespace(na
me) { var reelemnameparts = /^(?:(.*):)?(.*)$/.exec(na
me); return { namespace: jsontodom.namespaces[reelemnameparts[1]], shortname: reelemnameparts[2] }; } // note that 'elemnameorarray' is: either the full element name (eg.
...parse element namespace prefix (if none exists, default to defaultnamespace), and create element var elemns = namespace(elemnameorarray); var elem = doc.createelementns(elemns.namespace || jsontodom.defaultnamespace, elemns.shortna
me); // set element's attributes and/or callback functions (eg.
Install.js - Archive of obsolete content
r no post-install message // --- editable items end --- profileinstall: true, silentinstall: false, install: function() { var jarname = this.extshortname + '.jar'; var profiledir = install.getfolder('profile', 'chrome'); // parse http arguments this.parsearguments(); // check if extension is already installed in profile if (file.exists(install.getfolder(profiledir, jarna
me))) { if (!this.silentinstall) { install.alert('updating existing profile install of ' + this.extfullname + ' to version ' + this.extversion + '.'); } this.profileinstall = true; } else if (!this.silentinstall) { // ask user for install location, profile or browser dir?
...his.extshortname; install.initinstall(dispname, regname, this.extversion); // find directory to install into var installpath; if (this.profileinstall) installpath = profiledir; else installpath = install.getfolder('chrome'); // add jar file install.addfile(null, 'chrome/' + jarname, installpath, null); // register chrome var jarpath = install.getfolder(installpath, jarna
me); var installtype = this.profileinstall ?
Autodial for Windows NT - Archive of obsolete content
a brief history of autodial on windows in the consumer versions of windows, (windows 95, windows 98, windows
me) autodial for all applications is controlled from the control panel, in the internet options applet, under the tab connections.
...starting with windows nt, and in all nt-based versions (windows nt, windows 2000, and windows xp, including xp ho
me) microsoft has changed the behavior of autodial.
JavaScript Client API - Archive of obsolete content
function foostore(na
me) { store.call(this, na
me); } foostore.prototype = { __proto__: store.prototype, itemexists: function(guid) { // return true if an item with given guid exists in the store.
... function footracker(na
me) { tracker.call(this, na
me); // register yourself as event listener or observer for whatever // you want to track.
Makefile.mozextension.2 - Archive of obsolete content
cts http://kb.mozillazine.org/getting_started_with_extension_development # call with: # make -f makefile.mozextension2 make_structure ## (without args for 'all') # note: @echo silent; without @ the command is written in stdout project=test project_name=testworld #~ project_id={xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} project_id=test@testworld.ext project_version=1.0 project_desc="a $(project_na
me) project with advanced features" project_author=author name # mkdir=$(shell which mkdir) mkdir=/bin/mkdir zipprog=/usr/bin/zip shell = /bin/sh noop = $(shell) -c true noecho = @ rm_rf=rm -f cp=/bin/cp -i .phony: all all :: make_structure make_files $(noecho) $(noop) package:: make_xpi $(noecho) $(noop) #install :: make_xpi make_install # $(noecho) $(noop) clean :: make_clean $(noecho)...
...7a-9b95ba6f5640} #seamonkey {92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a} #sunbird {718e30fb-e89b-41dd-9da7-e25a45638b28} #netscape browser {3db10fab-e461-4c80-8b97-957ad5f8ea47} ###### define install_rdf <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <id>$(project_id)</id> <name>$(project_na
me)</name> <version>$(project_version)</version> <description>$(project_desc)</description> <creator>$(project_author)</creator> <contributor>here is a place for you who helped me</contributor> <homepageurl>http://$(project).mozdev.org/</homepageurl> <optionsurl>chrome://$(project)/content/settings.xul</optionsurl> <abouturl>chrome://$(project)/content/about.xul</abouturl> <iconurl>chrome://$(proje...
Monitoring downloads - Archive of obsolete content
var dbconn = this.storageservice.opendatabase(this.dbfile); statement = dbconn.createstatement("replace into items values " + "(?1, ?2, ?3, 0, 0.0, 0)"); statement.bindstringparameter(0, adownload.source.spec); statement.bindint64parameter(1, adownload.size); statement.bindint64parameter(2, adownload.startti
me); statement.execute(); statement.reset(); dbconn.close(); break; // record the completion (whether failed or successful) of the download case components.interfaces.nsidownloadmanager.download_finished: case components.interfaces.nsidownloadmanager.download_failed: case components.interfaces.nsidownloadmanager.download_canceled: this.logtrans...
...e=?2, speed=?3, status=?4 where source=?5 and starttime=?6"); statement.bindint64parameter(0, adownload.size); statement.bindint64parameter(1, endtime.gettime()); statement.binddoubleparameter(2, adownload.speed); statement.bindint32parameter(3, adownload.state); statement.bindstringparameter(4, adownload.source.spec); statement.bindint64parameter(5, adownload.startti
me); statement.execute(); statement.reset(); dbconn.close(); }, this simply opens the database and builds and executes a update sqlite command that finds the download item whose source uri and start time match the download that has completed and updates its information.
Space Manager High Level Design - Archive of obsolete content
during reflow, the space manager stores the space taken up by floats (updatespacemanager in nsblockfra
me) and provides information about the space available for other elements (getavailablespace in nsblockreflowstate).
...bandrects are a linked list (provided by prcliststr super-class) and also provide some geometry-management methods (splitvertically, splithorizontally) and some methods that query or manipulate the frames associated with the band (isoccupiedby, addframe, removefra
me).
Install script template - Archive of obsolete content
* * @param empty param list **/ function createsecondaryinstall() { // use getfolder in such a way that it creates c:\winnt\system32\myplugin secondaryfolder = getfolder("win system", company_na
me); // if secondaryfolder is null, then there has been an error if(!secondaryfolder) return nosecondaryinstall; else { // we have admin privileges to write to the win system directory // so we will set up dll and xpt in their new home errblock2 = addfile (plid, version, plugin_file, secondaryfolder, null); // something went wrong if errblock2 is not 0 if (errblock2!=0) { l...
...errorcode="+myregstatus); return myregstatus; } // write the productname myregstatus = winreg.setvaluestring(mymozillapluginpath, "productname", productna
me); if (myregstatus != 0) { logcomment("moz registerplid: could not write productname.
Sorting and filtering a custom tree view - Archive of obsolete content
1 : -1; //if the column is passed and it's already sorted by that column, reverse sort if (column) { columnname = column.id; if (tree.getattribute("sortresource") == columnna
me) { order *= -1; } } else { columnname = tree.getattribute("sortresource"); } function columnsort(a, b) { if (prepareforcomparison(a[columnname]) > prepareforcomparison(b[columnname])) return 1 * order; if (prepareforcomparison(a[columnname]) < prepareforcomparison(b[columnname])) return -1 * order; //tie breaker: name ascending is the second level sort if (columnname != "name") ...
..."ascending" : "descending"); tree.setattribute("sortresource", columnna
me); tree.view = new treeview(table); //set the appropriate attributes to show to indicator var cols = tree.getelementsbytagname("treecol"); for (var i = 0; i < cols.length; i++) { cols[i].removeattribute("sortdirection"); } document.getelementbyid(columnna
me).setattribute("sortdirection", order == 1 ?
Mozilla release FAQ - Archive of obsolete content
for this particular example, you would want to go look at relevant topics stuart cheshire's discussion on latency versus bandwidth internet -- under the covers (by
me) the rfc for http the w3's html 4.0 definition building mozilla i get x error when trying to build mozilla - what's wrong?
...here are a few representative systems (please send your specs in to
me) removed because the tree has changed enough that we'll probably need new times for all the builds.
NPClass - Archive of obsolete content
function pointer syntax typedef npobject *(*npallocatefunctionptr)(npp npp, npclass *aclass); typedef void (*npdeallocatefunctionptr)(npobject *npobj); typedef void (*npinvalidatefunctionptr)(npobject *npobj); typedef bool (*nphasmethodfunctionptr)(npobject *npobj, npidentifier na
me); typedef bool (*npinvokefunctionptr)(npobject *npobj, npidentifier name, const npvariant *args, uint32_t argcount, npvariant *result); typedef bool (*npinvokedefaultfunctionptr)(npobject *npobj, const npvariant *args, uint32_t argcount, ...
... npvariant *result); typedef bool (*nphaspropertyfunctionptr)(npobject *npobj, npidentifier na
me); typedef bool (*npgetpropertyfunctionptr)(npobject *npobj, npidentifier name, npvariant *result); typedef bool (*npsetpropertyfunctionptr)(npobject *npobj, npidentifier name, const npvariant *value); typedef bool (*npremovepropertyfunctionptr)(npobject *npobj, npidentifier na
me); typedef bool (*npenumerationfunctionptr)(npobject *npobj, npidentifier **value, uint32_t *count); typedef bool (*npconstructfunctionptr)(npobject *npobj, const npvariant *args, ...
NPP_StreamAsFile - Archive of obsolete content
syntax #include <npapi.h> void npp_streamasfile(npp instance, npstream* stream, const char* fna
me); parameters the function has the following parameters: instance pointer to current plug-in instance.
... if an error occurs while retrieving the data or writing the file, the file name (fna
me) is null.
:-moz-system-metric() - Archive of obsolete content
syntax values -moz-windows-compositormedia: media/visual accepts min/max prefixes: no:-moz-system-metric(images-in-menus)the :-moz-system-metric(images-in-menus) css pseudo-class matches an element if the computer's user interface supports images in menus.:-moz-system-metric(mac-graphite-the
me):-moz-system-metric(mac-graphite-the
me) will match an element if the user has chosen the "graphite" appearance in the "appearance" prefpane of the mac os x system preferences.:-moz-system-metric(scrollbar-end-backward)the :-moz-system-metric(scrollbar-end-backward) css pseudo-class will match an element if the computer's user interface includes a backward arrow button at the end of scrollbars.:-mo...
...es proportional scrollbar thumbs; that is, the draggable thumb on the scrollbar resizes to indicate the relative size of the visible area of the document.:-moz-system-metric(touch-enabled)the :-moz-system-metric(touch-enabled) css pseudo-class will match an element if the device on which the content is being rendered offers a supported touch-screen interface.:-moz-system-metric(windows-default-the
me)the :-moz-system-metric(windows-default-the
me) css pseudo-class matches an element if the user is currently using one of the following themes in windows: luna, royale, zune, or aero (i.e., vista basic, vista standard, or aero glass).
Object.prototype.__noSuchMethod__ - Archive of obsolete content
// example base class 1 function namedthing(na
me) { this.name = name; } namedthing.prototype = { getname: function() { return this.name; }, setname: function(newna
me) { this.name = newname; } } // example base class 2 function agedthing(age) { this.age = age; } agedthing.prototype = { getage: function() { return this.age; }, setage: function(age) { this.age = age; } } // child class.
... inherits from namedthing and agedthing // as well as defining address function person(name, age, address){ addparent(this, namedthing.prototype); namedthing.call(this, na
me); addparent(this, agedthing.prototype); agedthing.call(this, age); this.address = address; } person.prototype = { getaddr: function() { return this.address; }, setaddr: function(addr) { this.address = addr; } } var bob = new person('bob', 25, 'new york'); console.log('getage is ' + (('getage' in bob) ?
WebVR — Virtual Reality for the Web - Game development
there are many devices to chose from: desktop ones like oculus rift or htc vive, through consoles with playstation vr (which admittedly doesn't support webvr at this ti
me), to mobile experiences like gear vr or google cardboard.
...for example: function setcustomfov(up,right,down,left) { var testfov = new vrfieldofview(up,right,down,left); ghmd.setfieldofview(testfov,testfov,0.01,10000.0); } the gpositionsensor variable holds the positionsensorvrdevice — using this you can get the current position or orientation state (for example to update the scene view on every fra
me), or reset the sensor.
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
for example: function catname(na
me) { console.log("my cat's name is " + na
me); } catname("tiger"); /* the result of the code above is: "my cat's name is tiger" */ the above code snippet is how you would expect to write the code for it to work.
... now, let's see what happens when we call the function before we write it: catname("chloe"); function catname(na
me) { console.log("my cat's name is " + na
me); } /* the result of the code above is: "my cat's name is chloe" */ even though we call the function in our code first, before the function is written, the code still works.
What software do I need to build a website? - Learn web development
rd-party editor windows notepad notepad++ visual studio code web storm brackets shiftedit sublime text mac os textedit textwrangler visual studio code brackets shiftedit sublime text linux vi (all unix) gedit (gno
me) kate (kde) leafpad (xfce) emacs vim visual studio code brackets shiftedit sublime text chrome os shiftedit here is a screenshot of an advanced text editor: here is a screenshot of an online text editor: uploading files on the web when your website is ready for public viewing, you'...
...for now, here's a short list of free basic (s)ftp clients: operating system ftp software windows winscp moba xterm filezilla (all os) linux nautilus/files (gno
me) dolphin (kde) mac os cyberduck chrome os shiftedit (all os) browsing websites as you already know, you need a web browser to view websites.
JavaScript basics - Learn web development
function setusername() { let myname = prompt('please enter your name.'); localstorage.setitem('name', myna
me); myheading.textcontent = 'mozilla is cool, ' + myname; } the setusername() function contains a prompt() function, which displays a dialog box, similar to alert().
...update your setusername() function to this: function setusername() { let myname = prompt('please enter your name.'); if(!myna
me) { setusername(); } else { localstorage.setitem('name', myna
me); myheading.innerhtml = 'mozilla is cool, ' + myname; } } in human language, this means: if myname has no value, run setusername() again from the start.
What’s in the head? Metadata in HTML - Learn web development
chro
me) automatically fix incorrect encodings, so depending on what browser you use, you may not see this problem anyway.
...it will look something like this (although it may change over ti
me): <meta name="description" content="the mdn web docs site provides information about open web technologies including html, css, and apis for both web sites and progressive web apps."> now search for "mdn web docs" in your favorite search engine (we used google.) you'll notice the description <meta> and <title> element content used in the search result — definitely worth having!
Looping code - Learn web development
para = document.queryselector('p'); const input = document.queryselector('input'); const btn = document.queryselector('button'); btn.addeventlistener('click', function() { let searchname = input.value.tolowercase(); input.value = ''; input.focus(); for (let i = 0; i < contacts.length; i++) { let splitcontact = contacts[i].split(':'); if (splitcontact[0].tolowercase() === searchna
me) { para.textcontent = splitcontact[0] + '\'s number is ' + splitcontact[1] + '.'; break; } else { para.textcontent = 'contact not found.'; } } }); hidden code 3 <!doctype html> <html> <head> <meta charset="utf-8"> <title>simple contact search example</title> <style> </style> </head> <body> <label for="search">search by contact name: </label>...
... const input = document.queryselector('input'); const btn = document.queryselector('button'); btn.addeventlistener('click', function() { let searchname = input.value.tolowercase(); input.value = ''; input.focus(); for (let i = 0; i < contacts.length; i++) { let splitcontact = contacts[i].split(':'); if (splitcontact[0].tolowercase() === searchna
me) { para.textcontent = splitcontact[0] + '\'s number is ' + splitcontact[1] + '.'; break; } else if (i === contacts.length-1) para.textcontent = 'contact not found.'; } }); </script> </body> </html> first of all we have some variable definitions — we have an array of contact information, with each item being a string containing a ...
What is JavaScript? - Learn web development
enter; border: 2px solid rgba(0,0,200,0.6); background: rgba(0,0,200,0.3); color: rgba(0,0,200,0.6); box-shadow: 1px 1px 2px rgba(0,0,200,0.4); border-radius: 10px; padding: 3px 10px; display: inline-block; cursor: pointer; } and finally, we can add some javascript to implement dynamic behaviour: const para = document.queryselector('p'); para.addeventlistener('click', updatena
me); function updatename() { let name = prompt('enter a new name'); para.textcontent = 'player 1: ' + name; } try clicking on this last version of the text label to see what happens (note also that you can find this demo on github — see the source code, or run it live)!
...for example, let's return to the block of javascript we saw in our first example: const para = document.queryselector('p'); para.addeventlistener('click', updatena
me); function updatename() { let name = prompt('enter a new name'); para.textcontent = 'player 1: ' + name; } here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the updatename() code block (lines 5–8) is run.
Introduction to client-side frameworks - Learn web development
that could look something like this: function buildtodoitemel(id, na
me) { const item = document.createelement('li'); const span = document.createelement('span'); const textcontent = document.createtextnode(na
me); span.appendchild(textcontent) item.id = id; item.appendchild(span); item.appendchild(builddeletebuttonel(id)); return item; } here, we use the document.createelement() method to make our <li>, and several more lines of code to create the ...
...the code that will render our items on the page might read something like this: function rendertodolist() { const frag = document.createdocumentfragment(); state.tasks.foreach(task => { const item = buildtodoitemel(task.id, task.na
me); frag.appendchild(item); }); while (todolistel.firstchild) { todolistel.removechild(todolistel.firstchild); } todolistel.appendchild(frag); } we've now got well over thirty lines of code dedicated just to the ui – just to the step of rendering something in the dom – and at no point do we add classes that we could use later to style our list-items!
Working with Svelte stores - Learn web development
add the following import statement below the existing ones: import { alert } from '../stores.js' update your addtodo() function like so: function addtodo(na
me) { todos = [...todos, { id: newtodoid, name, completed: false }] $alert = `todo '${name}' has been added` } update removetodo() like so: function removetodo(todo) { todos = todos.filter(t => t.id !== todo.id) todosstatus.focus() // give focus to status heading $alert = `todo '${todo.name}' has been deleted` } update the updatetodo() function to this: funct...
...ion updatetodo(todo) { const i = todos.findindex(t => t.id === todo.id) if (todos[i].name !== todo.na
me) $alert = `todo '${todos[i].name}' has been renamed to '${todo.name}'` if (todos[i].completed !== todo.completed) $alert = `todo '${todos[i].name}' marked as ${todo.completed ?
Theme concepts
defining a theme to create a theme (in this example a simple, single image the
me): create a folder in a suitable location on your computer.
... 'sun.jpg', }, colors: { frame: '#cf723f', tab_background_text: '#111', } }, 'night': { images: { theme_frame: 'moon.jpg', }, colors: { frame: '#000', tab_background_text: '#fff', } } }; the theme.theme object is then passed to theme.update() to change the header theme, as in this code snippet from the same example: function settheme(the
me) { if (currenttheme === the
me) { // no point in changing the theme if it has already been set.
The Firefox codebase: CSS Guidelines
writing media queries boolean media queries do this: @media (-moz-mac-yosemite-theme: 0) { not this: @media not all and (-moz-mac-yosemite-the
me) { privilege css for most common configuration it is better to put the most common configuration (latest version of an os, or default theme for example) outside of the media query.
... do this: @media (-moz-mac-yosemite-theme: 0) { #placeslist { box-shadow: inset -2px 0 0 hsla(0,0%,100%,.2); } } not this: #placeslist { box-shadow: inset -2px 0 0 hsla(0,0%,100%,.2); } @media (-moz-mac-yosemite-the
me) { #placeslist { box-shadow: none; } } theme support firefox comes built-in with 3 themes: default, light and dark.
Communicating with frame scripts
objects an object whose properties are any cpows exposed by the sender as the third argument to sendasyncmessage() in the example below the listener just logs all the messages details: // chrome script messagemanager.addmessagelistener("my-addon@me.org:my-e10s-extension-message", listener); function listener(message) { console.log(message.na
me); console.log(message.sync); console.log(message.data); console.log(message.target); console.log(message.objects); } so combining this message listener with the message above will give console output somewhat like this, when the user clicks a <div>: "my-addon@me.org:my-e10s-extension-message" false object { details: "they clicked", tag: "div" } <xul:browser anonid="initialbrowser" ...
...the listener will be passed a message object whose data property is the message payload: // frame script function handlemessagefromchrome(message) { var payload = message.data.details; // "some more details" } addmessagelistener("my-addon@me.org:message-from-chrome", handlemessagefromchro
me); message-manager-disconnect if you're using a message manager to communicate with a script that may be running in a different process, you can listen for the message-manager-disconnect observer notification to know when the message manager has disconnected from the other end of the conversation, so you can stop sending it messages or expecting to receive messages.
Message manager overview
in multiprocess firefox there are (at least) two processes: the chrome process, also called the parent process, runs the browser ui (chro
me) code and code inserted by extensions one or more content processes, also called child processes.
... process message managers: these correspond to process boundaries, and enable code running in the parent (chro
me) process to communicate with code running in the child (content) process.
Message manager overview
in the initial version of multiprocess firefox there are two processes: the chrome process, also called the parent process, runs the browser ui (chro
me) code and code inserted by extensions the content processes, also called the child processes, run all web content.
... process message managers: these correspond to process boundaries, and enable code running in the parent (chro
me) process to communicate with code running in the child (content) process.
HTMLIFrameElement.getVolume()
syntax there are two versions of this method, a callback version: var request = instanceofhtmliframeelement.getvolume(); and a promise version: instanceofhtmliframeelement.getvolume().then(function(volu
me) { ...
... example callback version: var browser = document.queryselector('iframe'); var request = browser.getvolume(); request.onsuccess = function() { console.log('the current browser volume is ' + request.result); } promise version: var browser = document.queryselector('iframe'); browser.getvolume().then(function(volu
me) { console.log('the current browser volume is ' + volu
me); }); specification not part of any specification.
JNI.jsm
text', sig: '()' + sig.context }] }); var context = jni.loadclass(my_jenv, fullyqualifiednameofclass(sig.context), { methods: [ { /* http://developer.android.com/reference/android/content/context.html#getsystemservice%28java.lang.class%3ct%3e%29 * public abstract object getsystemservice (string na
me) */ name: 'getsystemservice', sig: genmethodsig([ sig.string // name ], sig.object // return ) }], static_fields: [ { name: 'window_service', sig: sig.string } // http://devel...
...(); // object { js#obj: cdata } var javastr_dirextstorepath = javafile_dirextstore.getpath(); // object { js#obj: cdata } var jsstr_dirextstorepath = jni.readstring(my_jenv, javastr_dirextstorepath); // "/mnt/sdcard" var jsstr_dirpicsname = jni.readstring(my_jenv, environment.directory_pictures); // "pictures" var jsstr_dirpics = os.path.join(jsstr_dirextstorepath, jsstr_dirpicsna
me); // "/mnt/sdcard/pictures" } finally { if (my_jenv) { jni.unloadclasses(my_jenv); } } example 2 blah blah blah code here ...
Sqlite.jsm
tableexists(na
me) this function determines whether a table exists in the current database.
... indexexists(na
me) this functions determines whether a named index exists in the current database.
Mozilla DOM Hacking Guide
union { nsdomclassinfoconstructorfnc mconstructorfptr; nsdomclassinfoexternalconstructorfnc mexternalconstructorfptr; } u; this union is a pointer to a function typedef'ed: typedef nsiclassinfo* (*nsdomclassinfoconstructorfnc)(nsdomclassinfoid aid); or typedef nsiclassinfo* (*nsdomclassinfoexternalconstructorfnc) (const char* ana
me); it is initialized with the docreate member function of the helper class passed as third argument to the macro.
...add the following line at the end of the queryinterface implementation: ns_interface_map_entry_content_classinfo(dom_object_na
me) for the domimplementation object, the line would be: ns_interface_map_entry_content_classinfo(domimplementation) what does it do?
AsyncTestUtils extended framework
folders create a folder let folderhandle = make_empty_folder(aoptionalfolderna
me); you do not have to specify a folder name - if you don't care, we'll make one up for you.
...er let junkfolder = get_junk_folder(); create a virtual folder (a folder whose contents are the result of a saved search) let virtualfolder = make_virtual_folder([afoldertosearch1, afoldertosearch2, ...], {subject: "", body: "", from: "", to: "", cc: "", recipient: "", involves: ""}, aandtermstogether, aoptionalna
me); this is a convenience function to help you create a new virtual folder.
PR_Bind
pr_bind assigns the specified address (also known as na
me) to the socket.
... call pr_getsockname to obtain the address (na
me) bound to a socket.
Index
* returns null if the name is not a supported algorithm */ static secoidtag hashnametooidtag(const char *hashna
me) { int i, nhashes = sizeof(hash_names); secoidtag hashtag = sec_oid_unknown; for (i = 0; i < nhashes; i++) { if (port_strcasecmp(hashname, hash_names[i].hashna
me) == 0) { hashtag = hash_names[i].oid; break; } } return hashtag; } /* newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* ...
... 338 python binding for nss python-nss is a python binding for nss (network security services) and nspr (netscape portable runti
me).
NSS Sample Code Sample_2_Initialization of NSS
sample code 1 /* nspr headers */ #include <prthread.h> #include <plgetopt.h> #include <prprf.h> /* nss headers */ #include <nss.h> #include <pk11func.h> #include "util.h" /* print a usage message and exit */ static void usage(const char *progna
me) { fprintf(stderr, "\nusage: %s -d <dbdirpath> [-p <plainpasswc>]" " [-f <passwdffile>]\n\n", progna
me); fprintf(stderr, "%-15s specify a db directory path\n\n", "-d <dbdirpath>"); fprintf(stderr, "%-15s specify a plaintext password\n\n", "-p <plainpasswc>"); fprintf(stderr, "%-15s specify a password file\n\n", ...
...); while ((status = pl_getnextopt(optstate)) == pl_opt_ok) { switch (optstate->option) { case 'd': dbdir = strdup(optstate->value); break; case 'p': plainpass = strdup(optstate->value); break; case 'f': pwfile = strdup(optstate->value); break; default: usage(progna
me); break; } } pl_destroyoptstate(optstate); if (!dbdir) usage(progna
me); pr_init(pr_user_thread, pr_priority_normal, 0); /* create the database */ rv = nss_initreadwrite(dbdir); if (rv != secsuccess) { pr_fprintf(pr_stderr, "nss_initialize failed"); pr_cleanup(); exit(rv); } if (pl_strcmp(slotname, "interna...
Initialize NSS database - sample 2
/* * print a usage message and exit */ static void usage(const char *progna
me) { fprintf(stderr, "\nusage: %s -d [-p ]" " [-f ]\n\n", progna
me); fprintf(stderr, "%-15s specify a db directory path\n\n", "-d "); fprintf(stderr, "%-15s specify a plaintext password\n\n", "-p "); fprintf(stderr, "%-15s specify a password file\n\n", "-f "); exit(-1); } /* * initslotpassword */ char * initslotpassword(pk11slotinfo *slot, prbool retry, void *arg) { file *input; file *output; char *p0 = null; char *p1 = null; ...
...); while ((status = pl_getnextopt(optstate)) == pl_opt_ok) { switch (optstate->option) { case 'd': dbdir = strdup(optstate->value); break; case 'p': plainpass = strdup(optstate->value); break; case 'f': pwfile = strdup(optstate->value); break; default: usage(progna
me); break; } } pl_destroyoptstate(optstate); if (!dbdir) usage(progna
me); pr_init(pr_user_thread, pr_priority_normal, 0); /* create the database */ rv = nss_initreadwrite(dbdir); if (rv != secsuccess) { pr_fprintf(pr_stderr, "nss_initialize failed"); pr_cleanup(); exit(rv); } if (pl_strcmp(slotname, "interna...
nss tech note4
cert->subjectname (char*) cert->issuername (char*) cert->emailaddr (char*) or char *cert_getcertificateemailaddress(certcertificate *cert); cert->keyusage (unsigned int) to break the issuer and subject names into components pass &(cert->issuer) or &(cert->subject) to the following functions char *cert_getcommonname(certname *na
me); char *cert_getcertemailaddress(certname *na
me); char *cert_getcountryname(certname *na
me); char *cert_getlocalityname(certname *na
me); char *cert_getstatename(certname *na
me); char *cert_getorgname(certname *na
me); char *cert_getorgunitname(certname *na
me); char *cert_getdomaincomponentname(certname *na
me); char *cert_getcertuid(certname *n...
...a
me); example code to illustrate access to the info is given below.
sslcrt.html
syntax #include <cert.h> secstatus cert_verifycertname( certcertificate *cert, char *hostna
me); parameters this function has the following parameters: cert a pointer to the certificate against which to check the hostname referenced by hostname.
... syntax #include <cert.h> certcertificate *cert_findcertbyname ( certcertdbhandle *handle, secitem *na
me); parameters this function has the following parameters: handle a pointer to the certificate database handle.
Multithreading in Necko
file, finger, dateti
me) do not worry about threading issues.
...the default implementation does not spawn a worker thread, and instead simply calls pr_getipnodebyname (essentially equivalent to gethostbyna
me).
Scripting Java
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, methodna
me) { 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()...
...the instanceof operator can be used to query the type of an exception: try { java.lang.class.forname("nonexistingclass"); } catch (e) { if (e.javaexception instanceof java.lang.classnotfoundexception) { print("class not found"); } } rhino also supports an extension to the try...catch statement that allows to define conditional catching of exceptions: function classforname(na
me) { try { return java.lang.class.forname(na
me); } catch (e if e.javaexception instanceof java.lang.classnotfoundexception) { print("class " + name + " not found"); } catch (e if e.javaexception instanceof java.lang.nullpointerexception) { print("class name is null"); } } classforname("nonexistingclass"); classforname(null); ...
Rhino serialization
writing an object to a file can be done in a few lines of java code: fileoutputstream fos = new fileoutputstream(filena
me); scriptableoutputstream out = new scriptableoutputstream(fos, scope); out.writeobject(obj); out.close(); here filename is the file to write to, obj is the object or function to write, and scope is the top-level scope containing obj.
... reading the serialized object back into memory is similarly simple: fileinputstream fis = new fileinputstream(filena
me); objectinputstream in = new scriptableinputstream(fis, scope); object deserialized = in.readobject(); in.close(); again, we need the scope to create our serialization stream class.
GC Rooting Guide
the usual way is to define a void trace(jstracer* trc, const char* na
me) method on the class -- which is already enough be able to create a js::rooted<yourstruct> on the stack -- and then arrange for it to be called during tracing.
... static void trace(jstracer* trc, jsobject* obj) { myclass* mine = static_cast<myclass*>(obj->getprivate()); mine->trace(trc, "myclass private field"); } } class myclass { heap<jsstring*> str; public: void trace(jstracer* trc, const char* na
me) { js::traceedge(trc, &str, "my string"); } } if a pointer to your structure is stored in some other structure, then its trace() method should invoke yours: struct myowningstruct { myclass* mything; void trace(jstracer* trc, const char* na
me) { if (mything) mything->trace(trc, "my thing"); } } if the toplevel structure is not stored in a jsobject, t...
JS::Add*Root
syntax bool js::addvalueroot(jscontext *cx, js::heap<js::value> *vp); bool js::addstringroot(jscontext *cx, js::heap<jsstring *> *rp); bool js::addobjectroot(jscontext *cx, js::heap<jsobject *> *rp); bool js::addnamedvalueroot(jscontext *cx, js::heap<js::value> *vp, const char *na
me); bool js::addnamedvaluerootrt(jsruntime *rt, js::heap<js::value> *vp, const char *na
me); bool js::addnamedstringroot(jscontext *cx, js::heap<jsstring *> *rp, const char *na
me); bool js::addnamedobjectroot(jscontext *cx, js::heap<jsobject *> *rp, const char *na
me); bool js::addnamedscriptroot(jscontext *cx, js::heap<jsscript...
... *> *rp, const char *na
me); name type description cx jscontext * the context in which to add the new root.
JS_FS
// added in spidermonkey 38 #define js_sym_fnspec(symbol, call, info, nargs, flags, selfhostedna
me) ...
... // added in spidermonkey 38 #define js_fnspec(name,call,info,nargs,flags,selfhostedna
me) ...
JS_LookupProperty
otherwise, flags must be the logical or of one or more of the following bits: jsresolve_qualified behave as though the property name appeared to the right of a dot, as in alert(obj.na
me).
... jsresolve_detecting behave as though the name appeared in an idiom like "if (obj.na
me) ..." or "obj.name ?
Shell global objects
internalconst(na
me) query an internal constant for the engine.
... getmoduleenvironmentvalue(module, na
me) get the value of a bound name in a module environment.
extIPreferenceBranch
method overview boolean has(in astring ana
me) extipreference get(in astring ana
me) nsivariant getvalue(in astring aname, in nsivariant adefaultvalue) void setvalue(in astring aname, in nsivariant avalue) void reset() attributes attribute type description root readonly attribute astring the name of the branch root.
... boolean has(in astring ana
me) 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 ana
me) 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.
extISessionStorage
return type method boolean has(in astring ana
me) void set(in astring aname, in nsivariant avalue) nsivariant get(in astring aname, in nsivariant adefaultvalue) attributes attribute type description events readonly attribute extievents the events object for the storage supports: "change" methods has() determines if a storage item exists with the given name.
... boolean has(in astring ana
me) parameters aname the name of an item return value true if an item exists with the given name, false otherwise.
Accessing the Windows Registry Using XPCOM
var wrk = components.classes["@mozilla.org/windows-registry-key;1"] .createinstance(components.interfaces.nsiwindowsregkey); wrk.open(wrk.root_key_local_machine, "software\\microsoft\\windows\\currentversion\\run", wrk.access_read); for (var i=0; i<wrk.valuecount; i++) { var name = wrk.getvaluename(i); var value = readregistryvalue(wrk, na
me); // do something interesting here...
... function removechildrenrecursive(wrk) { // we count backwards because we're removing them as we go for (var i = wrk.childcount - 1; i >= 0; i--) { var name = wrk.getchildname(i); var subkey = wrk.openchild(name, wrk.access_all); removechildrenrecursive(subkey); subkey.close(); wrk.removechild(na
me); } } var wrk = components.classes["@mozilla.org/windows-registry-key;1"] .createinstance(components.interfaces.nsiwindowsregkey); wrk.open(wrk.root_key_current_user, "software\\mdc\\test", wrk.access_all); removechildrenrecursive(wrk); wrk.close(); monitoring registry keys if you would like to know whether a registry key has changed since you last check...
Finishing the Component
the string comparison with the url type "http", "https", and "ftp" looks like this: nsembedcstring scheme; contentlocation->getscheme(sche
me); 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.
... here is the complete implementation of the shouldload() method: ns_imethodimp weblock::shouldload(print32 contenttype, nsiuri *contentlocation, nsisupports *ctxt, nsidomwindow *window, prbool *_retval) { if (!contentlocation) return ns_error_failure; nsembedcstring scheme; contentlocation->getscheme(sche
me); 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; } nsembedcstring hosttoload; contentlocation->gethost(hosttoload); // assume failure.
Setting up the Gecko SDK
*/ nsstring mname; }; #endif cspecialthing.cpp #include "cspecialthing.h" ns_impl_isupports1(cspecialthing, ispecialthing) cspecialthing::cspecialthing() { /* member initializers and constructor code */ mname.assign(l"default name"); } cspecialthing::~cspecialthing() { /* destructor code */ } /* attribute astring name; */ ns_imethodimp cspecialthing::getname(nsastring & ana
me) { aname.assign(mna
me); return ns_ok; } ns_imethodimp cspecialthing::setname(const nsastring & ana
me) { mname.assign(ana
me); return ns_ok; } /* long add (in long a, in long b); */ ns_imethodimp cspecialthing::add(print32 a, print32 b, print32 *_retval) { *_retval = a + b; return ns_ok; } this is generally your code.
...gecko_sdk_path ?= $(ho
me)/tmp/xr xpidl ?= $(gecko_sdk_path)/bin/xpidl cxx ?= c++ xpidlsrcs = \ interfacea.idl \ interfaceb.idl \ $(null) cppsrcs = \ sourcea.cpp \ sourceb.cpp \ $(null) cppflags += -fno-rtti \ -fno-exceptions \ -fshort-wchar \ -fpic \ $(null) # gcc only define which allows us to not have to #include mozilla-config # in every .cpp...
How to build a binary XPCOM component using Visual Studio
: /* additional members */ nsstring mname; }; #endif cpp file: #include "comp-impl.h" ns_impl_isupports1(cspecialthing, ispecialthing) cspecialthing::cspecialthing() { /* member initializers and constructor code */ mname.assign(l"default name"); } cspecialthing::~cspecialthing() { /* destructor code */ } /* attribute astring name; */ ns_imethodimp cspecialthing::getname(nsastring & ana
me) { aname.assign(mna
me); return ns_ok; } ns_imethodimp cspecialthing::setname(const nsastring & ana
me) { mname.assign(ana
me); return ns_ok; } /* long add (in long a, in long b); */ ns_imethodimp cspecialthing::add(print32 a, print32 b, print32 *_retval) { *_retval = a + b; return ns_ok; } lastly, we need to create the module implementation.
... use in javascript: function doxpcom() { try { const cid = "@starkravingfinkle.org/specialthing;1"; var obj = components.classes[cid].createinstance(); obj = obj.queryinterface(components.interfaces.ispecialthing); } catch (err) { alert(err); return; } var res = obj.add(3, 4); alert('3+4 = ' + res); var name = obj.name; alert('name = ' + na
me); obj.name = 'new name'; name = obj.name; alert('name = ' + na
me); } other resources creating xpcom components - mozilla how to build an xpcom component in javascript - mozilla an introduction to xpcom - ibm xpcom project page - mozilla ...
Index
264 getactiondescription this method retrieves the description (localized na
me) of the accessible action at the given zero-based index.
... 664 nsiframeloader interfaces, interfaces:scriptable, xpcom, xpcom interface reference activates event forwarding from client (remote fra
me) to parent.
Components.classes
the properties of this object are indexed by the contractid (or human-readable na
me) of the component class.
... to access a service (a singleton component, only single instance of which exists at any ti
me), you should use getservice instead of createinstance: var os = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); the first time anyone accesses a service, the corresponding component is created under the hood.
XPCShell Reference
gc(heapdumpfilena
me) gc() will invoke garbage collection.
... load(scriptfilena
me) load() allows you to load and run a script from the command line.
inIDOMUtils
as a service: var inidomutils = components.classes["@mozilla.org/inspector/dom-utils;1"] .getservice(components.interfaces.inidomutils); method overview void addpseudoclasslock(in nsidomelement aelement, in domstring apseudoclass); void clearpseudoclasslocks(in nsidomelement aelement); [implicit_jscontext] jsval colornametorgb(in domstring acolorna
me); nsiarray getbindingurls(in nsidomelement aelement); nsidomnodelist getchildrenfornode(in nsidomnode anode, in boolean ashowinganonymouscontent); unsigned long long getcontentstate(in nsidomelement aelement); void getcsspropertynames([optional] in unsigned long aflags, [optional] out unsigned long acount, [retval, array, size_is(acount)] out wstring aprops); ...
...dex); unsigned long long getspecificity(in nsidomcssstylerule arule, in unsigned long aselectorindex); nsidomfontfacelist getusedfontfaces(in nsidomrange arange); bool haspseudoclasslock(in nsidomelement aelement, in domstring apseudoclass); boolean isignorablewhitespace(in nsidomcharacterdata adatanode); bool isinheritedproperty(in astring apropertyna
me); void parsestylesheet(in nsidomcssstylesheet asheet, in domstring ainput); void removepseudoclasslock(in nsidomelement aelement, in domstring apseudoclass); astring rgbtocolorname(in octet ar, in octet ag, in octet ab); bool selectormatcheselement(in nsidomelement aelement, in nsidomcssstylerule arule, in unsigned long aselectorindex, [optional] in domstring a...
mozIStorageConnection
void createtable(in string atablename, in string atableschema); mozistoragependingstatement executeasync([array, size_is(anumstatements)] in mozistoragebasestatement astatements, in unsigned long anumstatements, [optional] in mozistoragestatementcallback acallback ); void executesimplesql(in autf8string asqlstatement); boolean indexexists(in autf8string aindexna
me); void preload(); obsolete since gecko 1.9 void removefunction(in autf8string afunctionna
me); mozistorageprogresshandler removeprogresshandler(); void rollbacktransaction(); void setgrowthincrement(in print32 aincrement, in autf8string adatabasena
me); mozistorageprogresshandler setprogresshandler(in print32 agranularity, in mozistorageprogre...
...sshandler ahandler); boolean tableexists(in autf8string atablena
me); attributes attribute type description connectionready boolean indicates if the connection is open and ready to use.
nsIAbCard
inherits from: nsisupports method overview astring getcardvalue(in string na
me) void setcardvalue(in string attrname, in astring value) void copy(in nsiabcard srccard) boolean equals(in nsiabcard card) string converttobase64encodedxml() astring converttoxmlprintdata() string converttoescapedvcard() astring generatename(in long agenerateformat,[optional] in nsistringbundle abundle) astring generatephoneti...
... allowremotecontent boolean allow remote content to be displayed in html mail received from this contact methods getcardvalue() astring getcardvalue(in string na
me) parameters name the attribute you want the value for.
nsIDOMElement
inherits from: nsidomnode last changed in gecko 1.7 method overview domstring getattribute(in domstring na
me); nsidomattr getattributenode(in domstring na
me); nsidomattr getattributenodens(in domstring namespaceuri, in domstring localna
me); domstring getattributens(in domstring namespaceuri, in domstring localna
me); nsidomnodelist getelementsbytagname(in domstring na
me); nsidomnodelist getelementsbytagnamens(in domstring namespaceuri, in domstring localna
me); boolean hasattribute(in domstring na
me); boolean hasattributens(in domstring namespaceuri, in domstring localna
me); void removeattribute(in domstring na
me) nsidomattr removeattributenode(in...
... nsidomattr oldattr) void removeattributens(in domstring namespaceuri, in domstring localna
me) void setattribute(in domstring name, in domstring value) nsidomattr setattributenode(in nsidomattr newattr) nsidomattr setattributenodens(in nsidomattr newattr) void setattributens(in domstring namespaceuri, in domstring qualifiedname, in domstring value) attributes attribute type description tagname domstring the element tag name.
nsIFrameLoader
void loadframe(); void loaduri(in nsiuri auri); void sendcrossprocesskeyevent(in astring atype, in long akeycode, in long acharcode, in long amodifiers, [optional] in boolean apreventdefault); void sendcrossprocessmouseevent(in astring atype, in float ax, in float ay, in long abutton, in long aclickcount, in long amodifiers, [optional] in boolean aignorerootscrollfra
me); void updatepositionandsize(in nsiframe aifra
me); native code only!
... methods activateframeevent() activates event forwarding from client (remote fra
me) to parent.
nsIHTMLEditor
gn); boolean breakisvisible(in nsidomnode anode); boolean candrag(in nsidomevent aevent); void checkselectionstateforanonymousbuttons(in nsiselection aselection); nsidomelement createanonymouselement(in astring atag, in nsidomnode aparentnode, in astring aanonclass, in boolean aiscreatedhidden); nsidomelement createelementwithdefaults(in astring atagna
me); void decreasefontsize(); void dodrag(in nsidomevent aevent); void getalignment(out boolean amixed, out short aalign); astring getbackgroundcolorstate(out boolean amixed); nsidomelement getelementorparentbytagname(in astring atagname, in nsidomnode anode); astring getfontcolorstate(out boolean amixed); astring getfontfacestate(out boo...
...out boolean aany, out boolean aall); nsisupportsarray getlinkedobjects(); void getlistitemstate(out boolean amixed, out boolean ali, out boolean adt, out boolean add); void getliststate(out boolean amixed, out boolean aol, out boolean aul, out boolean adl); astring getparagraphstate(out boolean amixed); nsidomelement getselectedelement(in astring atagna
me); nsidomelement getselectioncontainer(); void ignorespuriousdragevent(in boolean aignorespuriousdragevent); void increasefontsize(); void indent(in astring aindent); void insertelementatselection(in nsidomelement aelement, in boolean adeleteselection); void insertfromdrop(in nsidomevent aevent); void inserthtml(in astring ainputstring)...
nsIIOService
implemented by @mozilla.org/network/io-service;1 as a service: var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); method overview boolean allowport(in long aport, in string asche
me); acstring extractscheme(in autf8string urlstring); unsigned long getprotocolflags(in string asche
me); nsiprotocolhandler getprotocolhandler(in string asche
me); nsichannel newchannel(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); obsolete since gecko 48 nsichannel newchannel2(in autf8string aspec, in string aorigincharset, in nsiur...
...if the given port is considered unsafe, then the protocol handler (corresponding to asche
me) will be asked whether it wishes to override the io service's decision to block the port.
nsIIdleService
to create an instance, use: var idleservice = components.classes["@mozilla.org/widget/idleservice;1"] .getservice(components.interfaces.nsiidleservice); method overview void addidleobserver(in nsiobserver observer, in unsigned long ti
me); void removeidleobserver(in nsiobserver observer, in unsigned long ti
me); attributes attribute type description idletime unsigned long the amount of time in milliseconds that has passed since the last user activity.
... example example 1 var idleservice = components.classes["@mozilla.org/widget/idleservice;1"] .getservice(components.interfaces.nsiidleservice) settimeout(function() { alert(idleservice.idleti
me) }, 1000) // if you don't use the mouse or the keyboard after running this snippet, // you'll see a number around 1000 alerted.
nsIMimeConverter
decodemimeheader() string getstringproperty(in string propertyna
me); parameters propertyname the name of the property to retrieve.
... unsigned long getuint32property(in string propertyna
me); parameters propertyname the name of the property to retrieve.
nsIMsgIncomingServer
guretemporaryfilters(in nsimsgfilterlist filterlist); void configuretemporaryreturnreceiptsfilter(in nsimsgfilterlist filterlist); obsolete since gecko 1.8 void displayofflinemsg(in nsimsgwindow awindow); boolean equals(in nsimsgincomingserver server); void forgetpassword(); void forgetsessionpassword(); astring generateprettynameformigration(); boolean getboolattribute(in string na
me); boolean getboolvalue(in string attr); acstring getcharattribute(in string na
me); acstring getcharvalue(in string attr); nsilocalfile getfilevalue(in string relpref, in string abspref); nsimsgfilterlist getfilterlist(in nsimsgwindow amsgwindow); long getintattribute(in string na
me); long getintvalue(in string attr); nsimsgfolder getmsgfolderfromuri(in nsimsgfolder afolderresource,...
... in acstring auri); void getnewmessages(in nsimsgfolder afolder, in nsimsgwindow amsgwindow, in nsiurllistener aurllistener); acstring getpasswordwithui(in astring apromptstring, in astring aprompttitle, in nsimsgwindow amsgwindow, out boolean okayvalue); astring getunicharattribute(in string na
me); astring getunicharvalue(in string attr); boolean isnewhdrduplicate(in nsimsgdbhdr anewhdr); void onuserorhostnamechanged(in acstring oldname, in acstring newna
me); void performbiff(in nsimsgwindow amsgwindow); void performexpand(in nsimsgwindow amsgwindow); void removefiles(); void setboolattribute(in string name, in boolean value); void setboolvalue(in string attr, in boolean value); void setcharattribute(in string name, in acstring value); void setcharvalue(in string ...
nsIPluginHost
void createtmpfiletopost(in string apostdataurl, out string atmpfilena
me); native code only!
...obsolete since gecko 1.9.2 void getpluginname(in nsiplugininstance ainstance, [shared] out string apluginna
me); native code only!
nsIProfile
method overview void cloneprofile(in wstring profilena
me); void createnewprofile(in wstring profilename, in wstring nativeprofiledir, in wstring langcode, in boolean useexistingdir); void deleteprofile(in wstring name, in boolean candeletefiles); void getprofilelist(out unsigned long length, [retval, array, size_is(length)] out wstring profilenames); boolean profileexists(in wstring profilena
me); void renamep...
...rofile(in wstring oldname, in wstring newna
me); void shutdowncurrentprofile(in unsigned long shutdowntype); attributes attribute type description currentprofile wstring the name of the profile currently in use.
nsITaggingService
tags); nsivariant geturisfortag(in astring atag); nsivariant gettagsforuri(in nsiuri auri, [optional] out unsigned long length, [retval, array, size_is(length)] out wstring atags); attributes attribute type description alltags nsivariant retrieves all tags used to tag uris in the data-base (sorted by na
me).
... return value returns array of tags (sorted by na
me).
nsITextInputProcessor
omkeyevent adomkeyevent, [optional] in unsigned long akeyflags); boolean commitcompositionwith(in domstring acommitstring, [optional] in nsidomkeyevent adomkeyevent, [optional] in unsigned long akeyflags); boolean flushpendingcomposition([optional] in nsidomkeyevent adomkeyevent, [optional] in unsigned long akeyflags); boolean getmodifierstate(in domstring amodifierkeyna
me); boolean keydown([optional] in nsidomkeyevent adomkeyevent, [optional] in unsigned long akeyflags); boolean keyup([optional] in nsidomkeyevent adomkeyevent, [optional] in unsigned long akeyflags); void setcaretinpendingcomposition(in unsigned long aoffset); void setpendingcompositionstring(in domstring astring); void sharemodifierstateof(in nsitextinpu...
... boolean getmodifierstate(in domstring amodifierkeyna
me); parameters amodifierkeyname a modifier key name which is defined by dom level 3 keyboardevents key values.
nsIWindowsRegKey
method overview void close(); void create(in unsigned long rootkey, in astring relpath, in unsigned long mode); nsiwindowsregkey createchild(in astring relpath, in unsigned long mode); astring getchildname(in unsigned long index); astring getvaluename(in unsigned long index); unsigned long getvaluetype(in astring na
me); boolean haschanged(); boolean haschild(in astring na
me); boolean hasvalue(in astring na
me); boolean iswatching(); void open(in unsigned long rootkey, in astring relpath, in unsigned long mode); nsiwindowsregkey openchild(in astring relpath, in unsigned long mode); acstring readbinaryvalue(in astring na
me); unsigned long long...
... readint64value(in astring na
me); unsigned long readintvalue(in astring na
me); astring readstringvalue(in astring na
me); void removechild(in astring relpath); void removevalue(in astring na
me); void startwatching(in boolean recurse); void stopwatching(); void writebinaryvalue(in astring name, in acstring data); void writeint64value(in astring name, in unsigned long long data); void writeintvalue(in astring name, in unsigned long data); void writestringvalue(in astring name, in astring data); attributes attribute type description childcount unsigned long this attribute returns the number of child keys.
nsIZipReader
void close(); void extract(in autf8string zipentry, in nsifile outfile); void extract(in string zipentry, in nsifile outfile); obsolete since gecko 10 nsiutf8stringenumerator findentries(in autf8string apattern); nsiutf8stringenumerator findentries(in string apattern); obsolete since gecko 10 nsiprincipal getcertificateprincipal(in autf8string aentryna
me); nsiprincipal getcertificateprincipal(in string aentryna
me); obsolete since gecko 10 nsizipentry getentry(in autf8string zipentry); nsizipentry getentry(in string zipentry); obsolete since gecko 10 nsiinputstream getinputstream(in autf8string zipentry); nsiinputstream getinputstream(in string zipentry); obsolete since gecko 10 nsiinputstream getinputstre...
...ry); obsolete since gecko 10 boolean hasentry(in autf8string zipentry); void init(in nsifile zipfile); obsolete since gecko 1.9 void open(in nsifile zipfile); void openinner(in nsizipreader zipreader, in autf8string zipentry); void openinner(in nsizipreader zipreader, in string zipentry); obsolete since gecko 10 void test(in autf8string aentryna
me); void test(in string aentryna
me); obsolete since gecko 10 attributes attribute type description file nsifile the file that represents the zip with which this zip reader was initialized.
WebIDL bindings
so for example, given this idl: interface interfacewithnamedgetter { getter long(domstring arg); }; the corresponding c++ would be: class interfacewithnamedgetter { public: int32_t namedgetter(const nsastring& aname, bool& afound); bool nameisenumerable(const nsastring& ana
me); void getsupportednames(unsigned aflags, nstarray<nsstring>& anames); }; indexed getters if the interface has a indexed getter, the binding will expect the following methods on the c++ implementation: a indexedgetter method.
...in particular, in the xray case the jscontext is in the caller compartment (typically chro
me) but the jsobject is in the target compartment (typically content).
Using Objective-C from js-ctypes
class objc_getclass(const char *na
me); in /usr/include/objc/objc.h, class is defined as an opaque type by the following: typedef struct objc_class *class; in this example, we need the classnsspeechsynthesizer, which is retrieved with the following code: class nsspeechsynthesizer = objc_getclass("nsspeechsynthesizer"); registering a selector selectors can be registered and retrieved with sel_registername function, also declar...
...this could be converted by the following objective-c code (may not be exactly the sa
me).
Debugger.Environment - Firefox Developer Tools
getvariable(na
me) return the value of the variable bound toname in this environment, or undefined if this environment does not bindname.name must be a string that is a valid ecmascript identifier name.
... find(na
me) return a reference to the innermost environment, starting with this environment, that bindsname.
Debugger - Firefox Developer Tools
ondebuggerstatement(fra
me) debuggee code has executed adebugger statement inframe.
... onenterframe(fra
me) the stack frameframe is about to begin executing code.
Waterfall - Firefox Developer Tools
= 1000000000; function calculateprimes() { console.time("calculating..."); var primes = []; for (var i = 0; i < iterations; i++) { var candidate = i * (multiplier * math.random()); var isprime = true; for (var c = 2; c <= math.sqrt(candidate); ++c) { if (candidate % c === 0) { // not prime isprime = false; break; } } if (ispri
me) { primes.push(candidate); } } console.timeend("calculating..."); return primes; } the waterfall's output will look something like this: the marker is labeled with the argument you passed to console.time(), and when you select the marker, you can see the program stack in the right-hand sidebar.
...ng..."); 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 (ispri
me) { primes.push(candidate); } } console.timeend("calculating..."); return primes; } in the waterfall you'll now see something like this: ...
AudioParam.cancelScheduledValues() - Web APIs
syntax var audioparam = audioparam.cancelscheduledvalues(startti
me) parameters starttime a double representing the time (in seconds) after the audiocontext was first created after which all scheduled changes will be cancelled.
... examples var gainnode = audioctx.creategain(); gainnode.gain.setvaluecurveattime(wavearray, audioctx.currenttime, 2); //'gain' is the audioparam gainnode.gain.cancelscheduledvalues(audioctx.currentti
me); specifications specification status comment web audio apithe definition of 'cancelscheduledvalues' in that specification.
AudioParam.exponentialRampToValueAtTime() - Web APIs
syntax var audioparam = audioparam.exponentialramptovalueattime(value, endti
me) parameters value a floating point number representing the value the audioparam will ramp to by the given time.
...ryselector('.exp-ramp-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set its gain value to 0.5 var gainnode = audioctx.creategain(); // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination gainnode.gain.setvalueattime(0, audioctx.currentti
me); source.connect(gainnode); gainnode.connect(audioctx.destination); // set buttons to do something onclick exprampplus.onclick = function() { gainnode.gain.exponentialramptovalueattime(1.0, audioctx.currenttime + 2); } exprampminus.onclick = function() { gainnode.gain.exponentialramptovalueattime(0.01, audioctx.currenttime + 2); } note: a value of 0.01 was used for the value to ramp down ...
AudioParam.linearRampToValueAtTime() - Web APIs
syntax var audioparam = audioparam.linearramptovalueattime(value, endti
me) parameters value a floating point number representing the value the audioparam will ramp to by the given time.
...lector('.linear-ramp-minus'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination gainnode.gain.setvalueattime(0, audioctx.currentti
me); source.connect(gainnode); gainnode.connect(audioctx.destination); // set buttons to do something onclick linearrampplus.onclick = function() { gainnode.gain.linearramptovalueattime(1.0, audioctx.currenttime + 2); } linearrampminus.onclick = function() { gainnode.gain.linearramptovalueattime(0, audioctx.currenttime + 2); } specifications specification status comment ...
Background Tasks API - Web APIs
window.requestidlecallback = window.requestidlecallback || function(handler) { let starttime = date.now(); return settimeout(function() { handler({ didtimeout: false, timeremaining: function() { return math.max(0, 50.0 - (date.now() - startti
me)); } }); }, 1); } if window.requestidlecallback is undefined, we create it here.
... window.requestidlecallback = window.requestidlecallback || function(handler) { let starttime = date.now(); return settimeout(function() { handler({ didtimeout: false, timeremaining: function() { return math.max(0, 50.0 - (date.now() - startti
me)); } }); }, 1); }; window.cancelidlecallback = window.cancelidlecallback || function(id) { cleartimeout(id); }; managing the task queue next, let's look at the way we manage the tasks that need to be performed.
BaseAudioContext.createDelay() - Web APIs
syntax var delaynode = audioctx.createdelay(maxdelayti
me); parameters maxdelaytime optional the maximum amount of time, in seconds, that the audio signal can be delayed by.
... var delay1; rangesynth.oninput = function() { delay1 = rangesynth.value; synthdelay.delaytime.setvalueattime(delay1, audioctx.currentti
me); } specifications specification status comment web audio apithe definition of 'createdelay()' in that specification.
Cache - Web APIs
var expectedcachenamesset = new set(object.values(current_caches)); event.waituntil( caches.keys().then(function(cachenames) { return promise.all( cachenames.map(function(cachena
me) { if (!expectedcachenamesset.has(cachena
me)) { // if this cache name isn't present in the set of "expected" cache names, then delete it.
... console.log('deleting out of date cache:', cachena
me); return caches.delete(cachena
me); } }) ); }) ); }); self.addeventlistener('fetch', function(event) { console.log('handling fetch event for', event.request.url); event.respondwith( caches.open(current_caches.font).then(function(cache) { return cache.match(event.request).then(function(response) { if (response) { // if there is an entry in the cache for event.request, then response will be defined // and we can just return it.
CustomElementRegistry.whenDefined() - Web APIs
syntax promise<> customelements.whendefined(na
me); parameters name custom element name.
...const undefinedelements = container.queryselectorall(':not(:defined)'); const promises = [...undefinedelements].map( button => customelements.whendefined(button.localna
me) ); // wait for all the children to be upgraded, // then remove the placeholder.
Document.getElementsByName() - Web APIs
syntax var elements = document.getelementsbyname(na
me); elements is a live nodelist collection, meaning it automatically updates as new elements with the same name are added to/removed from the document.
... example <!doctype html> <html lang="en"> <title>example: using document.getelementsbyname</title> <input type="hidden" name="up"> <input type="hidden" name="down"> <script> var up_names = document.getelementsbyname("up"); console.log(up_names[0].tagna
me); // displays "input" </script> </html> notes the name attribute can only be applied in (x)html documents.
Document.getElementsByTagNameNS() - Web APIs
syntax elements = document.getelementsbytagnamens(namespace, na
me) elements is a live nodelist (but see the note below) of found elements in the order they appear in the tree.
... name is either the local name of elements to look for or the special value *, which matches all elements (see element.localna
me).
Introduction to the DOM - Web APIs
alert(paragraphs[0].nodena
me); all of the properties, methods, and events available for manipulating and creating web pages are organized into objects (for example, the document object that represents the document itself, the table object that implements the special htmltableelement dom interface for accessing html tables, and so forth).
... document.getelementbyid(id) document.getelementsbytagname(na
me) document.createelement(na
me) parentnode.appendchild(node) element.innerhtml element.style.left element.setattribute() element.getattribute() element.addeventlistener() window.content window.onload window.scrollto() testing the dom api this document provides samples for every interface that you can use in your own web development.
Element.getElementsByTagNameNS() - Web APIs
syntax elements = element.getelementsbytagnamens(namespaceuri, localna
me) elements is a live htmlcollection of found elements in the order they appear in the tree.
... localname is either the local name of elements to look for or the special value "*", which matches all elements (see element.localname and attr.localna
me).
Element.hasAttribute() - Web APIs
syntax var result = element.hasattribute(na
me); result holds the return value true or false.
... example var foo = document.getelementbyid("foo"); if (foo.hasattribute("bar")) { // do something } polyfill ;(function(prototype) { prototype.hasattribute = prototype.hasattribute || function(na
me) { return !!(this.attributes[name] && this.attributes[name].specified); } })(element.prototype); notes dom methods dealing with element's attributes: not namespace-aware, most commonly used methods namespace-aware variants (dom level 2) dom level 1 methods for dealing with attr nodes directly (seldom used) dom level 2 namespace-aware methods for dealing with attr nodes directly (seldom used) setattribute (dom 1) setattributens setattributenode setattributenodens getattribute (dom 1) ge...
Element.outerHTML - Web APIs
e.log(d.outerhtml); // the string '<div id="d"><p>content</p><p>further elaborated</p></div>' // is written to the console window replacing a node by setting the outerhtml property: html <div id="container"> <div id="d">this is a div.</div> </div> javascript var container = document.getelementbyid("container"); var d = document.getelementbyid("d"); console.log(container.firstchild.nodena
me); // logs "div" d.outerhtml = "<p>this paragraph replaced the original div.</p>"; console.log(container.firstchild.nodena
me); // logs "p" // the #d div is no longer part of the document tree, // the new paragraph replaced it.
...for example: var div = document.createelement("div"); div.outerhtml = "<div class=\"test\">test</div>"; console.log(div.outerhtml); // output: "<div></div>" also, while the element will be replaced in the document, the variable whose outerhtml property was set will still hold a reference to the original element: var p = document.getelementsbytagname("p")[0]; console.log(p.nodena
me); // shows: "p" p.outerhtml = "<div>this div replaced a paragraph.</div>"; console.log(p.nodena
me); // still "p"; the returned value will contain html escaped attributes: var anc = document.createelement("a"); anc.href = "https://developer.mozilla.org?a=b&c=d"; console.log(anc.outerhtml); // output: "<a href='https://developer.mozilla.org?a=b&c=d'></a>" specification specificati...
File.type - Web APIs
returns the media type (mi
me) of the file represented by a file object.
... syntax var name = file.type; value a string, containing the media type(mi
me) indicating the type of the file, for example "image/png" for png images example <input type="file" multiple onchange="showtype(this)"> function showtype(fileinput) { var files = fileinput.files; for (var i = 0; i < files.length; i++) { var name = files[i].name; var type = files[i].type; alert("filename: " + name + " , type: " + type); } } note: based on the current implementation, browsers won't actually read the bytestream of a file to determine its media type.
FileList - Web APIs
t element: // fileinput is an html input element: <input type="file" id="myfileinput" multiple> var fileinput = document.getelementbyid("myfileinput"); // files is a filelist object (similar to nodelist) var files = fileinput.files; var file; // loop through files for (var i = 0; i < files.length; i++) { // get item file = files.item(i); //or file = files[i]; alert(file.na
me); } here is a complete example.
...ected--> <input id="myfiles" multiple type="file"> </body> <script> var pullfiles=function(){ // love the query selector var fileinput = document.queryselector("#myfiles"); var files = fileinput.files; // cache files.length var fl = files.length; var i = 0; while ( i < fl) { // localize file var in the loop var file = files[i]; alert(file.na
me); i++; } } // set the input element onchange to call pullfiles document.queryselector("#myfiles").onchange=pullfiles; //a.t </script> </html> specifications specification status comment file apithe definition of 'filelist' in that specification.
File and Directory Entries API - Web APIs
there are also two global functions (which are not part of the specification at this time and are implemented only by google chro
me).
... there are also two global functions (which are not part of the specification at this time and are implemented only by google chro
me).
FormData.append() - Web APIs
syntax there are two versions of this method: a two and a three parameter version: formdata.append(name, value); formdata.append(name, value, filena
me); parameters name the name of the field whose data is contained in value.
...for example (and being compatible with php's naming conventions by adding [] to the na
me): 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.
Using the Frame Timing API - Web APIs
function create_frame_observer() { if (window.performanceobserver === undefined) return; // register the performance observer var observe_frame = new performanceobserver(function(list) { // log the frame entries var perfentries = list.getentriesbytype("frame"); for (var i=0; i < perfentries.length; i++) { console.log("obs #1: [" + i + "] = " + perfentries[i].na
me); } }); // only observe 'frame' events observe_frame.observe({entrytypes: ['frame']}); } function init () { create_frame_observer(); var obs = new performanceobserver(frame_observer_2); obs.observe({entrytypes: ['frame']}); } function frame_observer_2(list) { // log the frame entries var perfentries = list.getentriesbytype("frame"); for (var i=0; i < perfentries.length; i+...
...+) { console.log("obs #2: [" + i + "] = " + perfentries[i].na
me); } } <body onload="init(event)"> when the browser adds a new "frame" entry to the performance timeline, both of the observer callbacks will be invoked.
HTMLCanvasElement.toBlob() - Web APIs
var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); function blobcallback(iconna
me) { return function(b) { var a = document.createelement('a'); a.textcontent = 'download'; document.body.appendchild(a); a.style.display = 'block'; a.download = iconname + '.ico'; a.href = window.url.createobjecturl(b); } } canvas.toblob(blobcallback('passthisstring'), 'image/vnd.microsoft.icon', '-moz-parse-options:format=bmp;bpp=32'); save toblob to disk...
... var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); function blobcallback(iconna
me) { return function(b) { var r = new filereader(); r.onloadend = function () { // r.result contains the arraybuffer.
HTMLInputElement - Web APIs
possible values are: on: the browser can autocomplete the value using previously stored value off: the user must explicity enter a value max string: returns / sets the element's max attribute, containing the maximum (numeric or date-ti
me) value for this item, which must not be less than its minimum (min attribute) value.
...(if you set this to a negative number, an exception will be thrown.) min string: returns / sets the element's min attribute, containing the minimum (numeric or date-ti
me) value for this item, which must not be greater than its maximum (max attribute) value.
MediaTrackSettings - Web APIs
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 fra
me).
...this value will be between 0.0 (silent) to 1.0 (maximum supported volu
me).
Node.firstChild - Web APIs
<p id="para-01"> <span>first span</span> </p> <script> var p01 = document.getelementbyid('para-01'); console.log(p01.firstchild.nodena
me); </script> in the above, the console will show '#text' because a text node is inserted to maintain the whitespace between the end of the opening <p> and <span> tags.
... <p id="para-01"><span>first span</span></p> <script> var p01 = document.getelementbyid('para-01'); console.log(p01.firstchild.nodena
me); </script> now the console will show 'span'.
Node.getRootNode() - Web APIs
/dom/node/getrootnode()/demo/getrootnode.html --> <div class="js-parent"> <div class="js-child"></div> </div> <div class="js-shadowhost"></div> <script> // works on chrome 54+,opera 41+ var parent = document.queryselector('.js-parent'), child = document.queryselector('.js-child'), shadowhost = document.queryselector('.js-shadowhost'); console.log(parent.getrootnode().nodena
me); // #document console.log(child.getrootnode().nodena
me); // #document // create a shadowroot var shadowroot = shadowhost.attachshadow({mode:'open'}); shadowroot.innerhtml = '<style>div{background:#2bb8aa;}</style>' + '<div class="js-shadowchild">content</div>'; var shadowchild = shadowroot.queryselector('.js-shadowchild'); // the default value of composed is false console.lo...
...g(shadowchild.getrootnode() === shadowroot); // true console.log(shadowchild.getrootnode({composed:false}) === shadowroot); // true console.log(shadowchild.getrootnode({composed:true}).nodena
me); // #document </script> specifications specification status comment domthe definition of 'getrootnode()' in that specification.
OscillatorNode.detune - Web APIs
syntax var oscillator = audioctx.createoscillator(); oscillator.detune.setvalueattime(100, audioctx.currentti
me); // value in cents note: though the audioparam returned is read-only, the value it represents is not.
... // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currentti
me); // value in hertz oscillator.detune.setvalueattime(100, audioctx.currentti
me); // value in cents oscillator.start(); specifications specification status comment web audio apithe definition of 'detune' in that specification.
OscillatorNode.frequency - Web APIs
syntax var oscillator = audioctx.createoscillator(); oscillator.frequency.setvalueattime(440, audioctx.currentti
me); // value in hertz note: though the audioparam returned is read-only, the value it represents is not.
... // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(440, audioctx.currentti
me); // value in hertz oscillator.start(); specifications specification status comment web audio apithe definition of 'frequency' in that specification.
PannerNode.coneInnerAngle - Web APIs
e determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currentti
me); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currentti
me); panner.orientationy.setvalueattime(y1, context.currentti
me); panner.o...
...rientationz.setvalueattime(z1, context.currentti
me); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [x2, y2, z2] = yrotationtovector(-22.4); panner.orientationx.setvalueattime(x2, context.currenttime + 2); panner.orientationy.setvalueattime(y2, context.currenttime + 2); panner.orientationz.setvalueattime(z2, context.currenttime + 2); finally, let's connect all our nodes and start the oscillator!
PannerNode.coneOuterAngle - Web APIs
e determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currentti
me); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currentti
me); panner.orientationy.setvalueattime(y1, context.currentti
me); panner.o...
...rientationz.setvalueattime(z1, context.currentti
me); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [x2, y2, z2] = yrotationtovector(-22.4); panner.orientationx.setvalueattime(x2, context.currenttime + 2); panner.orientationy.setvalueattime(y2, context.currenttime + 2); panner.orientationz.setvalueattime(z2, context.currenttime + 2); finally, let's connect all our nodes and start the oscillator!
PannerNode.coneOuterGain - Web APIs
e determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currentti
me); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currentti
me); panner.orientationy.setvalueattime(y1, context.currentti
me); panner.o...
...rientationz.setvalueattime(z1, context.currentti
me); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [x2, y2, z2] = yrotationtovector(-22.4); panner.orientationx.setvalueattime(x2, context.currenttime + 2); panner.orientationy.setvalueattime(y2, context.currenttime + 2); panner.orientationz.setvalueattime(z2, context.currenttime + 2); finally, let's connect all our nodes and start the oscillator!
PannerNode.orientationX - Web APIs
e determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currentti
me); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currentti
me); panner.orientationy.setvalueattime(y1, context.currentti
me); panner.o...
...rientationz.setvalueattime(z1, context.currentti
me); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [x2, y2, z2] = yrotationtovector(-22.4); panner.orientationx.setvalueattime(x2, context.currenttime + 2); panner.orientationy.setvalueattime(y2, context.currenttime + 2); panner.orientationz.setvalueattime(z2, context.currenttime + 2); finally, let's connect all our nodes and start the oscillator!
PannerNode.orientationY - Web APIs
e determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currentti
me); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currentti
me); panner.orientationy.setvalueattime(y1, context.currentti
me); panner.o...
...rientationz.setvalueattime(z1, context.currentti
me); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [x2, y2, z2] = yrotationtovector(-22.4); panner.orientationx.setvalueattime(x2, context.currenttime + 2); panner.orientationy.setvalueattime(y2, context.currenttime + 2); panner.orientationz.setvalueattime(z2, context.currenttime + 2); finally, let's connect all our nodes and start the oscillator!
PannerNode.orientationZ - Web APIs
e determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currentti
me); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation // this means the sound will play at full volume const [x1, y1, z1] = yrotationtovector(0); // schedule the no-rotation vector immediately panner.orientationx.setvalueattime(x1, context.currentti
me); panner.orientationy.setvalueattime(y1, context.currentti
me); panner.o...
...rientationz.setvalueattime(z1, context.currentti
me); // calculate the vector for -22.4 degrees // since our coneouterangle is 45, this will just about make the sound audible // if we set it to +/-22.5, the sound volume will be 0, as the threshold is exclusive const [x2, y2, z2] = yrotationtovector(-22.4); panner.orientationx.setvalueattime(x2, context.currenttime + 2); panner.orientationy.setvalueattime(y2, context.currenttime + 2); panner.orientationz.setvalueattime(z2, context.currenttime + 2); finally, let's connect all our nodes and start the oscillator!
PannerNode.refDistance - Web APIs
test tones will last this many seconds const note_length = 6; // this is how far we'll move the sound const z_distance = 20; // this function creates a graph for the test tone with a given refdistance // and schedules it to move away from the listener along the z (depth-wise) axis // at the given start time, resulting in a decrease in volume (decay) const scheduletesttone = (refdistance, startti
me) => { const osc = new oscillatornode(context); const panner = new pannernode(context); panner.refdistance = refdistance; // set the initial z position, then schedule the ramp panner.positionz.setvalueattime(0, startti
me); panner.positionz.linearramptovalueattime(z_distance, starttime + note_length); osc.connect(panner) .connect(context.destination); osc.start(startti
me); ...
... osc.stop(starttime + note_length); }; // this tone should decay immediately and fairly quickly scheduletesttone(1, context.currentti
me); // this tone should decay slower and later than the previous one scheduletesttone(4, context.currenttime + note_length); // this tone should decay only slightly, and only start decaying fairly late scheduletesttone(7, context.currenttime + note_length * 2); after running this code, the resulting waveforms should look something like this: specifications specification status comment web audio apithe definition of 'refdistance' in that specification.
PannerNode.rolloffFactor - Web APIs
t tones will last this many seconds const note_length = 4; // this is how far we'll move the sound const z_distance = 20; // this function creates a graph for the test tone with a given rollofffactor // and schedules it to move away from the listener along the z (depth-wise) axis // at the given start time, resulting in a decrease in volume (decay) const scheduletesttone = (rollofffactor, startti
me) => { const osc = new oscillatornode(context); const panner = new pannernode(context); panner.rollofffactor = rollofffactor; // set the initial z position, then schedule the ramp panner.positionz.setvalueattime(0, startti
me); panner.positionz.linearramptovalueattime(z_distance, starttime + note_length); osc.connect(panner) .connect(context.destination); osc.start(starttime...
...); osc.stop(starttime + note_length); }; // this tone should decay fairly quickly scheduletesttone(1, context.currentti
me); // this tone should decay slower than the previous one scheduletesttone(0.5, context.currenttime + note_length); // this tone should decay only slightly scheduletesttone(0.1, context.currenttime + note_length * 2); after running this code, the resulting waveforms should look something like this: specifications specification status comment web audio apithe definition of 'rollofffactor' in that specification.
RTCRtcpParameters - Web APIs
properties cname the canonical name (cna
me) being used by rtcp.
... examples this example obtains the canonical name (cna
me) being used for rtcp on an rtcrtpsender or rtcrtpreceiver.
SVGStylable - Web APIs
interface overview also implement none methods cssvalue getpresentationattribute(in domstring na
me) properties readonly svganimatedstring classname readonly cssstyledeclaration style normative document svg 1.1 (2nd edition) properties name type description classname svganimatedstring corresponds to attribute class on the given element.
... methods name & arguments return description getpresentationattribute(in domstring na
me) cssvalue returns the base (i.e., static) value of a given presentation attribute as an object of type cssvalue.
SpeechSynthesis: voiceschanged event - Web APIs
r method: var synth = window.speechsynthesis; synth.addeventlistener('voiceschanged', function() { var voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].na
me); voiceselect.appendchild(option); } }); or use the onvoiceschanged event handler property: synth.onvoiceschanged = function() { var voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; option.setattribute('data-lang', voices[i].lang); option.se...
...tattribute('data-name', voices[i].na
me); voiceselect.appendchild(option); } } specifications specification status comment web speech apithe definition of 'speech synthesis events' in that specification.
URL - Web APIs
host a usvstring containing the domain (that is the hostna
me) followed by (if a port was specified) a ':' and the port of the url.
... usage notes the constructor takes a url parameter, and an optional base parameter to use as a base if the url parameter is a relative url: const url = new url('../cats', 'http://www.example.com/dogs'); console.log(url.hostna
me); // "www.example.com" console.log(url.pathna
me); // "/cats" url properties can be set to construct the url: url.hash = 'tabby'; console.log(url.href); // "http://www.example.com/cats#tabby" urls are encoded according to the rules found in rfc 3986.
WebGLRenderingContext.getVertexAttrib() - Web APIs
syntax any gl.getvertexattrib(index, pna
me); parameters index a gluint specifying the index of the vertex attribute.
... return value returns the requested vertex attribute information (as specified with pna
me).
Using textures in WebGL - Web APIs
drawscene(gl, programinfo, buffers, texture, deltati
me); ...
... function drawscene(gl, programinfo, buffers, texture, deltati
me) { at this point, the rotating cube should be good to go.
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
example frame callback a fairly basic (but typical) callback for rendering frames might look like this: function myanimationframecallback(time, fra
me) { let adjustedrefspace = applypositionoffsets(xrreferencespace); let pose = frame.getviewerpose(adjustedrefspace); animationframerequestid = frame.session.requestanimationframe(myanimationframecallback); if (pose) { let gllayer = frame.session.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); checkglerror("binding the framebuffer"); gl.clea...
...rcolor(0, 0, 0, 1.0); gl.cleardepth(1.0); gl.clear(gl.color_buffer_bit | gl.depth_buffer_bit); checkglerror("clearing the framebuffer"); const deltatime = (time - lastframeti
me) * 0.001; lastframetime = time; for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); checkglerror(`setting viewport for eye: ${view.eye}`); myrenderscene(gl, view, scenedata, deltati
me); } } } the callback begins by calling a custom function, applypositionoffsets(), which takes a reference space and applies to its transform matrix any changes that need to be made to take into account things such as user inputs from devices not controlled by webxr, such as the keyboard and ...
WebXR performance guide - Web APIs
consider the following function drawscene(gl, view, programinfo, buffers, texture, deltati
me) { ...
...const normalmatrix = mat4.create(); const modelviewmatrix = mat4.create(); function drawscene(gl, view, programinfo, buffers, texture, deltati
me) { ...
Using the Web Speech API - Web APIs
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.na
me), 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 th...
...on populatevoicelist() { voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].na
me); voiceselect.appendchild(option); } } when we come to run the function, we do the following.
XRReferenceSpace - Web APIs
properties in addition to the properties inherited from xrspace (of which there are none at this ti
me), xrreferencespace also inherits the properties of eventtarget.
... methods in addition to the methods inherited from its parent interface, xrspace (there are none at this ti
me), xrreferencespace inherits methods from eventtarget.
XSLTProcessor - Web APIs
[throws] any xsltprocessor.getparameter(string namespaceuri, string localna
me) gets the value of a parameter from the xslt stylesheet.
... [throws] void xsltprocessor.removeparameter(string namespaceuri, string localna
me) removes the parameter if it was previously set.
Border-image generator - CSS: Cascading Style Sheets
this.min : value; var input = new inputcomponent(this); var slider_left = new slidercomponent(this, -1); var slider_right = new slidercomponent(this, 1); slider_left.classname = 'ui-input-slider-left'; slider_right.classname = 'ui-input-slider-right'; if (na
me) { var info = document.createelement('span'); info.classname = 'ui-input-slider-info'; info.textcontent = name; node.appendchild(info); } node.appendchild(slider_left); node.appendchild(input); node.appendchild(slider_right); this.input = input; sliders[topic] = this; setvalue(topic, value); }; inputslider.prototype.setinputvalue = function setinputvalue() { this.i...
...tate'); 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 (na
me) { label.classname = 'text'; if (align) label.classname += ' ' + align; label.textcontent = name; } node.appendchild(checkbox); node.appendchild(label); this.node = node; this.topic = topic; this.checkbox = checkbox; checkbox.addeventlistener('change', function(e) { notify.call(this); }.bind(this)); buttons[topic] = this; }; var getnode = function getnode(...
Border-radius generator - CSS: Cascading Style Sheets
sensivity : 5; var input = new inputcomponent(this); var slider_left = new slidercomponent(this, -1); var slider_right = new slidercomponent(this, 1); slider_left.classname = 'ui-input-slider-left'; slider_right.classname = 'ui-input-slider-right'; if (na
me) { var info = document.createelement('span'); info.classname = 'ui-input-slider-info'; info.textcontent = name; node.appendchild(info); } node.appendchild(slider_left); node.appendchild(input); node.appendchild(slider_right); node.classname = 'ui-input-slider ui-input-slider-container'; this.input = input; sliders[topic] = this; setvalue(topic, value); } var setval...
...tate'); 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 (na
me) { label.classname = 'text'; if (align) label.classname += ' ' + align; label.textcontent = name; } node.appendchild(checkbox); node.appendchild(label); this.node = node; this.topic = topic; this.checkbox = checkbox; checkbox.addeventlistener('change', function(e) { notify.call(this); }.bind(this)); buttons[topic] = this; } var getnode = function getnode(t...
Box-shadow generator - CSS: Cascading Style Sheets
tate'); 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 (na
me) { label.classname = 'text'; if (align) label.classname += ' ' + align; label.textcontent = name; } node.appendchild(checkbox); node.appendchild(label); this.node = node; this.topic = topic; this.checkbox = checkbox; checkbox.addeventlistener('change', function(e) { notify.call(this); }.bind(this)); buttons[topic] = this; } var getnode = function getnode(t...
...; var pmatch = property.match(/(^([a-z0-9\-]*)=\[([a-z0-9\-\"]*)\])|^([a-z0-9\-]*)/i); name.textcontent = '\t' + pmatch[4]; if (pmatch[3] !== undefined) { name.textcontent = '\t' + pmatch[2]; value.textcontent = pmatch[3] + ';'; } name.textcontent += ': '; prop.classname = 'css-property'; name.classname = 'name'; value.classname = 'value'; prop.appendchild(na
me); prop.appendchild(value); classes[topic].node.appendchild(prop); classes[topic].line[property] = prop; classes[topic].prop[property] = value; } var outputclass = function outputclass(node) { var topic = node.getattribute('data-topic'); var prop = node.getattribute('data-prop'); var name = node.getattribute('data-name'); var properties = prop.split(' '); classes[t...
Linear-gradient Generator - CSS: Cascading Style Sheets
this.min : value; var input = new inputcomponent(this); var slider_left = new slidercomponent(this, -1); var slider_right = new slidercomponent(this, 1); slider_left.classname = 'ui-input-slider-left'; slider_right.classname = 'ui-input-slider-right'; if (na
me) { var info = document.createelement('span'); info.classname = 'ui-input-slider-info'; info.textcontent = name; node.appendchild(info); } node.appendchild(slider_left); node.appendchild(input); node.appendchild(slider_right); this.input = input; sliders[topic] = this; setvalue(topic, value); }; inputslider.prototype.setinputvalue = function setinputvalue() { this.i...
...true : false; this.topic = topic; this.unit = unit; var name = document.createelement('div'); var slider = document.createelement('div'); var pointer = document.createelement('div'); name.classname = 'ui-slider-name'; name.textcontent = info; slider.classname = 'ui-slider-slider'; pointer.classname = 'ui-slider-pointer'; node.appendchild(na
me); slider.appendchild(pointer); this.pointer = pointer; this.slider = slider; this.node = node; this.createsetbutton('-', this.decrement.bind(this)); node.appendchild(slider); this.createsetbutton('+', this.increment.bind(this)); this.createinputfield(); new trackmouse(slider, this.updateslider.bind(this), this.startmove.bind(this)); slider.addeventlistener('click', function(...
Audio and Video Delivery - Developer guides
the main mechanism is outlined below: navigator.mediadevices.getusermedia({audio:true}) .then(function onsuccess(stream) { var recorder = new mediarecorder(stream); var data = []; recorder.ondataavailable = function(e) { data.push(e.data); }; recorder.start(); recorder.onerror = function(e) { throw e.error || new error(e.na
me); // e.name is ff non-spec } recorder.onstop = function(e) { var audio = document.createelement('audio'); audio.src = window.url.createobjecturl(new blob(data)); } settimeout(function() { rec.stop(); }, 5000); }) .catch(function onerror(error) { console.log(error.message); }); see mediarecorder api for more details.
... encrypted media extensions (e
me) encrypted media extensions is a w3c proposal to extend htmlmediaelement, providing apis to control playback of protected content.
<input type="datetime-local"> - HTML: Hypertext Markup Language
chro
me).
...e="year"> </select> </span> </div> <div> <span> <label for="hour">hour:</label> <select id="hour" name="hour"> </select> </span> <span> <label for="minute">minute:</label> <select id="minute" name="minute"> </select> </span> </div> </div> </form> the months are hard-coded (as they are always the sa
me), while the day and year values are dynamically generated depending on the currently selected month and year, and the current year respectively (see the code comments below for detailed explanations of how these functions work.) we also decided to dynamically generate the hours and minutes, as there are so many of them!
Closures - JavaScript
lexical scoping consider the following example code: function init() { var name = 'mozilla'; // name is a local variable created by init function displayname() { // displayname() is the inner function, a closure alert(na
me); // use variable declared in the parent function } displayname(); } init(); init() creates a local variable called name and a function called displayname().
... closure consider the following code example: function makefunc() { var name = 'mozilla'; function displayname() { alert(na
me); } return displayname; } var myfunc = makefunc(); myfunc(); running this code has exactly the same effect as the previous example of the init() function above.
Concurrency model and the event loop - JavaScript
when foo returns, the top frame element is popped out of the stack (leaving only bar's call fra
me).
...in the example below, the message ''this is just a message'' will be written to the console before the message in the callback gets processed, because the delay is the minimum time required for the runtime to process the request (not a guaranteed ti
me).
Details of the object model - JavaScript
function employee(name, dept) { this.name = name || ''; this.dept = dept || 'general'; } public class employee { public string name; public string dept; public employee () { this("", "general"); } public employee (string na
me) { this(name, "general"); } public employee (string name, string dept) { this.name = name; this.dept = dept; } } function workerbee(projs) { this.projects = projs || []; } workerbee.prototype = new employee; public class workerbee extends employee { public string[] projects; public workerbee () { this(new string[0]); } public workerbee (string[] p...
...if you care about the exact value of this counter, one possible solution involves instead using the following constructor: function employee(name, dept) { this.name = name || ''; this.dept = dept || 'general'; if (na
me) this.id = idcounter++; } when you create an instance of employee to use as a prototype, you do not supply arguments to the constructor.
Meta programming - JavaScript
for example, getting a property on an object: let handler = { get: function(target, na
me) { return name in target?
... let revocable = proxy.revocable({}, { get: function(target, na
me) { return '[[' + name + ']]' } }) let proxy = revocable.proxy console.log(proxy.foo) // "[[foo]]" revocable.revoke() console.log(proxy.foo) // typeerror is thrown proxy.foo = 1 // typeerror again delete proxy.foo // still typeerror typeof proxy // "object", typeof doesn't trigger any trap reflection reflect is a built-in object that provides methods for int...
Warning: String.x is deprecated; use String.prototype.x instead - JavaScript
to non-supporting browsers: /*globals define*/ // assumes all supplied string instance methods already present // (one may use shims for these if not available) (function() { 'use strict'; var i, // we could also build the array of methods with the following, but the // getownpropertynames() method is non-shimable: // object.getownpropertynames(string).filter(function(methodna
me) { // return typeof string[methodname] === 'function'; // }); methods = [ 'contains', 'substring', 'tolowercase', 'touppercase', 'charat', 'charcodeat', 'indexof', 'lastindexof', 'startswith', 'endswith', 'trim', 'trimleft', 'trimright', 'tolocalelowercase', 'normalize', 'tolocaleuppercase', 'localecompare', 'match', 'search', 'slice', 'replace', 'split'...
..., 'substr', 'concat', 'localecompare' ], methodcount = methods.length, assignstringgeneric = function(methodna
me) { var method = string.prototype[methodname]; string[methodname] = function(arg1) { return method.apply(arg1, array.prototype.slice.call(arguments, 1)); }; }; for (i = 0; i < methodcount; i++) { assignstringgeneric(methods[i]); } }()); ...
SyntaxError: illegal character - JavaScript
message syntaxerror: invalid character (edge) syntaxerror: illegal character (firefox) syntaxerror: invalid or unexpected token (chro
me) error type syntaxerror what went wrong?
...famous examples of this are quotes, the minus or semicolon (greek questionmark (u+37e) looks sa
me).
TypeError: cannot use 'in' operator to search for 'x' in 'y' - JavaScript
message typeerror: invalid operand to 'in' (edge) typeerror: right-hand side of 'in' should be an object, got 'x' (firefox) typeerror: cannot use 'in' operator to search for 'x' in 'y' (firefox, chro
me) error type typeerror what went wrong?
... var foo = null; "bar" in foo; // typeerror: cannot use 'in' operator to search for 'bar' in 'foo' (chro
me) // typeerror: right-hand side of 'in' should be an object, got null (firefox) the in operator always expects an object.
Error - JavaScript
per(...params) // maintains proper stack trace for where our error was thrown (only available on v8) if (error.capturestacktrace) { error.capturestacktrace(this, customerror) } this.name = 'customerror' // custom debugging information this.foo = foo this.date = new date() } } try { throw new customerror('baz', 'bazmessage') } catch(e) { console.error(e.na
me) //customerror console.error(e.foo) //baz console.error(e.message) //bazmessage console.error(e.stack) //stacktrace } es5 custom error object all browsers include the customerror constructor in the stack trace when using a prototypal declaration.
...or); } 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.na
me); //customerror console.error(e.foo); //baz console.error(e.message); //bazmessage } specifications specification ecmascript (ecma-262)the definition of 'error' in that specification.
Function.displayName - JavaScript
by entering the following in a console, it should display as something like "function my function()": var a = function() {}; a.displayname = 'my function'; a; // "function my function()" when defined, the displayname property returns the display name of a function: function dosomething() {} console.log(dosomething.displayna
me); // "undefined" var popup = function(content) { console.log(content); }; popup.displayname = 'show popup'; console.log(popup.displayna
me); // "show popup" defining a displayname in function expressions you can define a function with a display name in a function expression: var object = { somemethod: function() {} }; object.somemethod.displayname = 'somemethod'; console.log(object.somem...
...ethod.displayna
me); // logs "somemethod" try { somemethod } catch(e) { console.log(e); } // referenceerror: somemethod is not defined changing displayname dynamically you can dynamically change the displayname of a function: var object = { // anonymous somemethod: function(value) { arguments.callee.displayname = 'somemethod (' + value + ')'; } }; console.log(object.somemethod.displayna
me); // "undefined" object.somemethod('123') console.log(object.somemethod.displayna
me); // "somemethod (123)" specifications not part of any standard.
Intl.DateTimeFormat() constructor - JavaScript
hour12 whether to use 12-hour time (as opposed to 24-hour ti
me).
...possible values are: "long" (e.g., british summer ti
me) "short" (e.g., gmt+1) the default value for each date-time component property is undefined, but if all component properties are undefined, then year, month, and day are assumed to be "numeric".
Intl.Locale.prototype.baseName - JavaScript
examples basic example let myloc = new intl.locale("fr-latn-ca"); // sets locale to canadian french console.log(myloc.tostring()); // prints out "fr-latn-ca-u-ca-gregory" console.log(myloc.basena
me); // prints out "fr-latn-ca" example with options in the input string // sets language to japanese, region to japan, // calendar to gregorian, hour cycle to 24 hours let japan = new intl.locale("ja-jp-u-ca-gregory-hc-24"); console.log(japan.tostring()); // prints out "ja-jp-u-ca-gregory-hc-h24" console.log(japan.basena
me); // prints out "ja-jp" example with options that override input string ...
...// input string indicates language as dutch and region as belgium, // but options object overrides the region and sets it to the netherlands let dutch = new intl.locale("nl-latn-be", {region: "nl"}); console.log(dutch.basena
me); // prints out "nl-latn-nl" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.maximize() - JavaScript
examples using maximize let mylocale = new intl.locale("fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basena
me); // prints "fr" console.log(mylocale.tostring()); // prints "fr-u-ca-gregory-hc-h24" let mylocmaximized = mylocale.maximize(); // prints "fr-latn-fr".
...console.log(mylocmaximized.basena
me); // prints "fr-latn-fr-u-ca-gregory-hc-h24".
Object.defineProperty() - JavaScript
var o = {}; // creates a new object object.defineproperty(o, 'a', { value: 37, writable: false }); console.log(o.a); // logs 37 o.a = 25; // no error thrown // (it would throw in strict mode, // even if the value had been the sa
me) console.log(o.a); // logs 37.
... 'whatever you have assigned'; }, set() { this.myname = 'this is my name string'; } }; function testdefinesetandget() { object.defineproperty(this, 'myproperty', pattern); } var instance = new testdefinesetandget(); instance.myproperty = 'test'; console.log(instance.myproperty); // i always return this string, whatever you have assigned console.log(instance.myna
me); // this is my name string inheritance of properties if an accessor property is inherited, its get and set methods will be called when the property is accessed and modified on descendant objects.
Object.prototype.hasOwnProperty() - JavaScript
var buz = { fog: 'stack' }; for (var name in buz) { if (buz.hasownproperty(na
me)) { console.log('this is fog (' + name + ') for sure.
... value: ' + buz[name]); } else { console.log(na
me); // tostring or something else } } using hasownproperty as a property name javascript does not protect the property name hasownproperty; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasownproperty to get correct results: var foo = { hasownproperty: function() { return false; }, bar: 'here be dragons' }; foo.hasownproperty('bar'); // always returns false // use another object's hasownproperty // and call it with 'this' set to foo ({}).hasownproperty.call(foo, 'bar'); // true // it's also possible to use the hasownproperty property // from the object prototype for this purpose object.prototype.hasownproperty.call(foo, 'bar'); // true note tha...
ReferenceError() constructor - JavaScript
examples catching a referenceerror try { let a = undefinedvariable } catch (e) { console.log(e instanceof referenceerror) // true console.log(e.message) // "undefinedvariable is not defined" console.log(e.na
me) // "referenceerror" console.log(e.filena
me) // "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 instan...
...ceof referenceerror) // true console.log(e.message) // "hello" console.log(e.na
me) // "referenceerror" console.log(e.filena
me) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'nativeerror constructor' in that specification.
ReferenceError - JavaScript
examples catching a referenceerror try { let a = undefinedvariable } catch (e) { console.log(e instanceof referenceerror) // true console.log(e.message) // "undefinedvariable is not defined" console.log(e.na
me) // "referenceerror" console.log(e.filena
me) // "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 instan...
...ceof referenceerror) // true console.log(e.message) // "hello" console.log(e.na
me) // "referenceerror" console.log(e.filena
me) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'referenceerror' in that specification.
SyntaxError() constructor - JavaScript
ameters message optional human-readable description of the error filename optional the name of the file containing the code that caused the exception linenumber optional the line number of the code that caused the exception examples catching a syntaxerror try { eval('hoo bar'); } catch (e) { console.error(e instanceof syntaxerror); console.error(e.message); console.error(e.na
me); console.error(e.filena
me); 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.na
me); // syntaxerror console.error(e...
....filena
me); // somefile.js console.error(e.linenumber); // 10 console.error(e.columnnumber); // 0 console.error(e.stack); // @debugger eval code:3:9 } specifications specification ecmascript (ecma-262)the definition of 'nativeerror constructor' in that specification.
SyntaxError - JavaScript
examples catching a syntaxerror try { eval('hoo bar'); } catch (e) { console.error(e instanceof syntaxerror); console.error(e.message); console.error(e.na
me); console.error(e.filena
me); 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.na
me); // syntaxerror console.error(e...
....filena
me); // somefile.js console.error(e.linenumber); // 10 console.error(e.columnnumber); // 0 console.error(e.stack); // @debugger eval code:3:9 } specifications specification ecmascript (ecma-262)the definition of 'syntaxerror' in that specification.
TypeError() constructor - JavaScript
the line number of the code that caused the exception examples catching a typeerror try { null.f() } catch (e) { console.log(e instanceof typeerror) // true console.log(e.message) // "null has no properties" console.log(e.na
me) // "typeerror" console.log(e.filena
me) // "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.na
me) // "typeerror" console.log(e.filena
me) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'nativeerror constructor' in that specification.
TypeError - JavaScript
examples catching a typeerror try { null.f() } catch (e) { console.log(e instanceof typeerror) // true console.log(e.message) // "null has no properties" console.log(e.na
me) // "typeerror" console.log(e.filena
me) // "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.na
me) // "typeerror" console.log(e.filena
me) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'typeerror' in that specification.
URIError() constructor - JavaScript
examples catching an urierror try { decodeuricomponent('%') } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "malformed uri sequence" console.log(e.na
me) // "urierror" console.log(e.filena
me) // "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.na
me) // "urierror" console.log(e.filena
me) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'nativeerror constructor' in that specification.
URIError - JavaScript
examples catching an urierror try { decodeuricomponent('%') } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "malformed uri sequence" console.log(e.na
me) // "urierror" console.log(e.filena
me) // "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.na
me) // "urierror" console.log(e.filena
me) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9\n" } specifications specification ecmascript (ecma-262)the definition of 'urierror' in that specification.
delete operator - JavaScript
the following snippet gives a simple example: var employee = { age: 28, name: 'abc', designation: 'developer' } console.log(delete employee.na
me); // 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.
... var employee = {}; object.defineproperty(employee, 'name', {configurable: false}); console.log(delete employee.na
me); // returns false var, let, and const create non-configurable properties that cannot be deleted with the delete operator: var nameother = 'xyz'; // we can access this global property using: object.getownpropertydescriptor(window, 'nameother'); // output: object {value: "xyz", // writable: true, // enumerable: true, // configurable: false} // since "nameother" is added using with the // var keyword, it is marked as "non-configurable" delete nameother; // return false in strict mode, this would have raised an exception.
XPath snippets - XPath
example: defining a simple docevaluatearray() utility function // example usage: // var els = docevaluatearray('//a'); // alert(els[0].nodena
me); // gives 'a' in html document with at least one link function docevaluatearray (expr, doc, context, resolver) { var i, result, a = []; doc = doc || (context ?
... example: defining a getxpathforelement() utility function function getxpathforelement(el, xml) { var xpath = ''; var pos, tempitem2; while(el !== xml.documentelement) { pos = 0; tempitem2 = el; while(tempitem2) { if (tempitem2.nodetype === 1 && tempitem2.nodename === el.nodena
me) { // if it is element_node of the same name pos += 1; } tempitem2 = tempitem2.previoussibling; } xpath = "*[name()='"+el.nodename+"' and namespace-uri()='"+(el.namespaceuri===null?'':el.namespaceuri)+"']["+pos+']'+'/'+xpath; el = el.parentnode; } xpath = '/*'+"[name()='"+xml.documentelement.nodename+"' and namespace-uri()='"+(el.namespaceuri===null?'':el.namespaceuri)+"']"+'...
Compiling from Rust to WebAssembly - WebAssembly
let's write some rust let's put this code into src/lib.rs instead: use wasm_bindgen::prelude::*; #[wasm_bindgen] extern { pub fn alert(s: &str); } #[wasm_bindgen] pub fn greet(name: &str) { alert(&format!("hello, {}!", na
me)); } this is the contents of our rust project.
... producing rust functions that javascript can call the final part is this one: #[wasm_bindgen] pub fn greet(name: &str) { alert(&format!("hello, {}!", na
me)); } once again, we see the #[wasm_bindgen] attribute.
Private Properties - Archive of obsolete content
before explaining how weakmaps work, the following looks at how ordinary objects can be used as hash maps, by creating a simple image cache: let images = {}; function getimage(na
me) { let image = images[name]; if (!image) { image = loadimage(na
me); images[name] = image; } return image; } now suppose there's a need to associate a thumbnail with each image.
request - Archive of obsolete content
the example below shows how to use request to get the most recent tweet from the @mozhacks account: var request = require("sdk/request").request; var latesttweetrequest = request({ url: "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=mozhacks&count=1", oncomplete: function (response) { var tweet = response.json[0]; console.log("user: " + tweet.user.screen_na
me); console.log("tweet: " + tweet.text); } }); // be a good consumer and check for rate limiting before doing more.
core/promise - Archive of obsolete content
earlier described defer may be passed optional prototype argument, in order to make the returned promise and all the subsequent promises decendents of that prototype: let { promise, resolve } = defer({ get: function get(na
me) { return this.then(function(value) { return value[name]; }); } }); promise.get('foo').get('bar').then(console.log); resolve({ foo: { bar: 'taram !!' } }); // => 'taram !!' also promised function maybe be passed a second optional prototype argument to achieve the same effect.
SpiderMonkey Internals
it runs automatically only when maxbytes (as passed to js_newrunti
me) bytes of gc things have been allocated and another thing-allocation request is made.
JSAPI Cookbook
message, filename, lineno); /* jsapi */ bool throwerror(jscontext *cx, jsobject *global, const char *message, const char *filename, int32 lineno) { jsstring *messagestr; jsstring *filenamestr; js::value args[3]; js::value exc; messagestr = js_newstringcopyz(cx, message); if (!messagestr) return false; filenamestr = js_newstringcopyz(cx, filena
me); if (!filenamestr) return false; args[0] = string_to_jsval(messagestr); args[1] = string_to_jsval(filenamestr); args[2] = int_to_jsval(lineno); if (js_callfunctionname(cx, global, "error", 3, args, &exc)) js_setpendingexception(cx, exc); return false; } ...
JS::PropertySpecNameIsSymbol
syntax bool js::propertyspecnameissymbol(const char *na
me); name type description name const char * the pointer of the name, actually the uintptr_t type, and not a pointer to any string.
JS_Add*Root
syntax jsbool js_addvalueroot(jscontext *cx, jsval *vp); jsbool js_addstringroot(jscontext *cx, jsstring **spp); jsbool js_addobjectroot(jscontext *cx, jsobject **opp); jsbool js_addgcthingroot(jscontext *cx, void **rp); jsbool js_addnamedvalueroot(jscontext *cx, jsval *vp, const char *na
me); jsbool js_addnamedstringroot(jscontext *cx, jsstring **spp, const char *na
me); jsbool js_addnamedobjectroot(jscontext *cx, jsobject **opp, const char *na
me); jsbool js_addnamedgcthingroot(jscontext *cx, void **rp, const char *na
me); name type description cx jscontext * the context in which to add the new root.
JS_CStringsAreUTF8
js_cstringsareutf8 returns js_true if the javascript engine is configured (either at compile time or at run ti
me) to interpret char strings as utf-8.
JS_CompileUTF8File
syntax jsobject * js_compileutf8file(jscontext *cx, jsobject *obj, const char *filena
me); name type description cx jscontext * the context in which to compile the script.
JS_DeleteProperty
syntax bool js_deleteproperty(jscontext *cx, js::handleobject obj, const char *na
me); bool js_deletepropertybyid(jscontext *cx, js::handleobject obj, jsid id); // added in spidermonkey 1.8.1 // added in spidermonkey 45 bool js_deleteproperty(jscontext *cx, js::handleobject obj, const char *name, js::objectopresult &result); bool js_deletepropertybyid(jscontext *cx, js::handleobject obj, js::handleid id, js::objectopresult &result); bool js_deleteucproperty(jscontext *cx, js::handleobject obj, const char16_t *name, size_t namelen, js::objectopresult &result); name type description cx jscontext * pointer to a js context from which to derive runtime ...
JS_HasOwnProperty
it behaves like the javascript expression object.hasownproperty(obj, na
me).
JS_NewFunction
syntax // added in spidermonkey 45 jsfunction * js_newfunction(jscontext *cx, jsnative call, unsigned nargs, unsigned flags, const char *na
me); // obsolete since jsapi 44 jsfunction * js_newfunctionbyid(jscontext *cx, jsnative call, unsigned nargs, unsigned flags, js::handle<jsid> id); // obsolete since jsapi 39 jsfunction * js_newfunction(jscontext *cx, jsnative call, unsigned nargs, unsigned flags, js::handle<jsobject*> parent, const char *na
me); jsfunction * js_newfunctionbyid(jscontext *cx, jsnative call, unsigned nargs, unsigned flags, js::handle<jsobject*> parent, js::handle<jsid> id); // added in spidermonkey 17 name t...
JS_SameValue
the samevalue algorithm is equivalent to the following javascript: function samevalue(v1, v2) { if (v1 === 0 && v2 === 0) return 1 / v1 === 1 / v2; if (v1 !== v1 && v2 !== v2) return true; return v1 === v2; } syntax // added in spidermonkey 45 bool js_samevalue(jscontext *cx, js::handle<js::value> v1, js::handle<js::value> v2, bool *sa
me); // obsolete since jsapi 39 bool js_samevalue(jscontext *cx, jsval v1, jsval v2, bool *sa
me); name type description cx jscontext * pointer to a js context from which to derive runtime information.
Secure Development Guidelines
rather than html and javascript if input is mixed with sql, it could itself become an sql instruction and be used to: query data from the database (passwords) insert value into the database (a user account) change application logic based on results returned by the database sql injection: example snprintf(str, sizeof(str), "select * from account where name ='%s'", na
me); sqlite3_exec(db, str, null, null, null); sql injection: prevention use parameterized queries insert a marker for every piece of dynamic content so data does not get mixed with sql instructions example: sqlite3_stmt *stmt; char *str = "select * from account where name='?'"; sqlite3_prepare_v2(db, str, strlen(str), &stmt, null); sqlite3_bind_text(stmt, 1, name, strlen(na
me), sqlite_...
Manipulating bookmarks using Places
bookmarkobserver var myext_bookmarklistener = { onbeginupdatebatch: function() {}, onendupdatebatch: function() {}, onitemadded: function(aitemid, afolder, aindex) {}, onitemremoved: function(aitemid, afolder, aindex) {}, onitemchanged: function(abookmarkid, aproperty, aisannotationproperty, avalue) { myextension.dosomething(); }, onitemvisited: function(abookmarkid, avisitid, ti
me) {}, onitemmoved: function(aitemid, aoldparent, aoldindex, anewparent, anewindex) {}, queryinterface: xpcomutils.generateqi([components.interfaces.nsinavbookmarkobserver]) }; // an extension var myextension = { // this function is called when my add-on is loaded onload: function() { bmsvc.addobserver(myext_bookmarklistener, false); }, // this function is called when my add-on is un...
Places Developer Guide
}, onitemvisited: function(id, visitid, ti
me) { // the visit id can be used with the history service to access other properties of the visit.
Creating a Python XPCOM component
def __del__(self): if verbose: print "pysimple: __del__ method called - object is destructing" def write(self): print self.yourname def change(self, newna
me): self.yourname = newname then register your component; the procedure is the same for any component, but will not work if python components weren't enabled.
nsIAnnotationObserver
1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void onitemannotationremoved(in long long aitemid, in autf8string ana
me); void onitemannotationset(in long long aitemid, in autf8string ana
me); void onpageannotationremoved(in nsiuri auri, in autf8string ana
me); void onpageannotationset(in nsiuri apage, in autf8string ana
me); methods onitemannotationremoved() this method is called when an annotation is deleted for an item.
nsIAppShellService
boolean createstartupstate(in long awindowwidth, in long awindowheight); obsolete since gecko 1.8 nsixulwindow createtoplevelwindow(in nsixulwindow aparent, in nsiuri aurl, in pruint32 achromemask, in long ainitialwidth, in long ainitialheight, in nsiappshell aappshell); nsiwebnav createwindowlessbrowser (in bool aischro
me) void destroyhiddenwindow(); void doprofilestartup(in nsicmdlineservice acmdlineservice, in boolean caninteract); obsolete since gecko 1.8 void ensure1window(in nsicmdlineservice acmdlineservice); obsolete since gecko 1.8 void enterlastwindowclosingsurvivalarea(); obsolete since gecko 1.8 void exitlastwindowclosingsurvivalarea(); obsolete since gecko 1...
nsIBoxObject
method overview wstring getlookandfeelmetric(in wstring propertyna
me); obsolete since gecko 1.9 wstring getproperty(in wstring propertyna
me); nsisupports getpropertyassupports(in wstring propertyna
me); void removeproperty(in wstring propertyna
me); void setproperty(in wstring propertyname, in wstring propertyvalue); void setpropertyassupports(in wstring propertyname, in nsisupports value); attributes attribute type description element nsidomelement read only.
nsIBrowserHistory
ped(in nsiuri auri); obsolete since gecko 22.0 void registeropenpage(in nsiuri auri); obsolete since gecko 9.0 void removeallpages(); void removepage(in nsiuri auri); void removepages([array, size_is(alength)] in nsiuri auris, in unsigned long alength, in boolean adobatchnotify); void removepagesbytimeframe(in long long abegintime, in long long aendti
me); void removepagesfromhost(in autf8string ahost, in boolean aentiredomain); void removevisitsbytimeframe(in long long abegintime, in long long aendti
me); void unregisteropenpage(in nsiuri auri); obsolete since gecko 9.0 note: the markpageasfollowedlink and markpageastyped methods were moved to nsinavhistoryservice in gecko 22.0 so that all markpageas* methods c...
nsIBrowserSearchService
in astring name, in astring iconurl, in astring alias, in astring description, in astring method, in astring url); void getdefaultengines([optional] out unsigned long enginecount, [retval, array, size_is(enginecount)] out nsisearchengine engines); nsisearchengine getenginebyalias(in astring alias); nsisearchengine getenginebyname(in astring aenginena
me); void getengines([optional] out unsigned long enginecount, [retval, array, size_is(enginecount)] out nsisearchengine engines); void getvisibleengines([optional] out unsigned long enginecount, [retval, array, size_is(enginecount)] out nsisearchengine engines); void init([optional] in nsibrowsersearchinitobserver observer); void moveen...
nsICacheEntryDescriptor
.3 / seamonkey 2.1) method overview void close(); void doom(); void doomandfailpendingrequests(in nsresult status); string getmetadataelement(in string key); void markvalid(); nsiinputstream openinputstream(in unsigned long offset); nsioutputstream openoutputstream(in unsigned long offset); void setdatasize(in unsigned long size); void setexpirationtime(in pruint32 expirationti
me); void setmetadataelement(in string key, in string value); void visitmetadata(in nsicachemetadatavisitor visitor); attributes attribute type description accessgranted nscacheaccessmode get the access granted to this descriptor.
nsICategoryManager
ter_addrefs(cats)); if (ns_failed(rv)) return rv; prbool hasmore; while (ns_succeeded(cats->hasmoreelements(&hasmore) && hasmore) { nscomptr<nsisupports> elem; cats->getnext(getter_addrefs(elem)); nscomptr<nsisupportscstring> category = do_queryinterface(elem, &rv); if (ns_failed(rv)) break; nsembedcstring categoryname; rv = category->getdata(categoryna
me); if (ns_failed(rv)) break; printf("%s\n", categoryname.get()); } return ns_ok; } this snippet shows how to print out a list of all categories in javascript.
nsIContentPrefObserver
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void oncontentprefremoved(in astring agroup, in astring ana
me); void oncontentprefset(in astring agroup, in astring aname, in nsivariant avalue); methods oncontentprefremoved() called when a content preference is removed.
nsIContentPrefService
.getservice(components.interfaces.nsicontentprefservice); method overview void addobserver(in astring aname, in nsicontentprefobserver aobserver); nsivariant getpref(in nsivariant agroup, in astring aname, [optional] in nsicontentprefcallback acallback); nsipropertybag2 getprefs(in nsivariant agroup); nsipropertybag2 getprefsbyname(in astring ana
me); boolean haspref(in nsivariant agroup, in astring ana
me); void removegroupedprefs(); void removeobserver(in astring aname, in nsicontentprefobserver aobserver); void removepref(in nsivariant agroup, in astring ana
me); void removeprefsbyname(in astring ana
me); void setpref(in nsivariant agroup, in astring aname, in nsivariant avalue); ...
nsIContentSecurityPolicy
acontext, in acstring amimetypeguess, in nsisupports aextra); short shouldprocess(in unsigned long acontenttype, in nsiuri acontentlocation, in nsiuri arequestorigin, in nsisupports acontext, in acstring amimetype, in nsisupports aextra); attributes attribute type description allowseval boolean whether this policy allows eval and eval-like functions such as settimeout("code string", ti
me).
nsIController
inherits from: nsisupports last changed in gecko 1.7 method overview void docommand(in string command); boolean iscommandenabled(in string command); void onevent(in string eventna
me); boolean supportscommand(in string command); methods docommand() when this method is called, your implementation should execute the command with the specified name.
nsICycleCollectorListener
method overview void begin(); void begindescriptions(); void describegcedobject(in unsigned long long aaddress, in boolean amarked); void describerefcountedobject(in unsigned long long aaddress, in unsigned long aknownedges, in unsigned long atotaledges); void end(); void noteedge(in unsigned long long afromaddress, in unsigned long long atoaddress, in string aedgena
me); void noteobject(in unsigned long long aaddress, in string aobjectdescription); methods begin() void begin(); parameters none.
nsIDocShell
acontenttype the type (mi
me) of data being loaded (empty if unknown).
nsIDownloadHistory
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) method overview void adddownload(in nsiuri asource, [optional] in nsiuri areferrer, [optional] in prtime astartti
me); methods adddownload() adds a download to history.
nsIDownloadManager
arent, in nsidownload adownload); obsolete since gecko 1.9.1 void openprogressdialogfor(in nsidownload adownload, in nsidomwindow aparent, in boolean acanceldownloadonclose); obsolete since gecko 1.9.1 void pausedownload(in unsigned long aid); void removedownload(in unsigned long aid); void removedownloadsbytimeframe(in long long abegintime, in long long aendti
me); void removelistener(in nsidownloadprogresslistener alistener); void resumedownload(in unsigned long aid); void retrydownload(in unsigned long aid); void savestate(); obsolete since gecko 1.8 void startbatchupdate(); obsolete since gecko 1.9.1 attributes attribute type description activedownloadcount long the nu...
nsIEditor
ction txn); void enableundo(in boolean enable); void undo(in unsigned long count); void canundo(out boolean isenabled, out boolean canundo); void redo(in unsigned long count); void canredo(out boolean isenabled, out boolean canredo); void begintransaction(); void endtransaction(); void beginplaceholdertransaction(in nsiatom na
me); void endplaceholdertransaction(); boolean shouldtxnsetselection(); void setshouldtxnsetselection(in boolean should); inline spellchecking methods nsiinlinespellchecker getinlinespellchecker(in boolean autocreate); void syncrealtimespell(); void setspellcheckuseroverride(in boolean enable); clipboard methods void cut...
nsIEnvironment
getservice(components.interfaces.nsienvironment); method overview void set(in astring aname, in astring avalue); astring get(in astring ana
me); boolean exists(in astring ana
me); methods set() set the value of an environment variable.
nsIExternalProtocolService
method overview boolean externalprotocolhandlerexists(in string aprotocolsche
me); astring getapplicationdescription(in autf8string asche
me); nsihandlerinfo getprotocolhandlerinfo(in acstring aprotocolsche
me); nsihandlerinfo getprotocolhandlerinfofromos(in acstring aprotocolscheme, out boolean afound); boolean isexposedprotocol(in string aprotocolsche
me); void loaduri(in nsiuri auri, [optional] in nsiinterfacerequestor awindowcontext); void loadurl(in nsiuri au...
nsIFormHistory2
method overview void addentry(in astring name, in astring value); boolean entryexists(in astring name, in astring value); boolean nameexists(in astring na
me); void removeallentries(); void removeentriesbytimeframe(in long long abegintime, in long long aendti
me); void removeentriesforname(in astring na
me); 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.
nsIJetpack
*/); void registerreceiver(in astring amessagename, in jsval areceiver); void unregisterreceiver(in astring amessagename, in jsval areceiver); void unregisterreceivers(in astring amessagena
me); void evalscript(in astring ascript); nsivariant createhandle(); void destroy(); methods sendmessage() this method asynchronously sends a message to the jetpack process.
nsILocalFile
delete_on_close may be implemented by removing the file (by path na
me) immediately after opening it, so beware of possible races; the file should be exclusively owned by this process.
nsIMsgFilterList
lterlist::loggingenabled defaultfile attribute nsilocalfile nsimsgfilterlist::defaultfile logstream attribute nsioutputstream nsimsgfilterlist::logstream logurl readonly attribute acstring nsimsgfilterlist::logurl methods getfilterat() nsimsgfilter nsimsgfilterlist::getfilterat (in unsigned long filterindex ) getfilternamed() nsimsgfilter nsimsgfilterlist::getfilternamed (in astring filterna
me) setfilterat() nsimsgfilter nsimsgfilterlist::setfilterat ( in unsigned long filterindex, in nsimsgfilter filter ) removefilter() void nsimsgfilterlist::removefilter (in nsimsgfilter filter) removefilterat() void nsimsgfilterlist::removefilterat (in unsigned long filterindex) movefilterat() void nsimsgfilterlist::movefilterat ( in unsigned long ...
nsIMsgHeaderParser
from: nsisupports last changed in gecko 1.9 (firefox 3) to create an instance, use: var msgheaderparser = components.classes["@mozilla.org/messenger/headerparser;1"] .createinstance(components.interfaces.nsimsgheaderparser); method overview string extractheaderaddressmailboxes(in string line); void extractheaderaddressname(in string line, out string na
me); void extractheaderaddressnames(in string line, out string usernames); astring makefulladdress(in astring aname, in astring aaddress); string makefulladdressstring(in string aname, in string aaddress); wstring makefulladdresswstring(in wstring name, in wstring addr); obsolete since gecko 1.9 void parseheaderaddresses(in string line, out string names, ...
nsIMsgSearchTerm
cstring customid; beginsgrouping attribute boolean beginsgrouping; endsgrouping attribute boolean endsgrouping; methods matchrfc822string boolean matchrfc822string(in string astring, in string charset, in boolean charsetoverride); matchrfc2047string boolean matchrfc2047string(in string astring, in string charset, in boolean charsetoverride); matchdate boolean matchdate(in prtime ati
me); matchstatus boolean matchstatus(in unsigned long astatus); matchpriority boolean matchpriority(in nsmsgpriorityvalue priority); matchage boolean matchage(in prtime days); matchsize boolean matchsize(in unsigned long size); matchlabel boolean matchlabel(in nsmsglabelvalue alabelvalue); matchjunkstatus boolean matchjunkstatus(in string ajunkscore); matchjunkpercent /* * test ...
nsINavHistoryResultObserver
historycontainerresultnode acontainernode); deprecated since gecko 2.0 obsolete since gecko 11.0 void containerstatechanged(in nsinavhistorycontainerresultnode acontainernode, in unsigned long aoldstate, in unsigned long anewstate); void invalidatecontainer(in nsinavhistorycontainerresultnode acontainernode); void nodeannotationchanged(in nsinavhistoryresultnode anode, in autf8string aannona
me); void nodedateaddedchanged(in nsinavhistoryresultnode anode, in prtime anewvalue); void nodehistorydetailschanged(in nsinavhistoryresultnode anode, in prtime anewvisitdate, in unsigned long anewaccesscount); void nodeiconchanged(in nsinavhistoryresultnode anode); void nodeinserted(in nsinavhistorycontainerresultnode aparent, in nsinavhistoryresultnode anode, in unsigned long anewindex); ...
nsINavHistoryResultViewer
method overview void containerclosed(in nsinavhistorycontainerresultnode acontainernode); void containeropened(in nsinavhistorycontainerresultnode acontainernode); void invalidatecontainer(in nsinavhistorycontainerresultnode acontainernode); void nodeannotationchanged(in nsinavhistoryresultnode anode, in autf8string aannona
me); void nodedateaddedchanged(in nsinavhistoryresultnode anode, in prtime anewvalue); void nodelastaddedchanged(in nsinavhistoryresultnode anode, in prtime anewvalue); void nodehistorydetailschanged(in nsinavhistoryresultnode anode, in prtime anewvisitdate, in unsigned long anewaccesscount); void nodeiconchanged(in nsinavhistoryresultnode anode); voi...
nsIPermissionManager
last changed in gecko 16 (firefox 16 / thunderbird 16 / seamonkey 2.13) inherits from: nsisupports method overview void add(in nsiuri uri, in string type, in pruint32 permission, [optional] in pruint32 expiretype, [optional] in print64 expireti
me); void addfromprincipal(in nsiprincipal principal, in string type, in pruint32 permission, [optional] in pruint32 expiretype, [optional] in print64 expireti
me); void remove(in autf8string host, in string type); void removefromprincipal(in nsiprincipal principal, in string type); void removepermission(in nsipermission perm); void...
nsIPropertyBag
inherits from: nsisupports last changed in gecko 1.0 method overview nsivariant getproperty(in astring na
me); attributes attribute type description enumerator nsisimpleenumerator get a nsisimpleenumerator whose elements are nsiproperty objects.
nsIProtocolHandler
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview boolean allowport(in long port, in string sche
me); nsichannel newchannel(in nsiuri auri); nsiuri newuri(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); attributes attribute type description defaultport long the default port is the port the protocol uses by default.
AudioParam.setValueAtTime() - Web APIs
syntax var audioparam = audioparam.setvalueattime(value, startti
me) parameters value a floating point number representing the value the audioparam will change to at the given time.
AudioParam.value - Web APIs
const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); gainnode.gain.value = 0.4; //which is identical to: gainnode.gain.setvalueattime(0.4, audioctx.currentti
me); specifications specification status comment web audio apithe definition of 'value' in that specification.
AudioParam - Web APIs
var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currentti
me); compressor.knee.setvalueattime(40, audioctx.currentti
me); compressor.ratio.setvalueattime(12, audioctx.currentti
me); compressor.attack.setvalueattime(0, audioctx.currentti
me); compressor.release.setvalueattime(0.25, audioctx.currentti
me); specifications specification status comment web audio apithe definition of 'audioparam' in that specification.
AudioParamDescriptor - Web APIs
udiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode = new audioworkletnode(audiocontext, 'white-noise-processor') whitenoisenode.connect(audiocontext.destination) now we can change the gain on the node like this: const gainparam = whitenoisenode.parameters.get('customgain') gainparam.setvalueattime(0, audiocontext.currentti
me) gainparam.linearramptovalueattime(0.5, audiocontext.currenttime + 0.5) specifications specification status comment web audio apithe definition of 'audioparamdescriptor' in that specification.
AudioTrackList.getTrackById() - Web APIs
function disablecharacter(videoelem, characterna
me) { videoelem.audiotracks.gettrackbyid(characterna
me).enabled = false; } this short function gets the audiotracklist containing the video's audio tracks using htmlmediaelement.audiotracks, then calls gettrackbyid() on it, specifying the character's name.
AudioWorkletGlobalScope - Web APIs
// test-processor.js class testprocessor extends audioworkletprocessor { 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(currentfra
me) console.log(currentti
me) } // 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 declar...
AudioWorkletNode() - Web APIs
syntax var node = new audioworkletnode(context, na
me); var node = new audioworkletnode(context, name, options); parameters context the baseaudiocontext instance this node will be associated with.
AudioWorkletNode.parameters - Web APIs
udiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode = new audioworkletnode(audiocontext, 'white-noise-processor') whitenoisenode.connect(audiocontext.destination) now we can change the gain on the node like this: const gainparam = whitenoisenode.parameters.get('customgain') gainparam.setvalueattime(0, audiocontext.currentti
me) gainparam.linearramptovalueattime(0.5, audiocontext.currenttime + 0.5) specifications specification status comment web audio apithe definition of 'parameters' in that specification.
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
udiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode = new audioworkletnode(audiocontext, 'white-noise-processor') whitenoisenode.connect(audiocontext.destination) now we can change the gain on the node like this: const gainparam = whitenoisenode.parameters.get('customgain') gainparam.setvalueattime(0, audiocontext.currentti
me) gainparam.linearramptovalueattime(0.5, audiocontext.currenttime + 0.5) specifications specification status comment web audio apithe definition of 'parameterdescriptors' in that specification.
BaseAudioContext.createBiquadFilter() - Web APIs
connect the nodes together source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(biquadfilter); biquadfilter.connect(convolver); convolver.connect(gainnode); gainnode.connect(audioctx.destination); // manipulate the biquad filter biquadfilter.type = "lowshelf"; biquadfilter.frequency.setvalueattime(1000, audioctx.currentti
me); biquadfilter.gain.setvalueattime(25, audioctx.currentti
me); specifications specification status comment web audio apithe definition of 'createbiquadfilter()' in that specification.
BaseAudioContext.createChannelMerger() - Web APIs
var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume of the left channel only var gainnode = ac.creategain(); gainnode.gain.setvalueattime(0.5, ac.currentti
me); splitter.connect(gainnode, 0); // connect the splitter back to the second input of the merger: we // effectively swap the channels, here, reversing the stereo image.
BaseAudioContext.createChannelSplitter() - Web APIs
var ac = new audiocontext(); ac.decodeaudiodata(somestereobuffer, function(data) { var source = ac.createbuffersource(); source.buffer = data; var splitter = ac.createchannelsplitter(2); source.connect(splitter); var merger = ac.createchannelmerger(2); // reduce the volume of the left channel only var gainnode = ac.creategain(); gainnode.gain.setvalueattime(0.5, ac.currentti
me); splitter.connect(gainnode, 0); // connect the splitter back to the second input of the merger: we // effectively swap the channels, here, reversing the stereo image.
BaseAudioContext.createDynamicsCompressor() - Web APIs
// create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currentti
me); compressor.knee.setvalueattime(40, audioctx.currentti
me); compressor.ratio.setvalueattime(12, audioctx.currentti
me); compressor.attack.setvalueattime(0, audioctx.currentti
me); compressor.release.setvalueattime(0.25, audioctx.currentti
me); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribut...
BaseAudioContext.createOscillator() - Web APIs
// create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.type = 'square'; oscillator.frequency.setvalueattime(3000, audioctx.currentti
me); // value in hertz oscillator.connect(audioctx.destination); oscillator.start(); specifications specification status comment web audio apithe definition of 'createoscillator' in that specification.
BaseAudioContext.createStereoPanner() - Web APIs
create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a stereo panner var pannode = audioctx.createstereopanner(); // event handler function to increase panning to the right and left // when the slider is moved pancontrol.oninput = function() { pannode.pan.setvalueattime(pancontrol.value, audioctx.currentti
me); panvalue.innerhtml = pancontrol.value; } // connect the mediaelementaudiosourcenode to the pannode // and the pannode to the destination, so we can play the // music and adjust the panning using the controls source.connect(pannode); pannode.connect(audioctx.destination); specifications specification status comment web audio apithe definition of 'createstereopanner()'...
Document.lastModified - Web APIs
(see: bug 4363 – document.lastmodified returns date in utc time, but should return it in local ti
me) if you want to know whether an external page has changed, please read this paragraph about the xmlhttprequest() api.
Document.mozSetImageElement() - Web APIs
each time the function is called, the square is a different color (its red component is increased each ti
me), so each time the user clicks the element, the background is filled with a brighter and brighter pattern of red tiles.
DynamicsCompressorNode.attack - Web APIs
// create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currentti
me); compressor.knee.setvalueattime(40, audioctx.currentti
me); compressor.ratio.setvalueattime(12, audioctx.currentti
me); compressor.attack.setvalueattime(0, audioctx.currentti
me); compressor.release.setvalueattime(0.25, audioctx.currentti
me); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribut...
DynamicsCompressorNode.knee - Web APIs
// create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currentti
me); compressor.knee.setvalueattime(40, audioctx.currentti
me); compressor.ratio.setvalueattime(12, audioctx.currentti
me); compressor.attack.setvalueattime(0, audioctx.currentti
me); compressor.release.setvalueattime(0.25, audioctx.currentti
me); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribut...
DynamicsCompressorNode.ratio - Web APIs
// create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currentti
me); compressor.knee.setvalueattime(40, audioctx.currentti
me); compressor.ratio.setvalueattime(12, audioctx.currentti
me); compressor.attack.setvalueattime(0, audioctx.currentti
me); compressor.release.setvalueattime(0.25, audioctx.currentti
me); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribut...
DynamicsCompressorNode.release - Web APIs
// create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currentti
me); compressor.knee.setvalueattime(40, audioctx.currentti
me); compressor.ratio.setvalueattime(12, audioctx.currentti
me); compressor.attack.setvalueattime(0, audioctx.currentti
me); compressor.release.setvalueattime(0.25, audioctx.currentti
me); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribut...
DynamicsCompressorNode.threshold - Web APIs
// create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currentti
me); compressor.knee.setvalueattime(40, audioctx.currentti
me); compressor.ratio.setvalueattime(12, audioctx.currentti
me); compressor.attack.setvalueattime(0, audioctx.currentti
me); compressor.release.setvalueattime(0.25, audioctx.currentti
me); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribut...
DynamicsCompressorNode - Web APIs
// create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a compressor node var compressor = audioctx.createdynamicscompressor(); compressor.threshold.setvalueattime(-50, audioctx.currentti
me); compressor.knee.setvalueattime(40, audioctx.currentti
me); compressor.ratio.setvalueattime(12, audioctx.currentti
me); compressor.attack.setvalueattime(0, audioctx.currentti
me); compressor.release.setvalueattime(0.25, audioctx.currentti
me); // connect the audiobuffersourcenode to the destination source.connect(audioctx.destination); button.onclick = function() { var active = button.getattribut...
Element.getAttributeNames() - Web APIs
syntax let attributenames = element.getattributenames(); example // iterate over element's attributes for (let name of element.getattributenames()) { let value = element.getattribute(na
me); console.log(name, value); } polyfill if (element.prototype.getattributenames == undefined) { element.prototype.getattributenames = function () { var attributes = this.attributes; var length = attributes.length; var result = new array(length); for (var i = 0; i < length; i++) { result[i] = attributes[i].name; } return result; }; } specifications s...
TypeError: invalid 'instanceof' operand 'x' - JavaScript
message typeerror: invalid 'instanceof' operand "x" (firefox) typeerror: "x" is not a function (firefox) typeerror: right-hand side of 'instanceof' is not an object (chro
me) typeerror: right-hand side of 'instanceof' is not callable (chro
me) error type typeerror what went wrong?
TypeError: 'x' is not iterable - JavaScript
message typeerror: 'x' is not iterable (firefox, chro
me) typeerror: 'x' is not a function or its return value is not iterable (chro
me) error type typeerror what went wrong?
Default parameters - JavaScript
g = something()) { return thing } let numberoftimescalled = 0 function something() { numberoftimescalled += 1 return numberoftimescalled } callsomething() // 1 callsomething() // 2 earlier parameters are available to later default parameters parameters defined earlier (to the left) are available to later default parameters: function greet(name, greeting, message = greeting + ' ' + na
me) { return [name, greeting, message] } greet('david', 'hi') // ["david", "hi", "hi david"] greet('david', 'hi', 'happy birthday!') // ["david", "hi", "happy birthday!"] this functionality can be approximated like this, which demonstrates how many edge cases are handled: function go() { return ':p' } function withdefaults(a, b = 5, c = b, d = go(), e = this, ...
setter - JavaScript
when current is assigned a value, it updates log with that value: const language = { set current(na
me) { this.log.push(na
me); }, log: [] } language.current = 'en'; console.log(language.log); // ['en'] language.current = 'fa'; console.log(language.log); // ['en', 'fa'] note that current is not defined, and any attempts to access it will result in undefined.
AggregateError() constructor - JavaScript
examples creating an aggregateerror try { throw new aggregateerror([ new error("some error"), ], 'hello'); } catch (e) { console.log(e instanceof aggregateerror); // true console.log(e.message); // "hello" console.log(e.na
me); // "aggregateerror" console.log(e.errors); // [ error: "some error" ] } specifications specification promise.anythe definition of 'aggregateerror()' in that specification.
AggregateError - JavaScript
examples catching an aggregateerror promise.any([ promise.reject(new error("some error")), ]).catch(e => { console.log(e instanceof aggregateerror); // true console.log(e.message); // "all promises rejected" console.log(e.na
me); // "aggregateerror" console.log(e.errors); // [ error: "some error" ] }); creating an aggregateerror try { throw new aggregateerror([ new error("some error"), ], 'hello'); } catch (e) { console.log(e instanceof aggregateerror); // true console.log(e.message); // "hello" console.log(e.na
me); // "aggr...
Array.prototype.reduce() - JavaScript
or.concat(currentvalue) }, [] ) // flattened is [0, 1, 2, 3, 4, 5] alternatively written with an arrow function: let flattened = [[0, 1], [2, 3], [4, 5]].reduce( ( accumulator, currentvalue ) => accumulator.concat(currentvalue), [] ) counting instances of values in an object let names = ['alice', 'bob', 'tiff', 'bruce', 'alice'] let countednames = names.reduce(function (allnames, na
me) { if (name in allnames) { allnames[name]++ } else { allnames[name] = 1 } return allnames }, {}) // countednames is: // { 'alice': 2, 'bob': 1, 'tiff': 1, 'bruce': 1 } grouping objects by a property let people = [ { name: 'alice', age: 21 }, { name: 'max', age: 20 }, { name: 'jane', age: 20 } ]; function groupby(objectarray, property) { return objectarray.reduce(funct...
Array.prototype.filter() - JavaScript
8, 130, 44].filter(isbigenough) // filtered is [12, 130, 44] find all prime numbers in an array the following example returns all prime numbers in the array: const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log(array.filter(ispri
me)); // [2, 3, 5, 7, 11, 13] filtering invalid entries from json the following example uses filter() to create a filtered json of all elements with non-zero, numeric id.
Array.prototype.find() - JavaScript
quantity: 5 } find a prime number in an array the following example finds an element in the array that is a prime number (or returns undefined if there is no prime number): function isprime(element, index, array) { let start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].find(ispri
me)); // undefined, not found console.log([4, 5, 8, 12].find(ispri
me)); // 5 the following examples show that nonexistent and deleted elements are visited, and that the value passed to the callback is their value when visited: // declare array with no elements at indexes 2, 3, and 4 const array = [0,1,,,,5,6]; // shows all indexes, not just those with assigned values array.find(function(value, in...
Array.prototype.findIndex() - JavaScript
function isprime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } console.log([4, 6, 8, 9, 12].findindex(ispri
me)); // -1, not found console.log([4, 6, 7, 9, 12].findindex(ispri
me)); // 2 (array[2] is 7) find index using arrow function the following example finds the index of a fruit using an arrow function: const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"]; const index = fruits.findindex(fruit => fruit === "blueberries"); console.log(index); // 3 console.log(fruits[index]);...
Array.prototype.forEach() - JavaScript
function copy(obj) { const copy = object.create(object.getprototypeof(obj)) const propnames = object.getownpropertynames(obj) propnames.foreach((na
me) => { const desc = object.getownpropertydescriptor(obj, na
me) object.defineproperty(copy, name, desc) }) return copy } const obj1 = { a: 1, b: 2 } const obj2 = copy(obj1) // obj2 looks like obj1 now modifying the array during iteration the following example logs one, two, four.
Array.isArray() - JavaScript
var iframe = document.createelement('iframe'); document.body.appendchild(ifra
me); xarray = window.frames[window.frames.length-1].array; var arr = new xarray(1,2,3); // [1,2,3] // correctly checking for array array.isarray(arr); // true // considered harmful, because doesn't work through iframes arr instanceof array; // false specifications specification ecmascript (ecma-262)the definition of 'array.isarray' in that specification.
Array.prototype.some() - JavaScript
// production steps of ecma-262, edition 5, 15.4.4.17 // reference: http://es5.github.io/#x15.4.4.17 if (!array.prototype.so
me) { array.prototype.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)) {...
BigInt - JavaScript
(bigint(1)) // '"1"' examples calculating primes // returns true if passed bigint is a prime number function isprime(p) { for (let i = 2n; i * i <= p; i++) { if (p % i === 0n) return false; } return true } // takes a bigint as an argument, returns nth prime number as bigint function nthprime(nth) { let maybeprime = 2n let prime = 0n while (nth >= 0n) { if (isprime(maybepri
me)) { nth-- prime = maybeprime } maybeprime++ } return prime } nthprime(20n) // ↪ 73n specifications specification ecmascript (ecma-262)the definition of 'bigint objects' in that specification.
Date.prototype[@@toPrimitive] - JavaScript
examples returning date primitives const testdate = new date(1590757517834); // "date fri may 29 2020 14:05:17 gmt+0100 (british summer ti
me)" testdate[symbol.toprimitive]('string'); // returns "date fri may 29 2020 14:05:17 gmt+0100 (british summer ti
me)" testdate[symbol.toprimitive]('number'); // returns "1590757517834" testdate[symbol.toprimitive]('default'); // returns "date fri may 29 2020 14:05:17 gmt+0100 (british summer ti
me)" specifications specification ecmascript (ecma-262)the definition of 'date.proto...
Object.prototype.toSource() - JavaScript
for example: function person(na
me) { this.name = name; } person.prototype.tosource = function person_tosource() { return 'new person(' + uneval(this.na
me) + ')'; }; console.log(new person('joe').tosource()); // ---> new person("joe") built-in tosource() methods each core javascript type has its own tosource() method.
Proxy.revocable() - JavaScript
examples using proxy.revocable var revocable = proxy.revocable({}, { get: function(target, na
me) { return "[[" + name + "]]"; } }); var proxy = revocable.proxy; console.log(proxy.foo); // "[[foo]]" revocable.revoke(); console.log(proxy.foo); // typeerror is thrown proxy.foo = 1 // typeerror again delete proxy.foo; // still typeerror typeof proxy // "object", typeof doesn't trigger any trap specifications specification ecmascript (ec...
Proxy - JavaScript
var obj = object.create(base.prototype); this.apply(target, obj, args); return obj; }, apply: function(target, that, args) { sup.apply(that, args); base.apply(that, args); } }; var proxy = new proxy(base, handler); descriptor.value = proxy; object.defineproperty(base.prototype, 'constructor', descriptor); return proxy; } var person = function(na
me) { this.name = name; }; var boy = extend(person, function(name, age) { this.age = age; }); boy.prototype.gender = 'm'; var peter = new boy('peter', 13); console.log(peter.gender); // "m" console.log(peter.na
me); // "peter" console.log(peter.age); // 13 manipulating dom nodes sometimes you want to toggle the attribute or class name of two different elements.
Reflect.construct() - JavaScript
function oneclass() { this.name = 'one' } function otherclass() { this.name = 'other' } // calling this: let obj1 = reflect.construct(oneclass, args, otherclass) // ...has the same result as this: let obj2 = object.create(otherclass.prototype) oneclass.apply(obj2, args) console.log(obj1.na
me) // 'one' console.log(obj2.na
me) // 'one' console.log(obj1 instanceof oneclass) // false console.log(obj2 instanceof oneclass) // false console.log(obj1 instanceof otherclass) // true console.log(obj2 instanceof otherclass) // true //another example to demonstrate below: function func1(a, b, c, d) { console.log(arguments[3]); } function func2(d, e, f, g) { consol.log(arguments[3])...
TypedArray.prototype.find() - JavaScript
function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 = new uint8array([4, 5, 8, 12]); console.log(uint8.find(ispri
me)); // 5 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.find' in that specification.
TypedArray.prototype.findIndex() - JavaScript
function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 = new uint8array([4, 6, 8, 12]); var uint16 = new uint16array([4, 6, 7, 12]); console.log(uint8.findindex(ispri
me)); // -1, not found console.log(uint16.findindex(ispri
me)); // 2 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.findindex' in that specification.
TypedArray.prototype.some() - JavaScript
// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.some if (!uint8array.prototype.so
me) { object.defineproperty(uint8array.prototype, 'some', { value: array.prototype.some }); } if you need to support truly obsolete javascript engines that don't support object.defineproperty, it's best not to polyfill array.prototype methods at all, as you can't make them non-enumerable.
WebAssembly.CompileError() constructor - JavaScript
examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.na
me); // "compileerror" console.log(e.filena
me); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly con...
WebAssembly.CompileError - JavaScript
examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.na
me); // "compileerror" console.log(e.filena
me); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly con...
WebAssembly.LinkError() constructor - JavaScript
examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.na
me); // "linkerror" console.log(e.filena
me); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'linkerror' in that...
WebAssembly.LinkError - JavaScript
examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.na
me); // "linkerror" console.log(e.filena
me); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'linkerror' in that...
WebAssembly.RuntimeError() constructor - JavaScript
examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.na
me); // "runtimeerror" console.log(e.filena
me); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications specification webassembly javascript interfacethe definition of 'webassembly.run...